简体   繁体   English

监听Web3j中的事件

[英]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. 我正在修补web3j和我想成功完成的大多数事情,但是我似乎无法收听事件。

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. 我通过添加事件VoteEnded扩展了通过remix获得的ballot.sol合同,该事件在调用winningProposal时触发,并且在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. 我能够在Web3j中部署此合同并进行投票等。 Then I added a filter to listen to VoteEnded. 然后我添加了一个过滤器来收听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): 当侦听基于本地松露的节点时,我必须添加.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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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