我正在尝试提取钱包地址持有的代币合约列表,类似于 bscscan 的做法,但以编程方式除外。 bscscan.com/apis 没有端点,web3js 似乎只报告 ETH 余额。
这是可以实现的,因为 bscscan 报告列表,并且许多代币跟踪器(例如 farmfol.io )似乎也提取该信息。我只是没有找到正确的方法
ERC-20(以及类似 ERC-20,如TRC-20、BEP-20等)每个地址的代币余额存储在代币的合约中。
区块链探索者扫描每笔交易中的Transfer()
事件,如果发射者是代币合约,他们会更新其单独数据库中的代币余额。然后,每个地址的所有代币余额(来自此单独的数据库)将显示为地址详细信息页面上的代币余额。Etherscan 和 BSCScan 目前不提供返回每个地址代币余额的 API。
为了获取某个地址的所有 ERC-20 代币余额,最简单的解决方案(除了找到返回数据的 API 之外)是循环遍历所有代币合约(或仅您感兴趣的代币),并且调用他们的
balanceOf(address)
函数。
const tokenAddresses = [
'0x123',
'0x456',
];
const myAddress = '0x789';
for (let tokenAddress of tokenAddresses) {
const contract = new web3.eth.Contract(erc20AbiJson, tokenAddress);
const tokenBalance = await contract.methods.balanceOf(myAddress).call();
}
详细教程在这里,或者只需按照以下步骤操作即可。
运行脚本之前
在查询用户的代币余额时,您应该手头有几个关键参数:OwnerAddress:这是拥有相关代币的区块链地址。请注意,这不是代币本身的合约地址。 tokenContractAddress:您想要余额的所有代币的合约地址数组。或者,如果您指定字符串 erc20,它将包含该地址曾经持有的整套 erc20 代币。
以下说明适用于您
设置 Alchemy 帐户(免费)后:
方法 1(最简单):使用 Alchemy SDK +“alchemy_getTokenBalances”端点。
在命令行中运行以下命令
// Setup: npm install alchemy-sdk
import { Alchemy, Network } from "alchemy-sdk";
const config = {
apiKey: "<-- ALCHEMY APP API KEY -->",
network: Network.ETH_MAINNET,
};
const alchemy = new Alchemy(config);
//Feel free to switch this wallet address with another address
const ownerAddress = "0x00000000219ab540356cbb839cbe05303d7705fa";
//The below token contract address corresponds to USDT
const tokenContractAddresses = ["0xdAC17F958D2ee523a2206206994597C13D831ec7"];
const data = await alchemy.core.getTokenBalances(
ownerAddress,
tokenContractAddresses
);
console.log("Token balance for Address");
console.log(data);
方法2:使用Node-Fetch
import fetch from 'node-fetch';
// Replace with your Alchemy API key:
const apiKey = "demo";
const fetchURL = `https://eth-mainnet.g.alchemy.com/v2/${apiKey}`;
// Replace with the wallet address you want to query:
const ownerAddr = "0x00000000219ab540356cbb839cbe05303d7705fa";
/*
Replace with the token contract address you want to query:
The below address Corresponds to USDT
*/
const tokenAddr = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "alchemy_getTokenBalances",
"headers": {
"Content-Type": "application/json"
},
"params": [
`${ownerAddr}`,
[
`${tokenAddr}`,
]
],
"id": 42
});
var requestOptions = {
method: 'POST',
body: raw,
redirect: 'follow'
};
var data;
/*
** Fetching the token Balance with Alchemy's getTokenBalances API
*/
await fetch(fetchURL, requestOptions)
.then(response => response.json())
.then(response => {
//This line converts the tokenBalance values from hex to decimal
response["result"]["tokenBalances"][0]["tokenBalance"] = parseInt(response["result"]["tokenBalances"][0]["tokenBalance"], 16);
data = response.result;
console.log("Response Object for getTokenBalances\n", data)
})
.catch(error => console.log('error', error));