0
  1. What is the appropriate way to handle live events (i.e. service/component should keep on listening to events and save it to offchain db (h2/postgres))
  2. How to close event subscription gracefully?

Implementation tried so far:

@Component
public class ERC20Listener implements Listener {


    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * Do something useful with the state update received
     */
    @Override
    @PostConstruct
    public void listen() throws Exception {
        Web3j web3j = null;
        Disposable flowableEvent = null;

        try {
            WebSocketService web3jService = new WebSocketService("ws://", true);
            web3jService.connect();
            web3j = Web3j.build(web3jService);

            ERC20Token token= ... //creating contract instance
            flowableEvent = token.transferEventFlowable(DefaultBlockParameterName.LATEST, DefaultBlockParameterName.LATEST)
                    .subscribe(event -> {
                        try {
                            System.out.printf("hash=%s from=%s to=%s amount=%s%n",
                                    event.log.getTransactionHash(),
                                    event.from,
                                    event.to,
                                    event.value);
                            //process event data save to offchain db ==> service call
                        }catch(Throwable e) {
                            e.printStackTrace();
                        }
                    });
        } catch (Exception e) {
            logger.error("Unknown Exception " + e.getMessage());
            throw new Exception(e.getMessage());
        } finally {
            web3j.shutdown();
            flowableEvent.dispose();
        }
    }
}
Vineeta
  • 85
  • 1
  • 11

0 Answers0