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

如何使用Web3Py查询指定地址的pending(待处理)交易?

如何用Web3Py查询BSC链指定地址的待处理(pending)交易

现有代码的核心问题

  • w3.eth.filter('latest')本身获取的是最新已打包区块的交易哈希,完全不涉及待处理交易,属于参数理解错误
  • 多数公共BSC RPC节点为了控制性能开销,不支持自定义fromBlock='pending'级别的地址过滤器,会自动将查询逻辑降级为查询已确认区块的交易,因此会拿到已经打包完成的结果

可行的解决方案

方案1:全量拉取待处理交易后本地筛选(兼容所有公共RPC节点)

此方案不需要RPC节点支持自定义pending过滤,适配性最高:

from web3 import Web3

# 初始化Web3连接
w3 = Web3(Web3.HTTPProvider('你的BSC RPC节点地址'))

target_address = "0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56".lower()
target_pending_txs = []

# 拉取所有pending交易哈希
pending_tx_hashes = w3.eth.filter('pending').get_all_entries()

for tx_hash in pending_tx_hashes:
    try:
        # 获取交易详情
        tx = w3.eth.get_transaction(tx_hash)
        # 可按需匹配转出地址/转入地址
        if (tx['from'].lower() == target_address) or (tx.get('to') and tx['to'].lower() == target_address):
            target_pending_txs.append(tx)
    except Exception:
        # 部分刚进入内存池的交易可能还未同步到节点详情,直接跳过即可
        continue

如果RPC节点有请求频率限制,可以在遍历逻辑中增加少量延迟避免触发限流。

方案2:实时订阅pending交易(适合有高性能/付费RPC节点的场景)

如果需要持续监听目标地址的待处理交易,可以用增量订阅的方式降低请求量:

import time
from web3 import Web3

w3 = Web3(Web3.HTTPProvider('你的BSC RPC节点地址'))
target_address = "0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56".lower()

# 初始化pending交易过滤器
pending_filter = w3.eth.filter('pending')

while True:
    # 只拉取上次查询后新增的pending交易哈希
    new_tx_hashes = pending_filter.get_new_entries()
    for tx_hash in new_tx_hashes:
        try:
            tx = w3.eth.get_transaction(tx_hash)
            if (tx['from'].lower() == target_address) or (tx.get('to') and tx['to'].lower() == target_address):
                print(f"捕获目标待处理交易:{tx.hash.hex()}")
                # 此处可添加你自己的交易处理逻辑
        except Exception:
            pass
    time.sleep(1)

内容的提问来源于stack exchange,提问作者kapisolec

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 15:15:02