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

使用Ethers.js无法获取以太坊钱包交易日志,请求协助解决

问题原因

provider.getLogs() 是用来查询合约事件日志的接口,仅能返回合约主动触发的事件记录。你传入的是普通外部账户(EOA)地址,这类账户不会触发合约事件,所以返回空数组是正常的。要获取钱包的交易记录,需要用专门的交易查询逻辑。

解决方案

方法1:遍历区块筛选交易(适合小范围区块查询)

通过遍历指定区块范围,逐个获取区块内的交易,筛选出from或to为目标钱包地址的交易。示例代码:

import { ethers } from "ethers";

const endpointURL = "https://mainnet.infura.io/v3/8e9f219935524dd7ac8a469c9367c4b7";
const provider = new ethers.JsonRpcProvider(endpointURL);

const currentBlockNumber = await provider.getBlockNumber();
const startBlockNumber = 18908894;
const walletAddress = "0x6843a2F81aCc7f5903359230E54E667703416DD4";

const walletTransactions = [];

// 注意:大范围区块遍历会非常慢,建议分批次处理
for (let blockNum = startBlockNumber; blockNum <= currentBlockNumber; blockNum++) {
  const block = await provider.getBlockWithTransactions(blockNum);
  if (block && block.transactions) {
    const filtered = block.transactions.filter(tx => 
      tx.from.toLowerCase() === walletAddress.toLowerCase() || 
      tx.to?.toLowerCase() === walletAddress.toLowerCase()
    );
    walletTransactions.push(...filtered);
  }
  // 每处理100个区块打印进度,避免无响应
  if (blockNum % 100 === 0) {
    console.log(`Processed block ${blockNum}`);
  }
}

console.log("Wallet transactions:", walletTransactions);

注意:如果区块范围过大(比如跨数十万区块),这种方法效率极低,不建议直接使用。

方法2:使用节点服务商的扩展RPC接口(高效查询)

部分节点服务商提供了扩展RPC方法,可以直接查询钱包的交易记录,无需遍历区块。以alchemy_getAssetTransfers为例(需使用对应服务商的节点地址):

import { ethers } from "ethers";

const endpointURL = "你的对应服务商节点地址";
const provider = new ethers.JsonRpcProvider(endpointURL);

const walletAddress = "0x6843a2F81aCc7f5903359230E54E667703416DD4";
const startBlockNumber = 18908894;

const transactions = await provider.send("alchemy_getAssetTransfers", [
  {
    fromBlock: ethers.toHex(startBlockNumber),
    toBlock: "latest",
    fromAddresses: [walletAddress],
    toAddresses: [walletAddress],
    category: ["external", "internal", "erc20", "erc721", "erc1155"]
  }
]);

console.log("Wallet transactions:", transactions.transfers);

方法3:利用区块索引服务

通过区块链浏览器的API可以快速查询钱包交易记录,无需自行遍历区块。调用时只需传入钱包地址和区块范围参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:12:46