3

I'm looking to estimate transaction fees in an application. In order to do so I need to estimate the current gas price before I execute the transaction.

I see web3.js has a getGasPrice method: https://web3js.readthedocs.io/en/v1.3.4/web3-eth.html#getgasprice

Is there a similar method in ethers.js? Or what is the recommended approach here?

5

There is a method called estimateGas in the Contract class. Example for how to use it:

const erc20Abi = [ /* ... */ ];
const address = "TOKEN_ADDRESS_HERE";
const provider = ethers.getDefaultProvider();
const erc20 = new ethers.Contract(address, abi, provider);

const recipient = "SOME_ADDRESS_HERE";
const estimation = await erc20.estimateGas.transfer(recipient, 100);

Caveats:

  1. You have to be connected to a provider, but luckily this is easy to do with the getDefaultProvider function.
  2. Don't expect the gas estimation to be super precise, especially when your contract call is making additional calls to other contracts.
4
4

Found it! https://docs.ethers.io/v5/api/providers/provider/#Provider-getGasPrice

Hint: the search functionality on docs.ethers.io isn't great - this method didn't show up by searching for "gasprice": https://docs.ethers.io/v5/search/?search=gasprice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.