7

I want to know how much gas it would cost to deploy my smart contract using Ethers.js.

I know how to estimate it for a transaction with contract.estimateGas.functionName(), but I can't seem to figure out how to do it for a smart contract.

Please help. Thank you!

2 Answers 2

10

You'll first need to get the encoded contract deployment data as follows:

const deploymentData = contract.interface.encodeDeploy([<constructor_arguments>])

Then, you could use the data to get the estimated gas limit as follows:

const estimatedGas = await ethers.provider.estimateGas({ data: deploymentData });
4
  • Thank you! How would I do the constructor_arguments if my code inherits from another contract? constructor() ERC20("Ex", "EX") {}
    – Adrian D.
    Aug 8, 2021 at 21:26
  • @AdrianD. looks like the constructor you defined above doesn't have any arguments. Only arguments within the brackets right after constructor keyword count. You would just pass an empty array for constructor args like .encodeDeploy([]). Aug 8, 2021 at 21:34
  • Thanks, unfortunately, this doesn't provide an accurate way to get the gas.
    – Adrian D.
    Aug 8, 2021 at 23:17
  • @AdrianD. so the above code will give you the gas limit, you would need to multiply it with the current network gas price in order to get the fee in ETH. Jan 6, 2022 at 10:19
5

use contractFactory.getDeployTransaction, see doc

sample code:

const contract = new ethers.ContractFactory(...);
const estimatedGas = await ethers.provider.estimateGas(contract.getDeployTransaction(...).data)
1
  • The chosen answer did not work for me; it gave a very low estimation. This method gave a perfect estimation. Thank you!
    – flcoder
    Aug 2, 2022 at 22:08

Your Answer

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

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