Ethers.js – How to Estimate Gas Fees for Smart Contract Function Calls

ethers.jsgas-estimategas-price

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?

Best Answer

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.