gpt4 book ai didi

web3js - 使用 Web3.js 获取从特定地址收到的 token 总量

转载 作者:行者123 更新时间:2023-12-04 12:27:24 26 4
gpt4 key购买 nike

在一个场景中,钱包A 正在接收 代币B 定期从 地址C .
AddressC 只发送 TokenB,没有别的。
在 etherscan 或 bscscan 中,很容易查看 WalletA 中收到了多少 TokenB,并且“来自”字段在那里,因此您可以进行一些数学计算以获得总数。
如何使用 web3 做到这一点?我在 web3 文档中找不到任何相关的 api 调用。
我可以通过 web3.js 在 WalletA 中获得 TokenB 的总余额,但我需要 token 数量 只有从地址C发送。
谢谢。

最佳答案

根据 ERC-20标准,每次 token 转移发出 Transfer()事件日志,包含发件人地址、收件人地址和代币数量。
您可以使用 web3js 获取过去的事件日志。一般方法web3.eth.getPastLogs() ,编码输入并解码输出。
或者您可以提供合约的 ABI JSON(在这种情况下仅使用 Transfer() 事件定义就足够了)并使用 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();

关于web3js - 使用 Web3.js 获取从特定地址收到的 token 总量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69602206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com