Web3JS – How to Get ERC20 Token Balance

web3js

I am still new with web3

How can I get balance of token?

On ropsten network, I have 100 LINK token.

Below is my code

const Web3 = require('web3')
const rpcURL = 'https://ropsten.infura.io/v3/xxxx'
const web3 = new Web3(rpcURL)

let tokenAddress = "0x20fe562d797a42dcb3399062ae9546cd06f63280";
let walletAddress = "0xdD440e8eCA5F1F3e6D5ffE903148EFB374942df2";

// The minimum ABI to get ERC20 Token balance
let minABI = [
  // balanceOf
  {
    "constant":true,
    "inputs":[{"name":"_owner","type":"address"}],
    "name":"balanceOf",
    "outputs":[{"name":"balance","type":"uint256"}],
    "type":"function"
  },
  // decimals
  {
    "constant":true,
    "inputs":[],
    "name":"decimals",
    "outputs":[{"name":"","type":"uint8"}],
    "type":"function"
  }
];

let contract = new web3.eth.Contract(minABI,tokenAddress);
async function getBalance() {
  balance = await contract.methods.balanceOf(walletAddress);
  return balance;
}

console.log(getBalance());

The code return:

Promise { <pending> }

based on my search on google, this promise pending should be solved by using async function but in my case, it still showing promise pending.

I am using latest node 14 and web3.js 1.26

Best Answer

Change this:

balance = await contract.methods.balanceOf(walletAddress);

To this:

balance = await contract.methods.balanceOf(walletAddress).call();

And this:

console.log(getBalance());

To this if you're using web3.js v0.x:

getBalance().then(function (result) {
    console.log(result.toFixed());
});

Or to this if you're using web3.js v1.x:

getBalance().then(function (result) {
    console.log(result);
});
Related Topic