-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Closed
Labels
A-cheatcodesArea: cheatcodesArea: cheatcodesA-testingArea: testingArea: testingC-forgeCommand: forgeCommand: forgeCmd-forge-testCommand: forge testCommand: forge testT-bugType: bugType: bug
Milestone
Description
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
Labels
A-cheatcodesArea: cheatcodesArea: cheatcodesA-testingArea: testingArea: testingC-forgeCommand: forgeCommand: forgeCmd-forge-testCommand: forge testCommand: forge testT-bugType: bugType: bug
Type
Projects
Status
Completed