Using the ethers.js library, how can I determine the gas limit when sending a transaction to a contract or deploying a new contract?

  • Could you please elaborate on your use case? What are you building, what exactly is the commission for? Nov 9, 2019 at 8:11
  • For sending, I use npm ethers module Nov 9, 2019 at 9:08
  • When you say commission, do you mean the fee paid to the miners? Nov 9, 2019 at 9:10
  • For sending, I use npm ethers module. To send all funds , the formula for receiving the value field is used tx.value = balance - gasLimit * gasPrcie. But when the tx.data field is added, the transaction is not sent due to lack of funds Nov 9, 2019 at 9:16
  • Yes "commission" = transaction fee Nov 9, 2019 at 9:17

2 Answers 2


(The OP has commented on the question that they're looking for a way to estimate the gas price, not the gas limit, this answer is based on that clarification.)

Method 1

Ethers has a built-in function for estimating gas: https://docs.ethers.org/v5/api/providers/provider/#Provider-estimateGas

Here's a copy of the snippet from the docs linked above:

await provider.estimateGas({
  // Wrapped ETH address
  to: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",

  // `function deposit() payable`
  data: "0xd0e30db0",

  // 1 ether
  value: parseEther("1.0")
// { BigNumber: "27938" }

You'll need to have a provider instantiated, and you'll also need to be able to pipe in the to address and the raw data. Here's a link to an answer about how to encode the raw data. This can be a bit of a hassle, so you may want to keep reading for another potential solution if you need this for a contract call.

Method 2

Another way of accomplishing this for contract calls specifically uses a built-in contract method called estimateGas. (Link to docs, you'll need to scroll down, but it's in that section)

Assume you have a contract you've instantiated inside Ethers as foo. If foo has a function bar (which takes 0 arguments), and you want to estimate the cost of calling bar, you can use:

await foo.estimateGas.bar();
// { BigNumber: "34458" }

You also may want to take a look at the callStatic contract method (in the same section as the docs) if you're interested in more data than just the gas estimate.


From the official documentation, see the deployment section from contracts module. The section provides an example of deploying a contract on ropsten. From the contract deployment hash, you can get the idea of different gas parameters:

Transaction Fee: 0.00181826 Ether ($0.000000)

Gas Limit: 363,652

Gas Used by Transaction: 363,652 (100%)

Gas Price: 0.000000005 Ether (5 Gwei)

You can read more about gas estimation from this issue and this issue.

hope it will help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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