6

I want to get the ERC-20 token balance of an account using ethers.js. Could you help me?

5
  • What kind of information are you looking for? Jun 14, 2021 at 6:20
  • I want to get the token balance of my wallet using ether.js.
    – Alex Weber
    Jun 14, 2021 at 6:22
  • That's more token contract information than it is wallet information. Jun 14, 2021 at 6:26
  • I've updated your question. Jun 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. Jun 14, 2021 at 14:14

1 Answer 1

8

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).

10
  • Could you send me Erc20.json?
    – Alex Weber
    Jun 14, 2021 at 6:34
  • 1
    You could find it here: ethereumdev.io/abi-for-erc20-contract-on-ethereum Jun 14, 2021 at 6:36
  • I've made some edits in my answer above. Jun 14, 2021 at 6:38
  • Thanks for your reply. I had an error, provider.getSigners is not a function What does reason? I am a beginner. Help me.
    – Alex Weber
    Jun 14, 2021 at 6:54
  • 1
    Could you try provider.getSigner() instead? What means? I am going to use contractAddress instead of provider.getSinger(). Right?
    – Alex Weber
    Jun 14, 2021 at 7:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.