3

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

iamdefinitelyahuman
  • 2,876
  • 1
  • 12
  • 32

2 Answers2

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.

The Renaissance
  • 2,749
  • 1
  • 17
  • 45
0

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.

Yahya
  • 328
  • 2
  • 12