Skip to content

GasMetering generates different results compared to gasleft() diff #4523

@Tudmotu

Description

@Tudmotu

Component

Forge

Have you ensured that all of these are up to date?

  • Foundry
  • Foundryup

What version of Foundry are you on?

forge 0.2.0 (ed9298d 2023-03-09T00:04:28.809303436Z)

What command(s) is the bug in?

forge test

Operating System

Linux

Describe the bug

In certain scenarios, using vm.pause/resumeGasMetering() will yield results that differ from what gasleft() would yield.

Below is a simplified reproducible example:

pragma solidity ^0.8.18;

import 'forge-std/Test.sol';

contract GasMeterTest is Test {
    mapping(uint => bytes32) map;

    function test_GasMeter () public {
        vm.pauseGasMetering();

        for (uint i = 0; i < 10000; i++) {
            map[i] = keccak256(abi.encode(i));
        }

        vm.resumeGasMetering();

        for (uint i = 0; i < 10000; i++) {
            map[i] = keccak256(abi.encode(i));
        }
    }

    function test_GasLeft () public {
        for (uint i = 0; i < 10000; i++) {
            map[i] = keccak256(abi.encode(i));
        }

        uint start = gasleft();
        for (uint i = 0; i < 10000; i++) {
            map[i] = keccak256(abi.encode(i));
        }
        console2.log("Gas cost:", start - gasleft());
    }
}

The output shows the difference:

Running 2 tests for test/GasMeterTest.sol:GasMeterTest
[PASS] test_GasLeft() (gas: 231370361)
Logs:
  Gas cost: 6464479

[PASS] test_GasMeter() (gas: 7308777)
Test result: ok. 2 passed; 0 failed; finished in 38.05ms

We can see that when calculating the gas used by diffing gasleft(), we get 6464479 while using the vm.pause/resumeGasMetering cheatcode, we get 7308777.

I've seen more complex scenarios (that are too long to share) where the difference is considerably larger.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Completed

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions