Transaction gas cost in Foundry `forge` unit tests

forgefoundrygastesting

forge test includes support for reporting gas usage by method externally with --gas-report.

However, I would like to measure gas usage within a given unit test, which from reading the documentation doesn't appear to be supported (though the Foundry documentation is sometimes thin).

Is there a way to measure gas usage within forge unit tests, ideally via an assert for a section of code in a given block?

Best Answer

It is not currently possible to create custom spans for gas reporting in Forge - or rather, Forge does not have a built-in mechanism for this.

The only way you can achieve something similar, is to create your own helper functions that use the gasleft() Solidity built-in.

These two functions are taken from solmate:

contract GasHelpers {
    string private checkpointLabel;
    uint256 private checkpointGasLeft = 1; // Start the slot warm.

    function startMeasuringGas(string memory label) internal virtual {
        checkpointLabel = label;

        checkpointGasLeft = gasleft();
    }

    function stopMeasuringGas() internal virtual {
        uint256 checkpointGasLeft2 = gasleft();

        // Subtract 100 to account for the warm SLOAD in startMeasuringGas.
        uint256 gasDelta = checkpointGasLeft - checkpointGasLeft2 - 100;

        emit log_named_uint(string(abi.encodePacked(checkpointLabel, " Gas")), gasDelta);
    }
}

The function emits an event with the gas used. To see the output of the events you must run your tests with at least double verbosity: forge test -vv.

Related Topic