Gas Fees – EtherJS Calculates Gas Fee Too Low

ethers.jsgas-estimategas-price

newbie here so please bear with me.

I am using EthersJS latest v5 in order to interact with our contracts, which works great so far. However, I spotted that for a certain period of time (around 1st March) a lot of our transactions failed due to running out of gas.

You can see a list of transactions here

As far as I understood, EthersJS will calculate the amount of fees via the estimateGas correct internally via the contract. At least on our end we don't do any manual gas calculation.

So I am wondering why at a certain period of time many of the transactions failed. Maybe this has to do with a certain RPC url used?

I would like to get some insight. One of the contract methods redeemAuto we call like so:

 const contract = new ethers.Contract(
  contracts[contractName].address,
  contracts[contractName].abi,
  library.getSigner()
);

await contract.redeemAuto(etherToWei(amount))

So nothing fancy going on here.

Thanks

Best Answer

Gas estimation is not always accurate or might change by the time your call gets executed. It is an estimate. Your transactions that failed have used 98% of the gas, so it's possible that you might need to bump your estimation to give your gas some wiggle room.

You can override the default gas estimate by providing all the necessary parameters as options.

With Ether;

const tx = await contract.redeemAuto(amount,{value:value,gas:150000,...})

There are tools to evaluate the gas cost of your transactions and investigate why the gas units differ.

For instance

hardhat-gas-reporter

I suspect that the loops you are performing in the contract and or the array with an undefined length might cause this behaviour.

Note that it is safe to provide more gas units than required since the EVM will never overcharge on the units. You will only use what you needed. (you will need to have that balance)

Related Topic