How to estimate the gas fee for a transaction with web3

In this tutorial, we are going to learn how to get the gas price and the gas amount to estimate the gas fee that a transaction will cost.

In this tutorial, we are going to learn how to get the gas price and the gas amount to estimate the gas fee of a transaction.

Set up

The first step is to install the web3 dependency using the following command:

npm install web3

Then, to interact with a blockchain (Ethereum or BSC or any other) you need to create an instance of Web3 and give it a provider (like window.ethereum for browser wallets, for example).

After that, you need to connect to the user's wallet using any method you want. You can check out our guides if you want to learn how to connect to a wallet.

How to get the amount of gas needed for a transaction

To get the amount of gas needed for a simple Ethereum transaction you need to use the estimateGas method:

const getGasAmount = async (fromAddress, toAddress, amount) => {
    const gasAmount = await web3.eth.estimateGas({
      to: toAddress,
      from: fromAddress,
      value: web3.utils.toWei(`${amount}`, 'ether'),
    });
    return gasAmount
}

For small simple transactions it should return 21000 as it's the minimum amount of gas an operation on Ethereum will use.

This limit is used to guarantee that the transaction will be executed but it could be more and it's better to get it dynamically and not hard-code it.

How to get the amount of gas needed to call a contract method

Again here, you need to use the estimateGas method but in a different way than previously:

const getGasAmountForContractCall = async (fromAddress, toAddress, amount, contractAddress) => {
    const contract = new web3.eth.Contract(ABI, contractAddress);
    gasAmount = await contract.methods.transfer(toAddress, Web3.utils.toWei(`${amount}`)).estimateGas({ from: fromAddress });
    return gasAmount
}

For that example, you can use this ABI:

const ABI = [
  {
    constant: false,
    inputs: [
      {
        name: 'to',
        type: 'address',
      },
      {
        name: 'value',
        type: 'uint256',
      },
    ],
    name: 'transfer',
    outputs: [
      {
        name: '',
        type: 'bool',
      },
    ],
    type: 'function',
  },
];

How to get the gas price of the network

Now that you have the amount of gas needed for the transaction, you need to get the gas price in order to compute the fee that your transaction will cost.

Here is how to get the gas price:

const gasPrice = await web3.eth.getGasPrice();

Estimate the fee that your transaction will cost

Now that you have the amount of gas needed and the gas price, you can multiply the 2 values and you will get the fee that you can expect to pay on your transaction.

const fee = gasPrice * gasAmount;

Thank you for reading this article 🙂