如何使用web3.py获取内存池中未确认交易的详情?filter('pending').get_all_entries方法失效
用web3.py获取区块链内存池未确认交易的解决方案
我之前也碰到过用filter('pending').get_all_entries()无效的问题,主要原因是大部分节点(尤其是第三方节点比如Infura免费层)默认不支持通过这个接口查询所有pending交易,而且web3.py的这个方法对pending过滤器的兼容性也不太好。下面给你两个靠谱的解决方案:
方法一:直接查询所有未确认交易
使用web3.py封装的w3.eth.get_pending_transactions()方法,这个方法对应以太坊RPC的eth_getPendingTransactions调用,只要你的节点支持这个RPC方法,就能直接拿到内存池里的所有pending交易。
示例代码
from web3 import Web3 # 连接到支持pending交易查询的节点(本地节点或付费第三方节点) w3 = Web3(Web3.HTTPProvider('http://localhost:8545')) # 先确认节点连接正常 if not w3.is_connected(): raise Exception("节点连接失败,请检查节点配置或URL") # 获取内存池中的所有未确认交易 pending_transactions = w3.eth.get_pending_transactions() # 遍历打印交易详情 for tx in pending_transactions: print(f"交易哈希: {w3.to_hex(tx['hash'])}") print(f"发送方: {tx['from']}") print(f"接收方: {tx['to'] if tx['to'] else '合约创建交易'}") print(f"金额 (ETH): {w3.from_wei(tx['value'], 'ether'):.6f}") print(f"燃气价格 (Gwei): {w3.from_wei(tx['gasPrice'], 'gwei'):.2f}") print(f"燃气上限: {tx['gas']}") print("-" * 50)
方法二:实时监听新的未确认交易
如果你需要实时获取刚进入内存池的交易,可以用pending过滤器结合轮询的方式,这种方式更适合监控场景:
示例代码
from web3 import Web3 import time w3 = Web3(Web3.HTTPProvider('http://localhost:8545')) if not w3.is_connected(): raise Exception("节点连接失败") # 创建pending交易过滤器 pending_filter = w3.eth.filter('pending') print("开始监听新的pending交易...") while True: # 获取过滤器创建后新增的交易哈希 new_tx_hashes = pending_filter.get_new_entries() if new_tx_hashes: for tx_hash in new_tx_hashes: # 根据哈希获取完整交易详情 tx = w3.eth.get_transaction(tx_hash) print(f"\n新pending交易: {w3.to_hex(tx_hash)}") print(f"发送方: {tx['from']}") print(f"金额: {w3.from_wei(tx['value'], 'ether'):.6f} ETH") # 每隔2秒轮询一次,可根据需求调整间隔 time.sleep(2)
关键注意事项
- 节点支持性:第三方免费节点(比如Infura免费版)通常不开放
eth_getPendingTransactions接口,建议自己运行本地Geth/OpenEthereum节点,或者使用付费的节点服务。本地Geth启动时可以加上--txpool.globalslots=10000来确保内存池有足够容量存储pending交易。 - 交易字段说明:如果
tx['to']为None,说明这是一笔合约创建交易,tx['input']字段是合约的部署字节码。 - 版本兼容性:确保你的web3.py版本是最新的(可以用
pip install --upgrade web3升级),旧版本可能存在接口兼容问题。
内容的提问来源于stack exchange,提问作者Ivan
相关产品推荐
相关产品推荐

