NO IMAGE

假設智慧合約中定義了一個事件:

pragma solidity ^0.4.0;
contract Transfer{
event transfer(address indexed _from, address indexed _to, uint indexed value);
function deposit() payable {
address current = this;
uint value = msg.value;
transfer(msg.sender, current, value);
}
function getBanlance() constant returns(uint) {
return this.balance;
}
/* fallback function */
function(){}
}

在web3j端對該事件的監聽方法為:

void listenEvent()
{
Event event = new Event("transfer",
Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}),
Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}));
EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST,
DefaultBlockParameterName.LATEST, contract_addr);
filter.addSingleTopic(EventEncoder.encode(event));
getWeb3jClient().ethLogObservable(filter).subscribe(new Action1<Log>() {
@Override
public void call(Log log) {
System.println(log.toString());
}
});
}

注意,因為智慧合約中transfer事件的定義形式是

event transfer(address indexed _from, address indexed _to, uint indexed value);

所以在web3j定義event的時候要對應上:

Event event = new Event("transfer",
Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}),
Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}));

否則事件監聽會失敗。