使用 Web3.js 获取从特定地址收到的代币总量

mhm*_*hmd 5 web3js

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

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

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

谢谢。

Pet*_*jda 3

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

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

或者,您可以提供合约的 ABI JSON(Transfer()在本例中仅使用事件定义就足够了)并使用方法web3jsweb3.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();
Run Code Online (Sandbox Code Playgroud)