Search code examples
javascriptethereumweb3jsabimetamask

How to properly get the balance of different tokens in my MetaMask wallet?


How can I get the balance of tokens like Alpaca in my MetaMask wallet? Googling around I found a piece of code but it returns this error:

TypeError: contract.balanceOf is not a function

this is the code:

let minABI = [
  // balanceOf
  {
    "constant":true,
    "inputs":[{"name":"_owner","type":"address"}],
    "name":"balanceOf",
    "outputs":[{"name":"balance","type":"uint256"}],
    "type":"function"
  },
];

let alpacaAddress = "0x8F0528cE5eF7B51152A59745bEfDD91D97091d2F";

let contract = new web3.eth.Contract(minABI, alpacaAddress);
contract.balanceOf(MyWallet, (error, balance) => {
    console.log(balance.toString());
});

Any Idea why contract.balanceOf is not a function?


Solution

  • Web3js uses the methods helper property. Plus you also need to use the .call() function to perform a read-only call.

    So in your case:

    contract.methods.balanceOf().call()
    

    Docs: https://web3js.readthedocs.io/en/v1.3.4/web3-eth-contract.html#methods-mymethod-call


    It seems that your snippet calling balanceOf() is using syntax from Truffle (docs), which is a different library, so it's not going to work on a web3 Contract instance (new web3.eth.Contract()).