首页 > 解决方案 > 使用 Web3.js 获取从特定地址收到的令牌总量

问题描述

在一个场景中,WalletA定期从AddressC接收TokenB。AddressC 只发送 TokenB,没有别的。

在 etherscan 或 bscscan 中,很容易查看 WalletA 中收到了多少 TokenB,并且存在“from”字段,因此您可以做一些数学运算来获得总数。

如何使用 web3 来做到这一点?我在 web3 文档中找不到任何相关的 api 调用。我可以通过 web3.js 获得 WalletA 中 TokenB 的总余额,但我需要仅从 AddressC 发送的令牌计数

谢谢。

标签: web3js

解决方案


根据ERC-20标准,每次代币传输都会发出一个Transfer()事件日志,其中包含发送者地址、接收者地址和代币数量。

web3js您可以使用通用方法web3.eth.getPastLogs()获取过去的事件日志,对输入进行编码并解码输出。

Transfer()或者您可以提供合同的 ABI JSON(在这种情况下仅使用事件定义就足够了)并使用web3js方法web3.eth.Contract.getPastEvents(),它根据提供的对输入进行编码并为您解码输出ABI JSON。

const Web3 = require('web3');
const web3 = new Web3('<provider_url>');

const walletA = '0x3cd751e6b0078be393132286c442345e5dc49699'; // sender
const tokenB = '0xdAC17F958D2ee523a2206206994597C13D831ec7'; // token contract address
const addressC = '0xd5895011F887A842289E47F3b5491954aC7ce0DF'; // receiver

// just the Transfer() event definition is sufficient in this case
const abiJson = [{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}];
const contract = new web3.eth.Contract(abiJson, tokenB);

const fromBlock = 10000000;
const toBlock = 13453500;
const blockCountIteration = 5000;

const run = async () => {
    let totalTokensTranferred = 0;

    for (let i = fromBlock; i <= (toBlock - blockCountIteration); i += blockCountIteration) {
        //console.log("Requesting from block", i, "to block ", i + blockCountIteration - 1);
        const pastEvents = await contract.getPastEvents('Transfer', {
            'filter': {
                'from': walletA,
                'to': addressC,
            },
            'fromBlock': i,
            'toBlock': i + blockCountIteration - 1,
        });
    }

    for (let pastEvent of pastEvents) {
        totalTokensTranferred += parseInt(pastEvent.returnValues.value);
    }

    console.log(totalTokensTranferred);
}

run();

推荐阅读