Search code examples
ethereumblockchainsoliditysmartcontractshardhat

How does the fee get calculated in hardhat?


I have a solidity method which transfers ether like below code:

function testTransfer() public payable {
        payable(owner()).transfer(msg.value);
    }

I am using hardhat to do unit test on this method.

    const balanceBefore = await ethers.provider.getBalance(address);
    console.log('balanceBefore', balanceBefore.toString());
    await contract.testTransfer({value: 100});
    const balanceAfter = await ethers.provider.getBalance(address);
    console.log('balanceAfter', balanceAfter.toString());
    console.log('different:', parseFloat(balanceBefore.toString()) - parseFloat(balanceAfter.toString()));

The output is:

balanceBefore 10000000000000000000000
balanceAfter 9999999941570704178388
different: 58429295034368

as you can see, the testTransfer in solidity only transfers 100 wei to the owner of the contract. But the balance different before and after run the method is 58429295034368 wei which is a lot larger than 100. I can only think there is extra fee cost on running the code but I don't expect the fee is that expensive. Is there something not correct in hardhat?


Solution

  • The fee is approx. 0.000058 ETH == 58k Gwei.

    Assuming the function costs roughly 29k gas units to execute (21k base for the transaction + 8k to read the output of the owner() function and to perform the transfer) => the gas price results in 2 Gwei per gas unit.

    Which is expected in the local testing environment.

    If you wish, you can change the gasPrice value in your config file (docs).

    For comparison - current (March 2024) gasPrice on the mainnet is usually in the tens of Gwei per gas unit, sometimes over a 100. Source: https://etherscan.io/gastracker