簡體   English   中英

監聽Web3j中的事件

[英]Listening to events in Web3j

我正在修補web3j和我想成功完成的大多數事情,但是我似乎無法收聽事件。

我通過添加事件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();
}
...

我能夠在Web3j中部署此合同並進行投票等。 然后我添加了一個過濾器來收聽VoteEnded。 我這樣做:

    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());
        }
    });

但是,這根本不打印任何內容。

我究竟做錯了什么?

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

當偵聽基於本地松露的節點時,我必須添加.substring(2):

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

其次,您可能需要使用

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

您所遇到的事件應該看起來像什么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM