0

I want to listen to event Sync from a contract.

In javascript, I managed like this (this is to understand better what I want):

const contract = new web3.eth.Contract(abi, contractAddress);

const syncEvent = contract.events["Sync"];

syncEvent().on('data', function(event){
    console.log(event);
}).on('error', function(error){
    console.log(error)
}).on("changed", function(isSyncing){
    console.log(isSyncing);
});

In java I managed only this:

Web3j web3jWS = Web3j.build(new WebSocketService("wss://...", false));

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

But I have no idea how to continue this, even if it's right my code.

How I can listen to the event Sync with Web3j?

4
  • How are you fetching the contract address? Also I think your filter will want to change the first DefaultBlockParameterName.LATEST, to DefaultBlockParameterName.EARLIEST,. Commented Dec 7, 2022 at 16:39
  • @ruby_newbie The contractAddress is a string in my code String contractAddress = "0x2b4c76d0dc16be1c31d4c1dc53bf9b45987fc75c" . It's from Fantom Blockchain.
    – KunLun
    Commented Dec 7, 2022 at 16:50
  • Did you try removing the 0x prefix from the address? Commented Dec 7, 2022 at 17:09
  • @ruby_newbie It's pointless since my code is not completely.
    – KunLun
    Commented Dec 7, 2022 at 17:18

1 Answer 1

1
    try {
        WebSocketService ws = new WebSocketService("ws://node-01:8545", true);
        ws.connect();
        Web3j web3 = Web3j.build(ws);
        EthFilter filter = new EthFilter(
            DefaultBlockParameter.valueOf(BigInteger.ZERO),
            DefaultBlockParameter.valueOf("latest"),
            contractAddress     
        );          
        web3.ethLogFlowable(filter)
            .onExceptionResumeNext( Flowable.empty() )
            .subscribe( log -> {
                
                System.out.println("EVENT !!!");
                System.out.println( log.getData() );
                
            }, error -> {
                System.out.println( error.getMessage() );
            }
        );          
        
    } catch (Exception e) {
        e.printStackTrace();
    }
1
  • Just be careful of setting from zero to latest filter range. I'm doing this on my private chain.
    – Magno C
    Commented Aug 9 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.