web123456

Listening to smart contract events in springboot using web3j

package io.liqiangz.config; import io.liqiangz.contract.Trace; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.web3j.protocol.Web3j; import org.web3j.protocol.admin.Admin; import org.web3j.protocol.core.DefaultBlockParameter; import org.web3j.protocol.core.DefaultBlockParameterName; import org.web3j.protocol.core.Request; import org.web3j.protocol.core.methods.request; import org.web3j.protocol.core.methods.request.EthFilter; import org.web3j.protocol.core.methods.response.AnmoBlockNumber; import org.web3j.protocol.core.methods.response.EthBlockNumber; import org.web3j.protocol.core.methods.response.Web3ClientVersion; import org.web3j.protocol.http.HttpService; import org.web3j.tx.ClientTransactionManager; import org.web3j.tx.ManagedTransaction; import org.web3j.tx.TransactionManager; import java.io.IOException; import java.math.BigInteger; /** * Intelligent contracts */ @Configuration public class ContractConfig { //Smart Contract Deployment Address private String contractAddress = "0xaf0895260ef377ceea0086c99e3eff7999f742c9"; @Bean @Scope("prototype") public Web3j web3j() { return Web3j.build(new HttpService("http://192.168.0.104:15450")); } @Bean @Autowired public Trace trace(Web3j web3j) throws IOException { Trace contract; try { Web3ClientVersion web3ClientVersion = web3j.web3ClientVersion().send(); String clientVersion = web3ClientVersion.getWeb3ClientVersion(); System.out.println("clientVersion" + clientVersion); // Invoke the contract as a user TransactionManager transactionManager = new ClientTransactionManager(web3j, "0x24602722816b6cad0e143ce9fabf31f6026ec622"); //Load Smart Contracts contract = Trace.load(contractAddress, web3j, transactionManager, ManagedTransaction.GAS_PRICE, org.web3j.tx.Contract.GAS_LIMIT); return contract; } catch (Exception e) { e.printStackTrace(); throw e; //throw new RRException("Connection to smart contract exception");; } } @Bean //Listening is only used here to generate a new object each time, because you can't use the same instance to listen to multiple events at the same time. @Scope("prototype") @Autowired public EthFilter ethFilter(Trace trace, Web3j web3j) throws IOException { //Get the block listening on startup Request<?, EthBlockNumber> request = web3j.ethBlockNumber(); BigInteger fromblock = request.send().getBlockNumber(); return new EthFilter(DefaultBlockParameter.valueOf(fromblock), // If you can't listen to the address here, you can remove the 0x. DefaultBlockParameterName.LATEST, trace.getContractAddress()); } }