简体   繁体   中英

Listening to events in Web3j

I'm tinkering with web3j and most of the things that I want to do succeed, however I seem to not be able to listen to events.

I've extended the ballot.sol contract you get with remix by adding an event VoteEnded, which is fired when a call is made to winningProposal and that works in the Remix JavaScript VM.

...
event VoteEnded();
...

function winningProposal() constant returns (uint8 winningProposal) {
    uint256 winningVoteCount = 0;
    for (uint8 proposal = 0; proposal < proposals.length; proposal++)
        if (proposals[proposal].voteCount > winningVoteCount) {
            winningVoteCount = proposals[proposal].voteCount;
            winningProposal = proposal;
        }
    VoteEnded();
}
...

I am able to deploy this contract and vote etc. in Web3j. Then I added a filter to listen to VoteEnded. I did it like:

    EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, contract.getContractAddress());
    web3.ethLogObservable(filter).subscribe(new Action1<Log>() {
        @Override    
        public void call(Log log) {
            System.out.println("log.toString(): " +  log.toString());
        }
    });

However this doesn't print anything at all.

What am I doing wrong?

您需要添加filter.addSingleTopic(EventEncoder.encode(event)) ,其中event是实例化的org.web3j.abi.datatypes.Event对象。

When listening to a local truffle based node I had to add .substring(2):

EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, contract.getContractAddress().substring(2);

Second, you probably need to use

    String encodedEventSignature = EventEncoder.encode(event);
    filter.addSingleTopic(encodedEventSignature);

Where event in your case should look like

new Event("VoteEnded", 
            Arrays.<TypeReference<?>>asList(), Arrays.<TypeReference<?>>asList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM