web3 如何监听链上的交易数据 (pending状态)

使用的环境为 node + web3js + ganache

我设置了 ganache AUTOMINE 为 30s

我这里百度尝试了如下几种版本

1、使用 web3 pendingTransactions

subscription = web3.eth
    .subscribe("pendingTransactions", function (error, result) {})
    .on("data", function (transactionHash) {
      console.log("transactionHash: ", transactionHash);
      web3.eth.getTransaction(transactionHash).then(function (transaction) {
        console.log(transaction.from, transaction.to);
      });
    });

image.png

当我如图进行交易的时候,只有在 交易已确认的时候,才能正常输出。按照文档描述,不是应该在交易已提交的时候触发 输出

2、我使用 getPastLogs 方法,也只能获取到交易已确认的事件。

参考文档:https://www.wenjiangs.com/doc/idggx3ee

里面说 blockNumber – Number: 包含事件的块编号,处于pending状态时该字段为null

web3.eth.getPastLogs({
    fromBlock: 1,
    toBlock: "pending",
    address: contract,
    topics: [topic],
  });

但是,依旧,只有交易已确认的时候才能接受到日志

请问,我如何获取到 pending 事件呢

请先 登录 后评论

最佳答案 2021-11-29 23:27

可以确认 使用 getPastLogs 肯定是不行的。

方法 1不成功,可能是Ganache 没有很好处理 pendingTransactions 的问题,我查到一个类似的问题: https://github.com/trufflesuite/ganache/issues/405

你可以试试用 geth, 或者 infura 测试网络。

请先 登录 后评论

其它 0 个回答