使用web3J是否可以收听infura事件?
我正在尝试获取事件,但出现错误
Caused by: org.web3j.protocol.core.filters.FilterException: Invalid request: The method eth_newFilter does not exist/is not available
at org.web3j.protocol.core.filters.Filter.throwException(Filter.java:172)
at org.web3j.protocol.core.filters.Filter.run(Filter.java:53)
at org.web3j.protocol.rx.JsonRpc2_0Rx.run(JsonRpc2_0Rx.java:73)
at org.web3j.protocol.rx.JsonRpc2_0Rx.lambda$ethLogFlowable$2(JsonRpc2_0Rx.java:65)
at io.reactivex.internal.operators.flowable.FlowableCreate.subscribeActual(FlowableCreate.java:71)
... 9 more```
# This is java wrappeer function generated by web3j maven plugin
public Flowable<PunkOfferedEventResponse> punkOfferedEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());
filter.addSingleTopic(EventEncoder.encode(PUNKOFFERED_EVENT));
return punkOfferedEventFlowable(filter);
}
public static class PunkOfferedEventResponse {
public Log log;
public BigInteger punkIndex;
public String toAddress;
public BigInteger minValue;
}
# This is the caller which subscribe to punkOfferedEventFlowable andd it should iddeally return events in stream fashion
Web3j web3j = Web3j.build(new HttpService(""));
Web3ClientVersion web3ClientVersion = web3j.web3ClientVersion().send();
Credentials credentials = Credentials.create("");
CryptoPunksMarket contract = CryptoPunksMarket.load("",web3j,credentials,new DefaultGasProvider()); contract.punkOfferedEventFlowable(null)
.doOnError(error -> error.printStackTrace())
.subscribe(event -> {
BigInteger index = event.punkIndex;
System.out.println("Index:"+index);
}).dispose();
我在不同的博客中读到,无法使用web3J获取过滤的事件,那么,使用web3J和infura来获取过滤的事件有哪些替代方法呢?
最佳答案
您必须从日志中读取事件。 Web3j提供了一种方法ethGetLogs
,该方法将ethFilter对象作为参数并响应事件日志列表。
对于您的请求将是这样的:
EthFilter ethFilter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, contract.getContractAddress());
ethFilter.addSingleTopic(EventEncoder.encode(CryptoPunksMarket.PUNK_OFFERED_EVENT));
EthLog ethLog = web3j.ethGetLogs(ethFilter).send();
关于java - web3J与infura的兼容性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57835680/