根据ERC-20 标准,每次令牌传输都会发出一个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();