Last active
January 14, 2025 20:39
-
-
Save 0xClandestine/ceb4c7b742b63ed5e7f379bdd82fa5bd to your computer and use it in GitHub Desktop.
Legacy Storage (slots assigned by compiler) to Namespace storage (slots explicitly assigned by us).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: UNLICENSED | |
pragma solidity ^0.8.13; | |
import {Test, console} from "forge-std/Test.sol"; | |
contract LegacyStorage { | |
uint256 public number; | |
function setNumber(uint256 newNumber) public { | |
number = newNumber; | |
} | |
} | |
contract NamespaceStorage { | |
struct State { | |
uint256 number; | |
} | |
function state() internal pure returns (State storage s) { | |
assembly { | |
s.slot := 0 | |
} | |
} | |
function setNumber(uint256 newNumber) public { | |
state().number = newNumber; | |
} | |
function number() public view returns (uint256) { | |
return state().number; | |
} | |
} | |
contract CounterTest is Test { | |
LegacyStorage public l; | |
NamespaceStorage public n; | |
function setUp() public { | |
l = new LegacyStorage(); | |
n = new NamespaceStorage(); | |
} | |
function testFuzz_SetNumber(uint256 x) public { | |
l.setNumber(x); | |
n.setNumber(x); | |
assertEq(l.number(), x); | |
assertEq(n.number(), x); | |
assertEq(uint256(vm.load(address(l), 0)), x); | |
assertEq(uint256(vm.load(address(n), 0)), x); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment