简体   繁体   English

如何查找erc20代币余额

[英]How to find erc20 tokens balance

I'm trying to find the balance of erc20 tokens (such as Tether) of specific addresses.我正在尝试查找特定地址的 erc20 代币(例如 Tether)的余额。

Actually, I hope to find an API that works like below, get the account address and contract address and return the balance of that specific token.实际上,我希望找到一个像下面这样工作的 API,获取帐户地址和合约地址并返回该特定令牌的余额。

Ether Scan token check以太扫描令牌检查

To clarify my purpose, In the TRC20 network, I use this endpoit and there is an array of trc20 token balances in the response.为了阐明我的目的,在 TRC20 网络中,我使用了这个端点,并且响应中有一组 trc20 代币余额。

ERC-20 (and ERC-20-like such as TRC-20 , BEP-20 , etc.) token balance of each address is stored in the contract of the token.每个地址的 ERC-20(以及类似 ERC-20,如TRC-20BEP-20等)的代币余额存储在代币的合约中。

Trongrid uses a separate DB that aggregates token balances from all Transfer() events (defined in the ERC-20 standard) throughout the history of the Tron network. Trongrid 使用一个单独的数据库来汇总整个 Tron 网络历史中所有Transfer()事件(在 ERC-20 标准中定义)的代币余额。 There's possibly a similar third-party service for ERC-20 tokens, but I don't know any. ERC-20 代币可能有类似的第三方服务,但我不知道。 For example Etherscan does have the same info, but they only display it on the address detail page, and they don't provide an API containing this data.例如,Etherscan 确实具有相同的信息,但它们仅在地址详细信息页面上显示,并且不提供包含此数据的 API。

In order to get all ERC-20 token balances of an address, the easiest solution (apart from finding an API that does the same thing as the Trongrid endpoint) is to loop through all token contracts (or just the tokens that you're interested in), and call their balanceOf(address) function.为了获得一个地址的所有 ERC-20 代币余额,最简单的解决方案(除了找到与 Trongrid 端点执行相同操作的 API 之外)是遍历所有代币合约(或者只是您感兴趣的代币in),并调用他们的balanceOf(address) function。

In Ethereum there is no built-in API like Trongrid to retrieve the balance of tokens of certain accounts.在以太坊中,没有像 Trongrid 这样的内置 API 来检索某些账户的代币余额。

If you want to do this, you have to call "balanceOf" method of smart contract tokens.如果你想这样做,你必须调用智能合约代币的“balanceOf”方法。

Infura APIs have an eth_call method to do this. Infura API 有一个eth_call 方法来执行此操作。

Calling this API is a little tricky, I wrote two code snippets for this reason, in JS and Go.调用这个 API 有点棘手,为此我写了两个代码片段,分别在 JS 和 Go 中。

JS: https://gist.github.com/arshamalh/33e6646eb793997f2cc69668bd97010a JS: https://gist.github.com/arshamalh/33e6646eb793997f2cc69668bd97010a

Go: https://gist.github.com/arshamalh/9fe035f7fe18cb5387737546ef84bf6c Go: https://gist.github.com/arshamalh/9fe035f7fe18cb538c873

You can call this using one simple Covlanet API call: https://www.covalenthq.com/docs/api/#get-/v1/{chain_id}/address/{address}/balances_v2/您可以使用一个简单的 Covlanet API 调用来调用它: https://www.covalenthq.com/docs/api/#get-/v1/{chain_id}/address/{address}/balances_v2/

If you want to switch to any other network, just change the chain_id如果要切换到任何其他网络,只需更改chain_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM