[SOLVED] Estimating ETH transfer and ERC20 transfer gas always returns same value


This Content is from Stack Overflow. Question asked by habbas33

I am trying to estimate erc20 transfer fee and eth transfer fee. However, the gasestimate always return the same value for both ethTransferGasEstimate and erc20TransferGasEstimate

  • ethTransferGasEstimate always = 21000
  • erc20TransferGasEstimate always = 68408
     [ ethTransferGasEstimate, erc20TransferGasEstimate, feeHistory, feeHistoryPendingBlock ] = await Promise.all([
                await web3.eth.estimateGas(ethTransferCallData),
                await usdc_contract.estimateGas.transfer(TO_ADDRESS_ETH_MAINNET, 100,{
                    from: FROM_ADDRESS_ETH_MAINNET
                await web3.eth.getFeeHistory(10, "latest",[10, 50, 90]),
                await web3.eth.getFeeHistory(1, "pending",[10, 50, 90])

const baseFeePerGas = parseInt(feeHistoryPendingBlock.baseFeePerGas,16)
            const rewardPerGas = feeHistory.reward.map(b => parseInt(b[1],16)).reduce((a, v) => a + v);
            const priorityFeePerGasEstimate = Math.round(rewardPerGas/feeHistory.reward.length);
            const ethTransferFee = ((baseFeePerGas+priorityFeePerGasEstimate)*ethTransferGasEstimate)/10**18
            const erc20TransferFee = ((baseFeePerGas+priorityFeePerGasEstimate)*erc20TransferGasEstimate.toNumber())/10**18
            console.log("gas estimate eth transfer",ethTransferGasEstimate.toString())
            console.log("total fee", ethTransferFee)
            console.log("gas estimate usdc_contract transfer", erc20TransferGasEstimate.toString())
            console.log("total fee", erc20TransferFee)


Each low-level operation (read from memory, write to storage, …) of the contract has a predetermined price in gas units. When the estimator adds up all of these operations, you get the amount of gas units in your ethTransferGasEstimate and erc20TransferGasEstimate variables.

Note: Some contract logic and the resulting final list of operations might depend on data that is not known before executing the transaction, that’s why it’s just an estimation.

Gas units are then automatically bought for ETH – this is the transaction fee. Their price is market driven, you can see the current prices for example at https://etherscan.io/gastracker or you can get your node provider’s estimation of current market price with provider.getGasPrice().

Currently, the market gas price is around 7 Gwei (= 7 million wei) per each gas unit. So with this price, the ETH transfer would cost you 21,000 gas units == 147,000,000,000 wei == 0.000000147 ETH. And the ERC20 transfer would currently cost you 68,408 gas units == 478,856,000,000 wei == 0.000000478856 ETH.

This Question was asked in StackOverflow by habbas33 and Answered by Petr Hejda It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?

Exit mobile version