{"eip":7201,"title":"Namespaced Storage Layout","description":"Conventions for the storage location of structs in the namespaced storage pattern.","authors":["Francisco Giordano (@frangio)","Hadrien Croubois (@Amxx)","Ernesto García (@ernestognw)","Eric Lau (@ericglau)"],"status":"Final","type":"Standards Track","category":"ERC","created":"2023-06-20","discussionsTo":"https://ethereum-magicians.org/t/eip-7201-namespaced-storage-layout/14796","repo":"ERCs","label":"ERC-7201","officialUrl":"https://eips.ethereum.org/EIPS/eip-7201","sourceUrl":"https://github.com/ethereum/ERCs/blob/master/ERCS/erc-7201.md","url":"https://eips.huatuo.xyz/eip-7201/","tldr":{"en":"A convention for placing a contract's state in hashed, collision-free storage namespaces and documenting them with a NatSpec tag, so upgradeable and modular contracts can grow safely and tools can find their data.","ja":"コントラクトのステートを、ハッシュ化された衝突のないストレージ名前空間に置き、NatSpec タグで文書化するための規約。アップグレード可能なコントラクトやモジュール型コントラクトが安全に成長でき、ツールがそのデータを見つけられるようにする。","ko":"컨트랙트 상태를 해시로 정해지는 충돌 없는 스토리지 네임스페이스에 두고 NatSpec 태그로 문서화하는 규약. 업그레이드 가능한 컨트랙트와 모듈형 컨트랙트가 안전하게 확장될 수 있고, 도구가 그 데이터를 찾을 수 있게 한다.","zh":"一种约定：把合约状态放入经过哈希、互不冲突的存储命名空间，并用 NatSpec 标签加以说明，使可升级合约和模块化合约能够安全扩展，工具也能找到它们的数据。"},"tags":["storage","upgradeable","proxy","solidity","tooling"],"explainers":{"en":{"lang":"en","tldr":"A convention for placing a contract's state in hashed, collision-free storage namespaces and documenting them with a NatSpec tag, so upgradeable and modular contracts can grow safely and tools can find their data.","tags":["storage","upgradeable","proxy","solidity","tooling"],"related":[1967,2535,1822,7],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-7201/","markdown":"## What problem does it solve?\n\nSolidity and Vyper lay out state variables sequentially from slot 0. That works for a single contract, but breaks down in two common patterns:\n\n- **Upgradeable contracts**: adding or reordering variables in a new implementation can shift existing ones and corrupt state.\n- **Modular contracts** that `DELEGATECALL` into several pieces of code: all of them share one storage space and must coordinate carefully.\n\nDevelopers solved this by putting groups of variables at pseudorandom, hash-derived slots (sometimes called \"diamond storage\"). But every project used its own formula, and because those variables are not ordinary state variables, compilers, static analyzers and block explorers could not see them.\n\nERC-7201 standardizes both the formula and a way to annotate it in source code.\n\n## How it works\n\n- A **namespace** is a Solidity `struct` whose fields are laid out with the usual rules, but rooted at a chosen slot instead of slot 0.\n- The struct is annotated with `@custom:storage-location \u003cformula\u003e:\u003cid\u003e`, for example `@custom:storage-location erc7201:example.main`. The namespace id should contain no whitespace.\n- The `erc7201` formula is:\n\n```\nerc7201(id) = keccak256(keccak256(id) - 1) \u0026 ~0xff\n```\n\nWhy this shape? `keccak256(id) - 1` is a location the default layout never uses. Hashing it a second time ensures that a multi-slot namespace does not run into slots the default layout could use. The final `\u0026 ~0xff` aligns the root to a multiple of 256, anticipating possible gas changes where groups of 256 slots become warm together.\n\nThe annotation has no effect on compilation; it is documentation that tooling can read. Solidity includes it in the AST from 0.8.20, which the spec recommends as the minimum version.\n\n## Sample code\n\nUsing a namespace in Solidity (from the spec's reference implementation):\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Example {\n    /// @custom:storage-location erc7201:example.main\n    struct MainStorage {\n        uint256 x;\n        uint256 y;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"example.main\")) - 1)) \u0026 ~bytes32(uint256(0xff))\n    bytes32 private constant MAIN_STORAGE_LOCATION =\n        0x183a6125c38840424c4a85fa12bab2ab606c4b6d0e7cc73c0c06ba5300eab500;\n\n    function _getMainStorage() private pure returns (MainStorage storage $) {\n        assembly {\n            $.slot := MAIN_STORAGE_LOCATION\n        }\n    }\n\n    function _getXTimesY() internal view returns (uint256) {\n        MainStorage storage $ = _getMainStorage();\n        return $.x * $.y;\n    }\n}\n```\n\nComputing a location off-chain (ethers v6):\n\n```ts\nimport { AbiCoder, keccak256, toBeHex, toBigInt, toUtf8Bytes } from \"ethers\";\n\nfunction erc7201(id: string): string {\n  const inner = toBigInt(keccak256(toUtf8Bytes(id))) - 1n;\n  const outer = toBigInt(keccak256(AbiCoder.defaultAbiCoder().encode([\"uint256\"], [inner])));\n  return toBeHex(outer \u0026 ~0xffn, 32);\n}\n\nconsole.log(erc7201(\"example.main\"));\n```\n\n## Things to know\n\n- Status is Final. OpenZeppelin Contracts 5.x uses ERC-7201 namespaces for its upgradeable contracts.\n- The compiler does not check the annotation. You are responsible for actually using the slot you documented; a wrong constant silently reads and writes the wrong storage.\n- Within a namespace, the normal upgrade rule still applies: append new struct fields at the end, never reorder or remove existing ones.\n- The pattern is independent of any proxy type. It works with [ERC-1967](/eip-1967/) proxies, UUPS ([ERC-1822](/eip-1822/)) and diamonds ([ERC-2535](/eip-2535/)), and the spec deliberately avoids the name \"diamond storage\" to keep it separate from the diamond proxy pattern.\n"},"ja":{"lang":"ja","tldr":"コントラクトのステートを、ハッシュ化された衝突のないストレージ名前空間に置き、NatSpec タグで文書化するための規約。アップグレード可能なコントラクトやモジュール型コントラクトが安全に成長でき、ツールがそのデータを見つけられるようにする。","tags":["storage","upgradeable","proxy","solidity","tooling"],"related":[1967,2535,1822,7],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-7201/","markdown":"## 何を解決するのか\n\nSolidity と Vyper は、ステート変数をスロット 0 から順番に配置します。単一のコントラクトならこれで問題ありませんが、よくある 2 つのパターンでは破綻します。\n\n- **アップグレード可能なコントラクト**: 新しい実装で変数を追加したり並べ替えたりすると、既存の変数がずれ、ステートが壊れる可能性があります。\n- 複数のコード片に `DELEGATECALL` する**モジュール型コントラクト**: すべてが 1 つのストレージ空間を共有するため、慎重に調整する必要があります。\n\n開発者は、変数のグループを、ハッシュから導いた擬似ランダムなスロットに置くことでこれを解決してきました（「diamond storage」と呼ばれることもあります）。しかしプロジェクトごとに独自の計算式を使い、これらの変数は通常のステート変数ではないため、コンパイラ、静的解析ツール、ブロックエクスプローラーからは見えませんでした。\n\nERC-7201 は、その計算式と、ソースコード上で注釈する方法の両方を標準化します。\n\n## 仕組み\n\n- **名前空間**は Solidity の `struct` で、フィールドは通常のルールで配置されますが、スロット 0 ではなく選んだスロットを起点にします。\n- struct には `@custom:storage-location \u003cformula\u003e:\u003cid\u003e` で注釈を付けます。たとえば `@custom:storage-location erc7201:example.main` です。名前空間の id には空白を含めないでください。\n- `erc7201` の計算式は次のとおりです。\n\n```\nerc7201(id) = keccak256(keccak256(id) - 1) \u0026 ~0xff\n```\n\nなぜこの形なのか。`keccak256(id) - 1` は、デフォルトのレイアウトが決して使わない場所です。これをもう一度ハッシュすることで、複数スロットにわたる名前空間が、デフォルトのレイアウトが使い得るスロットとぶつからないようにします。最後の `\u0026 ~0xff` は起点を 256 の倍数に揃えます。256 スロットのグループがまとめて warm になるような、将来のガス変更を見越したものです。\n\nこの注釈はコンパイルに影響しません。ツールが読める文書です。Solidity は 0.8.20 から AST に含めており、仕様ではこれを最低バージョンとして推奨しています。\n\n## サンプルコード\n\nSolidity での名前空間の使い方（仕様のリファレンス実装より）:\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Example {\n    /// @custom:storage-location erc7201:example.main\n    struct MainStorage {\n        uint256 x;\n        uint256 y;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"example.main\")) - 1)) \u0026 ~bytes32(uint256(0xff))\n    bytes32 private constant MAIN_STORAGE_LOCATION =\n        0x183a6125c38840424c4a85fa12bab2ab606c4b6d0e7cc73c0c06ba5300eab500;\n\n    function _getMainStorage() private pure returns (MainStorage storage $) {\n        assembly {\n            $.slot := MAIN_STORAGE_LOCATION\n        }\n    }\n\n    function _getXTimesY() internal view returns (uint256) {\n        MainStorage storage $ = _getMainStorage();\n        return $.x * $.y;\n    }\n}\n```\n\nオフチェーンで位置を計算する（ethers v6）:\n\n```ts\nimport { AbiCoder, keccak256, toBeHex, toBigInt, toUtf8Bytes } from \"ethers\";\n\nfunction erc7201(id: string): string {\n  const inner = toBigInt(keccak256(toUtf8Bytes(id))) - 1n;\n  const outer = toBigInt(keccak256(AbiCoder.defaultAbiCoder().encode([\"uint256\"], [inner])));\n  return toBeHex(outer \u0026 ~0xffn, 32);\n}\n\nconsole.log(erc7201(\"example.main\"));\n```\n\n## 知っておくべきこと\n\n- ステータスは Final です。OpenZeppelin Contracts 5.x は、アップグレード可能なコントラクトに ERC-7201 の名前空間を使っています。\n- コンパイラは注釈を検証しません。文書化したスロットを実際に使う責任は開発者にあります。定数が間違っていると、誤ったストレージを黙って読み書きします。\n- 名前空間の中でも通常のアップグレードルールは変わりません。新しい struct フィールドは末尾に追加し、既存のものを並べ替えたり削除したりしてはいけません。\n- このパターンはプロキシの種類に依存しません。[ERC-1967](/eip-1967/) プロキシ、UUPS（[ERC-1822](/eip-1822/)）、diamond（[ERC-2535](/eip-2535/)）のいずれでも動作します。仕様は、diamond プロキシパターンと区別するために、あえて「diamond storage」という名前を避けています。\n"},"ko":{"lang":"ko","tldr":"컨트랙트 상태를 해시로 정해지는 충돌 없는 스토리지 네임스페이스에 두고 NatSpec 태그로 문서화하는 규약. 업그레이드 가능한 컨트랙트와 모듈형 컨트랙트가 안전하게 확장될 수 있고, 도구가 그 데이터를 찾을 수 있게 한다.","tags":["storage","upgradeable","proxy","solidity","tooling"],"related":[1967,2535,1822,7],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-7201/","markdown":"## 어떤 문제를 해결하나요?\n\nSolidity와 Vyper는 상태 변수를 slot 0부터 순서대로 배치합니다. 컨트랙트 하나라면 문제없지만, 흔한 두 가지 패턴에서는 깨집니다.\n\n- **업그레이드 가능한 컨트랙트**: 새 구현에서 변수를 추가하거나 순서를 바꾸면 기존 변수가 밀려 상태가 손상될 수 있습니다.\n- 여러 코드 조각에 `DELEGATECALL`하는 **모듈형 컨트랙트**: 모두가 하나의 스토리지 공간을 공유하므로 세심하게 조율해야 합니다.\n\n개발자들은 변수 묶음을 해시로 얻은 의사 난수 slot에 두는 방식으로 이를 해결했습니다(때로 \"diamond storage\"라고 부릅니다). 하지만 프로젝트마다 자기만의 공식을 썼고, 이런 변수는 일반적인 상태 변수가 아니어서 컴파일러, 정적 분석기, 블록 익스플로러가 볼 수 없었습니다.\n\nERC-7201은 공식과 이를 소스 코드에 표기하는 방법을 모두 표준화합니다.\n\n## 어떻게 동작하나요?\n\n- **네임스페이스**는 Solidity `struct`이며, 필드는 평소 규칙대로 배치되지만 slot 0이 아니라 선택한 slot을 시작점으로 삼습니다.\n- struct에는 `@custom:storage-location \u003cformula\u003e:\u003cid\u003e` 주석을 붙입니다. 예를 들어 `@custom:storage-location erc7201:example.main`입니다. 네임스페이스 id에는 공백이 없어야 합니다.\n- `erc7201` 공식은 다음과 같습니다.\n\n```\nerc7201(id) = keccak256(keccak256(id) - 1) \u0026 ~0xff\n```\n\n왜 이런 형태일까요? `keccak256(id) - 1`은 기본 레이아웃이 절대 사용하지 않는 위치입니다. 이를 한 번 더 해시하면 여러 slot에 걸친 네임스페이스가 기본 레이아웃이 쓸 수 있는 slot과 부딪히지 않습니다. 마지막 `\u0026 ~0xff`는 시작점을 256의 배수로 맞추며, 256개 slot 묶음이 함께 warm해지는 gas 변경 가능성에 대비한 것입니다.\n\n이 주석은 컴파일에 영향을 주지 않으며, 도구가 읽을 수 있는 문서입니다. Solidity는 0.8.20부터 이를 AST에 포함하며, 명세는 이를 최소 버전으로 권장합니다.\n\n## 샘플 코드\n\nSolidity에서 네임스페이스 사용하기(명세의 레퍼런스 구현에서 발췌):\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Example {\n    /// @custom:storage-location erc7201:example.main\n    struct MainStorage {\n        uint256 x;\n        uint256 y;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"example.main\")) - 1)) \u0026 ~bytes32(uint256(0xff))\n    bytes32 private constant MAIN_STORAGE_LOCATION =\n        0x183a6125c38840424c4a85fa12bab2ab606c4b6d0e7cc73c0c06ba5300eab500;\n\n    function _getMainStorage() private pure returns (MainStorage storage $) {\n        assembly {\n            $.slot := MAIN_STORAGE_LOCATION\n        }\n    }\n\n    function _getXTimesY() internal view returns (uint256) {\n        MainStorage storage $ = _getMainStorage();\n        return $.x * $.y;\n    }\n}\n```\n\n오프체인에서 위치 계산하기(ethers v6):\n\n```ts\nimport { AbiCoder, keccak256, toBeHex, toBigInt, toUtf8Bytes } from \"ethers\";\n\nfunction erc7201(id: string): string {\n  const inner = toBigInt(keccak256(toUtf8Bytes(id))) - 1n;\n  const outer = toBigInt(keccak256(AbiCoder.defaultAbiCoder().encode([\"uint256\"], [inner])));\n  return toBeHex(outer \u0026 ~0xffn, 32);\n}\n\nconsole.log(erc7201(\"example.main\"));\n```\n\n## 알아둘 점\n\n- 상태는 Final입니다. OpenZeppelin Contracts 5.x는 업그레이드 가능한 컨트랙트에 ERC-7201 네임스페이스를 사용합니다.\n- 컴파일러는 이 주석을 검사하지 않습니다. 문서화한 slot을 실제로 사용하는 것은 개발자의 책임이며, 상수가 틀리면 아무 경고 없이 엉뚱한 스토리지를 읽고 씁니다.\n- 네임스페이스 안에서도 일반적인 업그레이드 규칙은 그대로 적용됩니다. 새 struct 필드는 끝에 추가하고, 기존 필드의 순서를 바꾸거나 제거하면 안 됩니다.\n- 이 패턴은 프록시 종류와 무관합니다. [ERC-1967](/eip-1967/) 프록시, UUPS([ERC-1822](/eip-1822/)), 다이아몬드([ERC-2535](/eip-2535/)) 모두에서 동작하며, 명세는 다이아몬드 프록시 패턴과 구분하기 위해 일부러 \"diamond storage\"라는 이름을 피합니다.\n"},"zh":{"lang":"zh","tldr":"一种约定：把合约状态放入经过哈希、互不冲突的存储命名空间，并用 NatSpec 标签加以说明，使可升级合约和模块化合约能够安全扩展，工具也能找到它们的数据。","tags":["storage","upgradeable","proxy","solidity","tooling"],"related":[1967,2535,1822,7],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-7201/","markdown":"## 它解决什么问题？\n\nSolidity 和 Vyper 从 slot 0 开始顺序排布状态变量。这对单个合约没有问题，但在两种常见模式下会失效：\n\n- **可升级合约**：在新的实现中添加或重新排列变量，可能会让已有变量发生位移，从而破坏状态。\n- 通过 `DELEGATECALL` 调用多段代码的**模块化合约**：它们共用同一个存储空间，必须小心协调。\n\n开发者的解决办法是把一组组变量放在由哈希推导出的伪随机 slot 上（有时称为\"diamond storage\"）。但每个项目都用自己的公式，而且这些变量不是普通的状态变量，因此编译器、静态分析工具和区块浏览器都看不到它们。\n\nERC-7201 把公式和在源码中注释它的方式都标准化了。\n\n## 它如何运作\n\n- **命名空间**是一个 Solidity `struct`，其字段按通常的规则排布，但起点是选定的 slot，而不是 slot 0。\n- 该 struct 用 `@custom:storage-location \u003cformula\u003e:\u003cid\u003e` 来注释，例如 `@custom:storage-location erc7201:example.main`。命名空间 id 中不应包含空白字符。\n- `erc7201` 公式为：\n\n```\nerc7201(id) = keccak256(keccak256(id) - 1) \u0026 ~0xff\n```\n\n为什么是这种形式？`keccak256(id) - 1` 是默认布局永远不会用到的位置。再哈希一次，可以确保跨多个 slot 的命名空间不会撞上默认布局可能使用的 slot。最后的 `\u0026 ~0xff` 把根位置对齐到 256 的倍数，以预期未来可能出现的 gas 变化（每 256 个 slot 一组同时变为 warm）。\n\n这个注释不影响编译；它是工具可以读取的文档。Solidity 从 0.8.20 起把它放入 AST，规范建议以此作为最低版本。\n\n## 示例代码\n\n在 Solidity 中使用命名空间（来自规范的参考实现）：\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Example {\n    /// @custom:storage-location erc7201:example.main\n    struct MainStorage {\n        uint256 x;\n        uint256 y;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"example.main\")) - 1)) \u0026 ~bytes32(uint256(0xff))\n    bytes32 private constant MAIN_STORAGE_LOCATION =\n        0x183a6125c38840424c4a85fa12bab2ab606c4b6d0e7cc73c0c06ba5300eab500;\n\n    function _getMainStorage() private pure returns (MainStorage storage $) {\n        assembly {\n            $.slot := MAIN_STORAGE_LOCATION\n        }\n    }\n\n    function _getXTimesY() internal view returns (uint256) {\n        MainStorage storage $ = _getMainStorage();\n        return $.x * $.y;\n    }\n}\n```\n\n在链下计算位置（ethers v6）：\n\n```ts\nimport { AbiCoder, keccak256, toBeHex, toBigInt, toUtf8Bytes } from \"ethers\";\n\nfunction erc7201(id: string): string {\n  const inner = toBigInt(keccak256(toUtf8Bytes(id))) - 1n;\n  const outer = toBigInt(keccak256(AbiCoder.defaultAbiCoder().encode([\"uint256\"], [inner])));\n  return toBeHex(outer \u0026 ~0xffn, 32);\n}\n\nconsole.log(erc7201(\"example.main\"));\n```\n\n## 需要注意\n\n- 状态为 Final。OpenZeppelin Contracts 5.x 的可升级合约使用了 ERC-7201 命名空间。\n- 编译器不会检查这个注释。你有责任确保实际使用的就是你记录的 slot；常量写错会悄无声息地读写错误的存储。\n- 在命名空间内部，通常的升级规则依然适用：新的 struct 字段只能追加在末尾，绝不能重新排序或删除已有字段。\n- 该模式与任何代理类型无关。它适用于 [ERC-1967](/eip-1967/) 代理、UUPS（[ERC-1822](/eip-1822/)）和 diamond（[ERC-2535](/eip-2535/)），规范有意避免使用\"diamond storage\"这一名称，以便与 diamond 代理模式区分开来。\n"}},"requiredBy":[7546,7779,8042,8317]}
