工作 web3j.replayTransactionsObservable 示例

Working web3j.replayTransactionsObservable example

我想检索 2 个区块之间的交易历史,我发现了这个重放过滤器 要重播包含在一个区块范围内的单个交易:

Subscription subscription = web3j.replayTransactionsObservable( <startBlockNumber>, <endBlockNumber>) .subscribe(tx -> { ... });

但是,我找不到与此过滤器相关的任何工作示例。任何人都可以帮助提供一个工作示例吗?

访问交易对象非常简单:

Web3j web3j = Web3j.build(new HttpService());

web3j.replayTransactionsObservable(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST).subscribe(System.out::println));

将打印出您本地主机上对等节点 运行 上发生的所有交易。只需将 System.out::println 更改为 tx -> //do something with txtxorg.web3j.protocol.core.methods.response.EthBlock$TransactionObject)。

请注意,这只会重播历史记录。当块被添加到链中时,您不会看到任何新的交易对象。

如果你想做一些事情,比如监听发出的特定事件,就会出现一个更复杂的使用订阅的例子。如果有帮助,我在下面包含了一个示例。如果您在特定问题上需要帮助,请 post 提出问题并提供更多详细信息和示例代码。

// Prints event emitted from a deployed contract
// Event definition:
// event MyEvent(address indexed _address, uint256 _oldValue, uint256 _newValue);
public static void eventTest() {
  try {
    Web3j web3j = Web3j.build(new HttpService());

    Event event = new Event("MyEvent",
                            Arrays.asList(new TypeReference<Address>() {}),
                            Arrays.asList(new TypeReference<Uint256>() {}, new TypeReference<Uint256>() {}));

    // Note contract address here. See https://github.com/web3j/web3j/issues/405
    EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, "6dd7c1c13df7594c27e0d191fd8cc21efbfc98b4");

    filter.addSingleTopic(EventEncoder.encode(event));

    web3j.ethLogObservable(filter).subscribe(log -> System.out.println(log.toString()));
  }
  catch (Throwable t) {
    t.printStackTrace();
  }
}