0

I am using web3.js and getting balance for rinkeby network in MetaMask. But I am getting always object promise in console. But, I want to get USDT amount from the account.

Please check following code.

async function getBalance(contract,accounts) {
    
    contract.balanceOf(accounts[0], function(error, balance){
        contract.decimals((error, decimals) => {            
            balance = balance.div(10**decimals);
            netbalance = balance.toString();
            return netbalance;                                      
        });
    }); 
}

$(document).on('click','#click',async function(){   
    try {
        contract = web3.eth.contract(contractABI).at(contractAddress);
        accounts = await ethereum.request({ method: 'eth_accounts' });
        let balance = getBalance(contract, accounts);
        console.log(balance);
    } catch(error) {    
        if(error.code == 4001) {
            var msg = '<p>Transaction rejected by user.</p>';
        }else{
            var msg = error.message;
        }
    }
});

Output:

enter image description here

1 Answer 1

1

You are using a very old version of web3. I'd suggest to upgrade to the latest version.

Then you can modify getBalance to use async/await. It will look like this for web3 v1.5.

async function getBalance(contract, account) {
    let balance = await contract.methods.balanceOf(account);
    let decimals = await contract.methods.decimals();
    balance = balance.div(web3.utils.toBN(10).pow(decimals));
    let netbalance = balance.toString();
    return netbalance;
}

Then you could initialize

try {
    let contract = new web3.eth.Contract(contractABI, contractAddress);
    let accounts = await ethereum.request({ method: 'eth_accounts' });
    let balance = await getBalance(contract, accounts[0]);
    console.log(balance);
} ...

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.