I want to get the ERC-20 token balance of an account using ethers.js. Could you help me?
-
What kind of information are you looking for?– Ahmed Ihsan TawfeeqJun 14, 2021 at 6:20
-
I want to get the token balance of my wallet using ether.js.– Alex WeberJun 14, 2021 at 6:22
-
That's more token contract information than it is wallet information.– Ahmed Ihsan TawfeeqJun 14, 2021 at 6:26
-
I've updated your question.– Ahmed Ihsan TawfeeqJun 14, 2021 at 6:27
-
Related: you can use create-eth-app to get a boilerplate React/ Vue.js template that contains a script for querying an ERC-20 token balance.– Paul Razvan BergJun 14, 2021 at 14:14
1 Answer
You could do the following:
const ethers = require('ethers');
const genericErc20Abi = require(..../.../Erc20.json);
const tokenContractAddress = '0x...';
const provider = ...; (use ethers.providers.InfuraProvider for a Node app or ethers.providers.Web3Provider(window.ethereum/window.web3) for a React app)
const contract = new ethers.Contract(tokenContractAddress, genericErc20Abi, provider);
const balance = (await contract.balanceOf((await provider.getSigners())[0].address)).toString();
This will return the result in wei. If you want to know the exact amount of token with its token name then you need to divide it with its decimal. For example if you want to get USDC amount you need to divide the result by 10^6.
const balance = ((await contract.balanceOf((await provider.getSigners())[0].address))/10**6).toString();
The final output will be "TokenAmount USDC" (example 10 USDC).
-
-
1You could find it here: ethereumdev.io/abi-for-erc20-contract-on-ethereum Jun 14, 2021 at 6:36
-
-
Thanks for your reply. I had an error,
provider.getSigners is not a function
What does reason? I am a beginner. Help me. Jun 14, 2021 at 6:54 -
1
Could you try provider.getSigner() instead?
What means? I am going to use contractAddress instead ofprovider.getSinger()
. Right? Jun 14, 2021 at 7:06