Search code examples
reactjsweb3jsethers.js

window.ethereum.request get_balance method, how do I get the tokens amount of specific token?


I was wondering, what can be done so it would get a balance of specific token I want instead of ethereum?

const getAccountBalance = (account) => {
        window.ethereum.request({method: 'eth_getBalance', params: [account, 'latest']})
        .then(balance => {
            setUserBalance(ethers.utils.formatEther(balance));
        })
        .catch(error => {
            setErrorMessage(error.message);
        });
    };

Solution

  • I use ethers.js library.

    When the wallet connects to your website, you connect to the tokens contract too.

    let provider;
    let signer;
    let signerAddress;
    
    const tokenContractAddress = TOKEN_CONTRACT_ADDRESS;
    const tokenABI = TOKEN_ABI;
    let tokenContract;
    let userTokenBalance;
    
    const startFunction = async () => {
        //Connect to MetaMask
        await ethereum.request({ method: 'eth_requestAccounts'});
        //get provider
        provider = new ethers.providers.Web3Provider(window.ethereum);
        //get signer (I usually use signer because when you connect to contract via signer,
        //you can write to it too, but via provider, you can only read data from contract)
        signer = provider.getSigner();
        //Get connected wallet address
        signerAddress = await signer.getAddress();
        //Connect to contract
        tokenContract = await new ethers.Contract(tokenContractAddress , tokenABI , signer);
    }
    startFunction();
    
    const getAccountBalance = async () => {
        userTokenBalance = await tokenContract.balanceOf(signerAddress);
        //Note that userTokenBalance is not a number and it is bigNumber
        console.log(userTokenBalance);
    }