How to get balance of specific token

Is there a way to get the balance of a specific token? (without running a while loop)

1 Like

You can use web3 to do that, This is how we get WETH balance of specific wallet

const WETH9 = new web3.eth.Contract('abiWETH9', 'contractAddressWeth');

WETH9.methods.balanceOf('walletAddress').call({from: 'walletAddress'})
            .then((e) => {
               console.log(e)
            });

Is it possible to do it with Web3 API?

it is possible to do it from your Moralis DB easier, for example you have BscTokenBalance table that automatically syncs that data for current authenticated users that use your application.

The moralis docs doesn’t help. Here is the solution for getting token balances:

async function getBalances( token_id ) {

const options = {

    chain: "chain",

    address: "the address you wish to get the balance of",

    token_address: "token contract address",

    token_id: token_id

  };

  const balance = await Moralis.Web3API.account.getNFTsForContract(options);

  return balance.result[0].amount;

}

Is this for NFTs only?

Yes, the above code is for nfts. If you are interested in erc20 balance you can call it directly as a function on the contract or use getTokenBalances

The struggle is how to get balance of a specific erc20 token. Seems impossible with Moralis.

in that case you can call directly balanceOf function on that erc20 token address, you can use runContractFunction

This should work for you, just swap out the chain, address, abi, account. I’m fetching the users ETH balance here.

import { useMoralisWeb3Api } from 'react-moralis';

const Web3Api = useMoralisWeb3Api()

const fetchBalance = async () => {
  const options = {
    chain: 'polygon',
    address: '0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619', // WETH contract address
    function_name: 'balanceOf',
    abi: WETH_ABI, // WETH COntract ABI
    params: { account: "add user address here" },
  };

  const result = await Web3Api.native.runContractFunction(options)
  console.log(result)
}

Until two days ago the code bellow used to work for NFTs. Today not anymore.

const options = {

chain: "chain",

address: "the address you wish to get the balance of",

token_address: "token contract address",

token_id: token_id

};

const balance = await Moralis.Web3API.account.getNFTsForContract(options);

return balance.result[0].amount;