Please check/provide contract events example with web3j.
I got stuck several days, for what should be straightforward: Getting smart contract events
/**
* Using Web3j .ethLogFlowable(filter).subscribe()
* that is sending eth_newFilter and eth_getfilterlogs/eth_getFilterChanges JSON RPC requests,
* see https://eth.wiki/json-rpc/API#eth_newfilter
* and https://eth.wiki/json-rpc/API#eth_getfilterlogs ,
* https://eth.wiki/json-rpc/API#eth_getfilterchanges
* @param contractAddress
*/
private void subscribeLogs(String contractAddress) {
log.info("subscribeLogs({}) begin...", contractAddress);
EthFilter filter = new EthFilter( // fromBlock, toBlock, contractAddress
//DefaultBlockParameterName.EARLIEST,DefaultBlockParameterName.LATEST, contractAddress);
DefaultBlockParameterName.LATEST, DefaultBlockParameterName.LATEST, contractAddress);
Disposable subscription = web3j
.ethLogFlowable(filter)
.subscribe(
logCounter
, errorCounter
, counterAction
);
subscriptions.add(subscription);
log.info("subscribeLogs() end.");
}
I was trying lambda and class like below for subscribe() Consumer parameter. With counter like below, I am more sure I have not missed event in output.
int logCount = 0;
// org.web3j.protocol.core.methods.response.Log
/**
* Log object used by {@link org.web3j.protocol.core.methods.response.EthLog}
* and {@link org.web3j.protocol.core.methods.response.EthGetTransactionReceipt}.
*/
class LogCounter implements Consumer<Log>{
@Override
public void accept(Log logObject) throws Exception {
logCount++;
log.info("log #{} {}", logCount, logObject);
}
}
LogCounter logCounter = new LogCounter();
The problem is that I can get no events at all. (While similar code for blocks and transactions just work, events for a smart contract are just silent. Of course I check contract address I am interesting, and send transaction)
Using
DefaultBlockParameterName.EARLIEST,DefaultBlockParameterName.LATEST, contractAddress); just gives NPE over JSON RPC error {"code":-32000,"message":"exceed maximum block range: 5000"}} #1486 So I only do latest blocks. I still wonder how to rescan older block events.
I am not using topic for filter hoping to see all but was also trying this
Event targetEventTopic = new Event("Withdraw", Arrays.asList(
new TypeReference<Address>() {},
new TypeReference<Uint256>() {},
new TypeReference<Uint256>() {}
));
filter.addSingleTopic(EventEncoder.encode(targetEventTopic));
```