Transactions – How to Calculate Gas Fees for Deploying a Smart Contract Using Hardhat

etherscangoerlitransactions

I have created the following script for calculating the transaction fee for deploying smart contract using Hardhat:

const contractFactory = await ethers.getContractFactory('Lock');
const deployTx = contractFactory.getDeployTransaction(unlockTime, { value: lockedAmount });
const contract = await contractFactory.deploy(unlockTime, { value: lockedAmount });

const receipt = await contract.deployTransaction.wait();
const transactionHash = await ethers.provider.getTransactionReceipt(receipt.transactionHash);


const gasUsed = transactionHash.gasUsed;
const gasPricePaid = await ethers.provider.getGasPrice();
const transactionFee = gasUsed.mul(gasPricePaid);
console.log(`Transaction fee paid for contract deployment: ${ethers.utils.formatEther(transactionFee)} wei`);

  console.log(
`Smart contract address: ${contract.address}}`
);
  
console.log(`Transaction fee estimated for contract deployment: ${deploymentPriceRBTC} wei`);

It works fine and I get results like:

Transaction fee paid for contract deployment: 0.000838054876525056 wei

However when I open the transaction on Etherscan I see that the transaction fee is different 0.00118697 for the same transaction.

Can someone explain me what is exactly happening how can I get the real value which is stored on etherscan

Best Answer

Use effectiveGasPrice value directly from the receipt, instead of ethers.provider.getGasPrice

const transactionReceipt = await ethers.provider.getTransactionReceipt(receipt.transactionHash);
const gasUsed = transactionReceipt.gasUsed;
const gasPricePaid = transactionReceipt.effectiveGasPrice;
const transactionFee = gasUsed.mul(gasPricePaid);

provider.getGasPrice 🔗

— returns suggested gas price for current/next transactions. You call this before sending the transaction, to estimate the gas price.

Related Topic