You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用ethers.js V5监听已打包交易而非内存池pending交易?

解决ethers.js V5监听已打包交易的问题

在ethers.js V5中,监听已打包(mined)交易可以通过以下两种可靠方式实现:

方法1:监听transaction事件

该事件会在交易被成功打包进区块时触发,直接返回完整的交易对象,无需额外查询。适配你原有筛选逻辑的代码示例:

provider.on("transaction", async (tx) => {
  try {
    // 生成目标地址列表(过滤允许接收的未屏蔽地址)
    const targetAddresses = Object.keys(addresses)
      .filter(key => addresses[key].hasIncoming && !addresses[key].blocked)
      .map(addr => addr.toLowerCase());
    
    // 匹配发起地址
    if (targetAddresses.includes(tx.from.toLowerCase())) {
      console.log(`已打包交易:发起地址 ${tx.from},交易哈希 ${tx.hash},所在区块 ${tx.blockNumber}`);
    }
  } catch (error) {
    console.error("处理交易异常:", error);
  }
});

方法2:监听block事件并遍历区块交易

如果需要批量处理整个区块内的交易,可监听block事件,通过getBlockWithTransactions获取包含交易详情的区块对象,再筛选目标地址:

provider.on("block", async (blockNumber) => {
  try {
    const block = await provider.getBlockWithTransactions(blockNumber);
    const targetAddresses = Object.keys(addresses)
      .filter(key => addresses[key].hasIncoming && !addresses[key].blocked)
      .map(addr => addr.toLowerCase());
    
    // 遍历区块内所有交易
    block.transactions.forEach(tx => {
      if (targetAddresses.includes(tx.from.toLowerCase())) {
        console.log(`已打包交易:发起地址 ${tx.from},交易哈希 ${tx.hash},所在区块 ${blockNumber}`);
      }
    });
  } catch (error) {
    console.error("处理区块异常:", error);
  }
});

注意事项

  • transaction事件返回的交易对象中,blockNumber字段不为null,可用来区分已打包交易与内存池中的pending交易;
  • 若需监听目标地址的转入交易,只需将判断逻辑改为targetAddresses.includes(tx.to.toLowerCase())即可。

内容的提问来源于stack exchange,提问作者Zé Pedro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:05:21