How to catch error event(Error: Returned error: insufficient funds for gas * price + value) to send tether on Ethereum network

ethereum-wallet-dappgastetherweb3js

This code is to send tether from one address to other address on Ethereum network.

    const Web3 = require('web3')
    const web3 = new Web3('https://mainnet.infura.io/v3/f957dcc0cb6c430f9d32c2c085762bdf')   
    web3.eth.accounts.wallet.add('privateKey');
    var contractAbi = [];
    var tokenAddress = '0xdAC17F958D2ee523a2206206994597C13D831ec7'
    var fromAddress = '0xa73e...'
    var tokenInst = new web3.eth.Contract(contractAbi,tokenAddress);
    await tokenInst.methods.transfer(receiver, amount).send({from: fromAddress, gas: 100000})
        .then(console.log)
        .catch(console.error);

I already checked the above code was working well.

But now I faced this error (Error: Returned error: insufficient funds for gas * price + value) since I haven`t enough eth in my wallet.

So, I am wanna to add calling function at below code to alert 'insufficient funds for gas * price + value on your wallet' or alert 'Withdrawal is successfully done!'.

await tokenInst.methods.transfer(receiver, amount).send({from: fromAddress, gas: 100000}) .then(console.log).catch(console.error);

And I would like to know about reasonable gas fee.

It would be appreciated if you could fix these problems. Thanks.

Best Answer

James, you can use the estimateGas method available on the contract instance to check for the amount of gas that will be used by the transaction.

Once you have the gas you can compare your wallet's balance against the gas * gasPrice (to whatever value of gasPrice you are choosing for the transaction) product to resolve this error.

So your gas estimation code will look like

let gas = await tokenInst.methods.transfer(receiver, amount).estimateGas({from: fromAddress})