监听合约Tranfer事件
调用代码 private void run1() throws Exception {
log.info("hello eth,hello web3j");
Web3j web3j = Web3jInfo.connect();
// BigInteger total = TokenClient.getTokenTotalSupply(web3j, "0xff9c1b15b16263c61d017ee9f65c50e4ae0113d7");
// System.out.println("loot(0xff9c1b15b16263c61d017ee9f65c50e4ae0113d7) total:" + total);
TransMonitor.getInstance().setWeb3j(web3j);
TransMonitor.getInstance().subscribeContract("0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", new Action1<Log>() {
@Override
public void call(Log log) {
System.out.println("transBlockNo:" + log.getBlockNumber());
System.out.println("transHash:" + log.getTransactionHash());
List<String> topics = log.getTopics();
for (String topic : topics) {
System.out.println("transTopic:" + topic);
}
}
});
}
核心代码实现在这里
/**
* 监听合约的交易事件
**/
public Subscription subscribeContract(String contractAddress, final Action1<? super Log> onNext) {
if (this.web3j == null) return null;
// 要监听的合约事件 交易
EthFilter filter = new EthFilter(
DefaultBlockParameter.valueOf(BigInteger.valueOf(13763721L)),
DefaultBlockParameterName.LATEST,
contractAddress);
Event event = new Event("Transfer",
Arrays.<TypeReference<?>>asList(
new TypeReference<Address>(true) {
},
new TypeReference<Address>(true) {
},
new TypeReference<Uint256>(false) {
}));
filter.addSingleTopic(EventEncoder.encode(event));
return web3j.ethLogObservable(filter).subscribe(onNext);
}
public void unsubscribeContract(Subscription subscription) {
if (this.web3j == null) return;
subscription.unsubscribe();
}
之前实验全量区块,导致请求多次失败,是由于个人RPC节点的请求和数据有限,为了测试出结果,从13763721L block到当前,结果毫秒级返回成功。
Transfer包含的3个参数
所以由此扩展,所有合约的Event 都可以按照此方法进行构造和监听。
项目github地址https://github.com/jambestwick/we3jdemo
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)