Web3j events

In the smart contract, we have defined a few events. Each one will be represented in the smart contract wrapper with a method named identically, which takes the transaction receipt and returns a decoded result (event parameters) in an instance of the EventValues object. Given that, here's how to get the event data and display its content in our console:

for (CFutures.DepositEvEventResponse event : CFutureInstance.getDepositEvEvents(DepositReceipt)) {
log.info("Depoist event detected:" + event.amount+"wei has been deposited");
    log.info("The funds has been sent by: " + event.sender);
}

Alternatively, you can use Observables (RxJava's observables), which will listen for events associated with the smart contract. Then use an EthFilter object to filter your observable, as follows:

EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, 
DefaultBlockParameterName.LATEST, CFutureInstance.getContractAddress());
web3j.ethLogObservable(filter).subscribe(Clog -> {
log.info("contract log"+ Clog.toString());
});

For EthFilter, we specify the topics that we wish to apply to the filter, including the contract address. We can also provide specific topics (only for indexed Solidity event parameters) to filter using: filter.addSingleTopic(EventEncoder.encode(event));

At the time of writing, listening for events (filters/subscriptions) is supported by Infura only using websocket endpoints on mainnet, Ropsten, and Rinkeby. However, web3j doesn't yet support websockets, so we can't use filters in web3j while using Infura.

This was the last web3J feature we needed to cover in this chapter – it's time to test the code. Grab the full code from https://github.com/bellaj/web3j.git  and then import and run the project in Eclipse.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset