-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
gasleft()
are inconsistent between tests, appear to depend on test name
#6164
Comments
gasleft()
does not return consistent values between tests gasleft()
are inconsistent between tests, appear to depend on test name
This is a quirk of function dispatch in smart contracts – by the time an external function is called, Solidity's done a fair bit of work to match the function selector to a valid function. Solc doesn't (yet) have constant-gas/constant-time function dispatch, so calls that satisfy earlier function signature checks will consume less gas before entering the function (Seaport 1.6 has an "efficient" You have some potential workarounds by using the You may be able to pause gas metering in the setUp function, then resume it during tests; that should bypass metering during the function dispatch for the tests themselves. Hopefully, you won't run into the cheatcodes' quirks/bugs. |
Closing per @jameswenzel's comment which is correct. If you share more about what you're trying to do we may be able to provide guidance on how to do it to avoid bias from function dispatch gas |
Thanks @jameswenzel ! Was not aware function dispatch could cause different gas costs. I'm trying to create positive and negative tests for a function which should revert or not based on the value of |
Is this a correct interpretation of what you're trying to test: contract Foo {
function foo() public {
// Do some stuff.
// Revert if not enough gas left.
if (gasleft() < 20_000) revert InsufficientGas();
// Do more stuff.
}
} If so, some options:
contract Foo {
function _gasleft() internal virtual returns (uint256) {
return gasleft(); // virtual to be overridden in tests
}
function foo() public {
// Do some stuff.
// Revert if not enough gas left.
if (gasleft() < 20_000) revert InsufficientGas();
// Do more stuff.
}
}
contract FooHarness is Foo {
function _gasleft() internal override returns (uint256) {
return 10; // or add a setter method to read this from storage, etc.
}
} |
I think |
Component
Forge
Have you ensured that all of these are up to date?
What version of Foundry are you on?
forge 0.2.0 (dee4181 2023-10-29T00:18:36.507223145Z)
What command(s) is the bug in?
No response
Operating System
Linux
Describe the bug
The behavior of
gasleft()
is not consistent across tests. In particular, it appears to depend on the name of the test. To reproduce, consider the following 3 test files:Test.t.sol:
Test2.t.sol:
Test3.t.sol
Running
forge test --mt test_x -vv
yields:The text was updated successfully, but these errors were encountered: