Skip to content

Instantly share code, notes, and snippets.

@DrasticWatermelon
Created April 16, 2024 10:07
Show Gist options
  • Save DrasticWatermelon/54e127e4fe7021107c7d4197ca677fd7 to your computer and use it in GitHub Desktop.
Save DrasticWatermelon/54e127e4fe7021107c7d4197ca677fd7 to your computer and use it in GitHub Desktop.
Array length cache PoC
pragma solidity ^0.8.17;
import "forge-std/Test.sol";
import "forge-std/console2.sol";
contract AuditTest is Test {
address[] array;
function setUp() external {
array.push(address(1));
array.push(address(2));
array.push(address(3));
array.push(address(4));
array.push(address(5));
array.push(address(6));
array.push(address(7));
array.push(address(8));
array.push(address(9));
array.push(address(10));
}
function test_AccessArrayLengthFromStorage() external {
// No cache
uint256 gasB4 = gasleft();
for(uint i; i < array.length; i++) {
// Do smth
}
uint256 gasConsumed = gasB4 - gasleft();
// Cache
uint256 length = array.length;
uint256 _gasB4 = gasleft();
for(uint i; i < length; i++) {
// Do smth
}
uint256 _gasConsumed = _gasB4 - gasleft();
console2.log("No cache gas consumed: ", gasConsumed); // 4252
console2.log("Cache gas consumed: ", _gasConsumed); // 1152
console2.log("Absolute diff: %d ", gasConsumed - _gasConsumed); // 3100
console2.log("Relative diff: %d% ", (gasConsumed - _gasConsumed) * 100 / gasConsumed); // 72%
}
}
1. Add the above file to /test
2. Execute it with `forge t --mc AuditTest -vv`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment