Web3j:从智能合约中获取最后的事件
Web3j: Getting last events from a smart contract
我正在使用 org.web3j (4.8.4)
和 Java 11
。我在 Kovan 网络上部署了一个智能合约。我想订阅我调用 subscribe(...)
后发出的所有新事件。我对之前发出的事件不感兴趣。这是我当前的代码:
public void subscribeToEvents() throws Exception {
String wssUrl = "wss://kovan.infura.io/ws/v3/TOKEN";
String contractAddress = "0x123...";
// initialize web socket service
WebSocketService wss = new WebSocketService(wssUrl, false);
try {
wss.connect();
} catch (Exception e) {
System.out.println("Error while connecting to WSS service: " + e);
throw e;
}
// build web3j client
Web3j web3j = Web3j.build(wss);
// create filter for contract events
EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, contractAddress);
// subscribe to events
web3j.ethLogFlowable(filter).subscribe(event -> {
System.out.println("Event received");
System.out.println(event);
}, error -> {
System.out.println("Error: " + error);
});
}
但是,当我 运行 这段代码时,它还会打印几天前发生的旧事件。我如何更改代码,以便它只打印 new 事件,这些事件是在我调用 subscribe(...)
后由智能合约发出的?
正在替换
EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, contractAddress);
和
EthFilter filter = new EthFilter(DefaultBlockParameterName.LATEST, DefaultBlockParameterName.LATEST, contractAddress);
帮了我大忙。
我正在使用 org.web3j (4.8.4)
和 Java 11
。我在 Kovan 网络上部署了一个智能合约。我想订阅我调用 subscribe(...)
后发出的所有新事件。我对之前发出的事件不感兴趣。这是我当前的代码:
public void subscribeToEvents() throws Exception {
String wssUrl = "wss://kovan.infura.io/ws/v3/TOKEN";
String contractAddress = "0x123...";
// initialize web socket service
WebSocketService wss = new WebSocketService(wssUrl, false);
try {
wss.connect();
} catch (Exception e) {
System.out.println("Error while connecting to WSS service: " + e);
throw e;
}
// build web3j client
Web3j web3j = Web3j.build(wss);
// create filter for contract events
EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, contractAddress);
// subscribe to events
web3j.ethLogFlowable(filter).subscribe(event -> {
System.out.println("Event received");
System.out.println(event);
}, error -> {
System.out.println("Error: " + error);
});
}
但是,当我 运行 这段代码时,它还会打印几天前发生的旧事件。我如何更改代码,以便它只打印 new 事件,这些事件是在我调用 subscribe(...)
后由智能合约发出的?
正在替换
EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, contractAddress);
和
EthFilter filter = new EthFilter(DefaultBlockParameterName.LATEST, DefaultBlockParameterName.LATEST, contractAddress);
帮了我大忙。