简体   繁体   中英

Web3j: Getting last events from a smart contract

I am using org.web3j (4.8.4) and Java 11 . I have a smart contract deployed on Kovan network. I want to subscribe to all new events emitted after I call 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(...) ?.

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.

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