简体   繁体   English

Web3j:从智能合约中获取最新事件

[英]Web3j: Getting last events from a smart contract

I am using org.web3j (4.8.4) and Java 11 .我正在使用org.web3j (4.8.4)Java 11 I have a smart contract deployed on Kovan network.我在 Kovan 网络上部署了一个智能合约。 I want to subscribe to all new events emitted after I call subscribe(...) .我想订阅调用subscribe(...)后发出的所有新事件。 I am not interested in events that were emitted before.我对之前发出的事件不感兴趣。 This is my current code:这是我当前的代码:

public void subscribeToEvents() throws Exception {
    String wssUrl = "wss://kovan.infura.io/ws/v3/TOKEN";
    String contractAddress = "0x123...";
    
    // initialize web socket service
    WebSocketService wss = new WebSocketService(wssUrl, false);
    try {
        wss.connect();
    } catch (Exception e) {
        System.out.println("Error while connecting to WSS service: " + e);
        throw e;
    }

    // build web3j client
    Web3j web3j = Web3j.build(wss);

    // create filter for contract events
    EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, contractAddress);

    // subscribe to events
    web3j.ethLogFlowable(filter).subscribe(event -> {
        System.out.println("Event received");
        System.out.println(event);
    }, error -> {
        System.out.println("Error: " + error);
    });
}

However, when I run this code, it also prints old events which occurred few days ago.但是,当我运行此代码时,它还会打印几天前发生的旧事件。 How can I change the code so that it only prints new events which are emitted by smart contract after I call subscribe(...) ?.如何更改代码,使其仅在我调用subscribe(...)后打印智能合约发出的事件?

Replacing更换

EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, contractAddress);

with

EthFilter filter = new EthFilter(DefaultBlockParameterName.LATEST, DefaultBlockParameterName.LATEST, contractAddress);

did the job for me.为我完成了这项工作。

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

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