Skip to content

Instantly share code, notes, and snippets.

@0xClandestine
Last active January 14, 2025 20:39
Show Gist options
  • Save 0xClandestine/ceb4c7b742b63ed5e7f379bdd82fa5bd to your computer and use it in GitHub Desktop.
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).
// 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