Forge test estimates less gas than the real transaction

12 Views Asked by At

I noticed that using forge test, the estimated gas used tends to be much less than the real gas used. Taking for example this transaction in Ethereum mainnet: https://etherscan.io/tx/0x187521e2db0fad0c8c354da7632bda2e1b4380ba9f3428d99e6afe2f1a43f681

I tried to replicate it by:

  • forking at the block before the tx
  • using vm.prank to send the transaction from the same caller 0xf5213a6a2f0890321712520b8048D9886c1A9900
  • calling the target address 0xE592427A0AEce92De3Edee1F18E0157C05861564 (UniswapV3 router) with the same tx data

Here's the test code:

contract EstimateGas is Test {
    
    function setUp() public {
        vm.createSelectFork("https://eth.drpc.org", 19400684);
    }

    function testEstimateGas() public {
        vm.prank(0xf5213a6a2f0890321712520b8048D9886c1A9900);
        bytes memory data = hex"414bf389000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000d1d2eb1b1e90b638588728b4130137d262c87cae0000000000000000000000000000000000000000000000000000000000000bb8000000000000000000000000f5213a6a2f0890321712520b8048d9886c1a99000000000000000000000000000000000000000000000000000000000065ecea7e00000000000000000000000000000000000000000000000058c3de02f05a8000000000000000000000000000000000000000000000000000000027c593b519ff0000000000000000000000000000000000000000000000000000000000000000";
        address router = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
        (bool success,) = router.call(data);
        require(success, "fail");
    }
}

The original transaction consumed 122532 gas, however the estimated gas used by forge is 106309, which is considerably less. What could be the cause of this difference, and how can the gas be estimated precisely with a forge test?

I'm using forge 0.2.0 (42da942 2024-03-17T00:17:57.841914000Z)

0

There are 0 best solutions below