【问题标题】:Working web3j.replayTransactionsObservable example工作 web3j.replayTransactionsObservable 示例
【发布时间】:2018-09-26 17:47:59
【问题描述】:

我想检索 2 个区块之间的交易历史,我遇到了这个重播过滤器 要重放一系列区块中包含的单个交易:

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

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

【问题讨论】:

    标签: java blockchain ethereum web3-java


    【解决方案1】:

    简单地访问事务对象非常简单:

    Web3j web3j = Web3j.build(new HttpService());
    
    web3j.replayTransactionsObservable(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST).subscribe(System.out::println));
    

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

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

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

    // 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();
      }
    }
    

    【讨论】:

    • 其实我只想要 2 个特定区块之间的交易细节,比如说区块号 500 和 600。我使用了这段代码 Web3j webj = Web3j.build(new HttpService()); webj.replayTransactionsObservable(new DefaultBlockParameterNumber(500), new DefaultBlockParameterNumber(600)) .subscribe(tx -> System.out.println(tx.getBlockNumber()+" "+tx.getHash() + "" + tx.getTo( )));但它不是从所需的块号开始的。我哪里错了?
    • 您在输出中看到了什么?我已经使用 Ganache 对一个块范围进行了测试,它工作得很好。如果您使用的是其中一个测试网络而不是 Ganache,则需要确保您的节点已完全同步。
    • 我使用的是 geth 测试网。不过,我也会尝试使用 ganache 并在此处更新。
    • 我可以通过下载 ganache 并连接我的 dapp 来连接以太坊主网吗?因为我想查询实际的以太坊区块链。
    • 你不会为此使用 Ganache。您使用它来运行开发节点(使用它比使用测试网更快,因为它会立即挖掘交易)。要使用主网,您将使用完全同步的客户端节点(可以使用 Geth 或 Parity),或者使用 Infura 之类的提供程序。不过,有些提供商在功能上存在限制。
    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 2011-07-02
    • 2016-11-09
    • 2010-10-02
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多