2

Let's say you have a function in your smart contract, like:

function saveUser(address newUser) public {
    // Saving user
}

How can we estimate, with Ethers.js, what the gas price will be for calling this function?

1 Answer 1

2

First, you must get the estimated gas price to use in an empty transaction:

const gasPrice = await provider.getGasPrice();

Then, get the estimated gas price for your specific transaction, and multiply it by gasPrice:

const functionGasFees = await contract.estimateGas.saveUser(userAddress);
const finalGasPrice = gasPrice * functionGasFees;

Of course, finalGasPrice will never be exactly equal to the actual gas price you will end up paying, but it is a close enough estimate.

2
  • I get a 16-digit number instead of 18 digits when I do this
    – ihor.eth
    Commented Jun 2, 2022 at 0:26
  • Actually, it is a gas amount. Just convert it from hex to decimals and you will see it in a more "natural" way. And gas amount is a simple integer, not wei Commented Sep 8, 2022 at 15:47

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.