如何通过ethers获取EVM最新的10或20笔交易?
获取EVM最新交易(含Pending/已确认)的实现方案
1. 获取已确认的最新交易
要获取已上链的最新交易,可通过拉取最近区块的交易数据实现。使用getBlockWithTransactions方法能获取指定区块的所有交易,结合最新区块号即可拿到最新的已确认交易:
const url = "...some-node-or-alchemy-"; const provider = new ethers.providers.JsonRpcProvider(url); // 获取最新的N笔已确认交易哈希 async function getLatestConfirmedTxHashes(count = 20) { let txHashes = []; let latestBlockNumber = await provider.getBlockNumber(); // 从最新区块往前遍历,直到收集够指定数量的交易 for (let i = latestBlockNumber; i >= 0 && txHashes.length < count; i--) { const block = await provider.getBlockWithTransactions(i); if (block && block.transactions) { // 提取交易哈希,区块内最新交易在前 const blockTxHashes = block.transactions.map(tx => tx.hash).reverse(); txHashes.push(...blockTxHashes); } } return txHashes.slice(0, count); } // 调用示例 getLatestConfirmedTxHashes(20).then(hashes => console.log("已确认最新交易哈希:", hashes));
2. 结合Pending交易,获取全状态最新交易
如果要同时包含pending状态的未上链交易,可以维护一个集合存储pending交易哈希(避免重复监听),再和已确认交易合并:
const pendingTxHashes = new Set(); // 监听pending交易,去重存储 provider.on("pending", (txHash) => { pendingTxHashes.add(txHash); }); // 获取最新的N笔交易哈希(含pending) async function getLatestAllTxHashes(count = 20) { const confirmedHashes = await getLatestConfirmedTxHashes(count); // pending交易更新鲜,放在已确认交易前面 const allHashes = [...pendingTxHashes, ...confirmedHashes]; // 去重并截取指定数量 return [...new Set(allHashes)].slice(0, count); } // 定时刷新获取(示例:每5秒更新一次) setInterval(async () => { const latestHashes = await getLatestAllTxHashes(20); console.log("最新20笔交易哈希(含pending):", latestHashes); }, 5000);
补充说明
- 拿到交易哈希后,可通过
provider.getTransaction(txHash)获取完整交易对象,pending和已确认状态均支持查询。 - 控制区块遍历数量,避免给节点造成过大压力;部分节点服务(如Alchemy)支持批量查询,可进一步优化效率。
- 部分节点对pending交易仅返回哈希,无法获取完整交易详情,需根据节点能力调整逻辑。
内容的提问来源于stack exchange,提问作者delete
相关产品推荐
相关产品推荐

