15

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

2
  • The code returns blank output because you're not printing anything. Looks like you're new not only to web3. Commented Apr 24, 2020 at 5:02
  • sorry, i forgot to print out with console log. what i mean in my question is, i have trouble with the promise pending although i have used async function. perhaps you can point out my mistake. thanks
    – webmaster
    Commented Apr 24, 2020 at 6:22

1 Answer 1

16

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);
});
4
  • i updated my code, but it return a long list of methods.
    – webmaster
    Commented Apr 24, 2020 at 6:33
  • @webmaster: Sorry, please see updated answer. Commented Apr 24, 2020 at 6:38
  • it said getBalance().call().then(function (result) { ^ TypeError: getBalance(...).call is not a function
    – webmaster
    Commented Apr 24, 2020 at 6:43
  • 1
    @webmaster: Sorry, please see updated answer. Commented Apr 24, 2020 at 7:07

Your Answer

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

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