web3j监听智能合约的event事件

假设智能合约中定义了一个事件:

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.>asList(new TypeReference
() {}), Arrays.>asList(new TypeReference
() {})); EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, contract_addr); filter.addSingleTopic(EventEncoder.encode(event)); getWeb3jClient().ethLogObservable(filter).subscribe(new Action1() { @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.>asList(new TypeReference
() {}), Arrays.>asList(new TypeReference
() {}));
否则事件监听会失败。





你可能感兴趣的:(区块链)