Web3j: Getting last events from a smart contract
Asked Answered
L

1

6

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(...)?.

Laurasia answered 21/5, 2021 at 17:39 Comment(2)
There is a JSON-RPC call to get the past events, but I do not know what API calls it map on Web3j.Fairy
I am not interested in past events, I want to subscribe to new events only.Laurasia
L
4

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.

Laurasia answered 26/5, 2021 at 10:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.