node.jssmartcontractsweb3jsbinance-smart-chain

How to calculate gasLimit for token transactions like USDT in BSC (BEP-20) blockchain?


I'm developing a DAPP in Binance Smart Chain and I'm wondering that how I can calculate the gas Limit for token transactions like USDT just like its Chrome extension that suggests the transaction gas Limit and calculate its transactionFee. I have a formula for calculating gas Limit in BNB transactions but that is not gonna work for token transactions.

Formula to calculate BNB Transaction:

const gasPrice = await web3.eth.getGasPrice(); // estimate the gas price
    
const transactionObject = {
  from: SENDER_WALLET_ADDRESS,
  to: RECIEVER_WALLET_ADDRESS,
  gasPrice
}

const gasLimit = await web3.eth.estimateGas(transactionObject); // estimate the gas limit for this transaction
const transactionFee = gasPrice * gasLimit; // calculate the transaction fee

It would be great if I can calculate transactionFee like above, too.


Solution

  • When performing token transactions, you can instantiate the contract helper object in JS using web3.eth.Contract.

    Then you can use the .methods property that contains helper functions based on the contract ABI and public functions.

    And then you can chain the .estimateGas() function to the contract function.

    const myContract = new web3.eth.Contract(abiJson, contractAddress);
    const gasLimit = await myContract.methods
        .transfer(to, amount)       // the contract function
        .estimateGas({from: ...});  // the transaction object
    

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