web3js - 使用 Web3.js 获取从特定地址收到的令牌总量
问题描述
在一个场景中,WalletA定期从AddressC接收TokenB。AddressC 只发送 TokenB,没有别的。
在 etherscan 或 bscscan 中,很容易查看 WalletA 中收到了多少 TokenB,并且存在“from”字段,因此您可以做一些数学运算来获得总数。
如何使用 web3 来做到这一点?我在 web3 文档中找不到任何相关的 api 调用。我可以通过 web3.js 获得 WalletA 中 TokenB 的总余额,但我需要仅从 AddressC 发送的令牌计数。
谢谢。
解决方案
根据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();
推荐阅读
- laravel - 测试驱动的 Laravel:为 foreach 提供的参数无效
- r - 使用文本匹配改变列
- python - 使用 Python 读取大型二进制文件的最快方法
- ruby-on-rails - 测试模型规模和精度的正确方法
- xaml - 如何在 Xamarin 表单中呈现多个根元素?
- sql - 如何在 SQL Server 中计算变量的平均值
- excel - 将 xls 文件另存为 xlsx 时出现日期格式问题
- rust - 有没有办法做 unwrap_or_return 一个错误(任何错误)
- python - 为什么我会收到此错误?TypeError:+ 不支持的操作数类型:添加两个日期时的“TimedeltaIndex”和“relativedelta”
- javascript - 如何在赛普拉斯自定义命令中调用“请求”?