From 1cb8abcd27ec32d2cae021b4ae5627e9b22faf1b Mon Sep 17 00:00:00 2001 From: hensha256 Date: Wed, 24 Apr 2024 13:01:28 -0300 Subject: [PATCH] add snapLastCall --- .forge-snapshots/singleSstoreLastCall.snap | 1 + src/GasSnapshot.sol | 13 +++++++++++-- src/test/SimpleOperations.sol | 4 ++++ test/GasSnapshot.t.sol | 9 +++++++++ 4 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 .forge-snapshots/singleSstoreLastCall.snap diff --git a/.forge-snapshots/singleSstoreLastCall.snap b/.forge-snapshots/singleSstoreLastCall.snap new file mode 100644 index 0000000..4c52430 --- /dev/null +++ b/.forge-snapshots/singleSstoreLastCall.snap @@ -0,0 +1 @@ +43429 \ No newline at end of file diff --git a/src/GasSnapshot.sol b/src/GasSnapshot.sol index ded4027..e2326e2 100644 --- a/src/GasSnapshot.sol +++ b/src/GasSnapshot.sol @@ -55,7 +55,6 @@ contract GasSnapshot is Script { } /// @notice Snapshot the given external closure - /// @dev most accurate as storage cost semantics are not involved function snap(string memory name, function() external fn) internal { uint256 gasBefore = gasleft(); fn(); @@ -68,7 +67,6 @@ contract GasSnapshot is Script { } /// @notice Snapshot the given internal closure - /// @dev most accurate as storage cost semantics are not involved function snap(string memory name, function() internal fn) internal { uint256 gasBefore = gasleft(); fn(); @@ -80,6 +78,17 @@ contract GasSnapshot is Script { } } + /// @notice Snapshot using forge isolate of gas of the previous call + /// @dev most accurate as this uses a complete transaction and no storage semantics + function snapLastCall(string memory name) internal { + uint256 gasUsed = vm.lastCallGas().gasTotalUsed; + if (check) { + _checkSnapshot(name, gasUsed); + } else { + _writeSnapshot(name, gasUsed); + } + } + /// @notice Start a snapshot with the given name /// @dev The next call to `snapEnd` will end the snapshot function snapStart(string memory name) internal { diff --git a/src/test/SimpleOperations.sol b/src/test/SimpleOperations.sol index 0d95a8a..49b5ef3 100644 --- a/src/test/SimpleOperations.sol +++ b/src/test/SimpleOperations.sol @@ -16,6 +16,10 @@ contract SimpleOperations { } } + function singleSstore() public { + test = block.timestamp + 3; + } + function manySstore() public { for (uint256 i = 0; i < 100; i++) { test = i + 2; diff --git a/test/GasSnapshot.t.sol b/test/GasSnapshot.t.sol index 2da91b8..d888b68 100644 --- a/test/GasSnapshot.t.sol +++ b/test/GasSnapshot.t.sol @@ -29,6 +29,15 @@ contract GasSnapshotTest is Test, GasSnapshot { assertEq(value, "5247"); } + function testAddLastCall() public { + simpleOperations.singleSstore(); + snapLastCall("singleSstoreLastCall"); + + string memory value = vm.readLine(".forge-snapshots/singleSstoreLastCall.snap"); + // includes 21,000 overhead for transaction, 20,000 clean SSTORE + assertEq(value, "43429"); + } + function testAddClosure() public { snap("addClosure", simpleOperations.add);