{"eip":8042,"title":"Diamond Storage","description":"Define storage locations for structs using human-readable, meaningful strings.","authors":["Nick Mudge (@mudgen)"],"status":"Final","type":"Standards Track","category":"ERC","created":"2025-10-11","requires":[7201],"discussionsTo":"https://ethereum-magicians.org/t/erc-8042-diamond-storage/25718","repo":"ERCs","label":"ERC-8042","officialUrl":"https://eips.ethereum.org/EIPS/eip-8042","sourceUrl":"https://github.com/ethereum/ERCs/blob/master/ERCS/erc-8042.md","url":"https://eips.huatuo.xyz/eip-8042/","tldr":{"en":"Formalises the original \"diamond storage\" pattern: put a struct at the storage slot keccak256(\"some.readable.id\"), with identifiers restricted to printable ASCII.","ja":"元の「ダイヤモンドストレージ」パターンを正式化する。構造体をストレージスロット keccak256(\"some.readable.id\") に置き、識別子は表示可能な ASCII に限定する。","ko":"원래의 \"다이아몬드 스토리지\" 패턴을 공식화한다. 구조체를 스토리지 슬롯 keccak256(\"some.readable.id\")에 두고, 식별자는 출력 가능한 ASCII로 제한한다.","zh":"将最初的\"钻石存储\"（diamond storage）模式正式化：把结构体放在存储槽 keccak256(\"some.readable.id\") 处，标识符限定为可打印 ASCII。"},"tags":["storage","solidity","proxies","diamonds","layout"],"explainers":{"en":{"lang":"en","tldr":"Formalises the original \"diamond storage\" pattern: put a struct at the storage slot keccak256(\"some.readable.id\"), with identifiers restricted to printable ASCII.","tags":["storage","solidity","proxies","diamonds","layout"],"related":[2535,7201,721],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-8042/","markdown":"## What problem does it solve?\n\nProxies, diamonds ([ERC-2535](/eip-2535/)) and libraries that run via `DELEGATECALL` all share one contract's storage. If two pieces of code both use slot 0, they overwrite each other. Since Solidity 0.6.4 (March 2020) a struct can be placed at any storage slot, and the \"diamond storage\" pattern became the common fix: give each module its own struct at `keccak256(\"a.unique.string\")`.\n\n[ERC-7201](/eip-7201/) later standardised namespaced storage, but with a *different* formula, so the many contracts already using plain diamond storage were not covered by any standard. ERC-8042 documents that original, simpler formula and the rules that keep it safe.\n\n## How it works\n\n- A **diamond storage identifier** is a string of printable ASCII only (`0x20`–`0x7E`).\n- The struct's location is `keccak256(identifier)`. Nothing more.\n- Recommendations: use compile-time Solidity string literals (the compiler enforces ASCII), choose unique human-readable names such as `\"myproject.erc721.registry\"`, avoid spaces, and never use `unicode\"…\"` literals or `\\x`/`\\u` escapes.\n- Tooling can annotate the struct with the ERC-7201 NatSpec tag using a new formula id: `@custom:storage-location erc8042:\u003cid\u003e`.\n\nCompared with ERC-7201:\n\n| | ERC-8042 | ERC-7201 |\n| --- | --- | --- |\n| Formula | `keccak256(id)` | `keccak256(abi.encode(uint256(keccak256(id)) - 1)) \u0026 ~0xff` |\n| Identifier rules | Printable ASCII, readable | No whitespace, otherwise free |\n\nThe ASCII rule is what keeps the simple formula safe. Solidity's own mapping and array slots hash inputs containing zero bytes, which a printable-ASCII string cannot reproduce, so diamond storage locations cannot be crafted to collide with them.\n\n## Sample code\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary CounterStorage {\n    bytes32 constant POSITION = keccak256(\"myproject.counter.storage\");\n\n    /// @custom:storage-location erc8042:myproject.counter.storage\n    struct Layout {\n        uint256 count;\n        mapping(address =\u003e uint256) perUser;\n    }\n\n    function layout() internal pure returns (Layout storage s) {\n        bytes32 position = POSITION;\n        assembly { s.slot := position }\n    }\n}\n\ncontract CounterFacet {\n    function increment() external {\n        CounterStorage.Layout storage s = CounterStorage.layout();\n        s.count += 1;\n        s.perUser[msg.sender] += 1;\n    }\n\n    function count() external view returns (uint256) {\n        return CounterStorage.layout().count;\n    }\n}\n```\n\n## Things to know\n\n- **Status: Final.**\n- Uniqueness is your responsibility: two modules using the same string share the same storage. Prefix identifiers with your project or standard name.\n- Both ERC-8042 and ERC-7201 are valid choices. ERC-7201 tolerates arbitrary or machine-generated namespace ids; ERC-8042 favours readable strings and matches existing diamond deployments.\n- Never change an identifier or reorder struct fields in an upgrade. Appending new fields at the end is the usual safe practice.\n- The pattern is not limited to proxies. Any contract can use it to organise storage.\n"},"ja":{"lang":"ja","tldr":"元の「ダイヤモンドストレージ」パターンを正式化する。構造体をストレージスロット keccak256(\"some.readable.id\") に置き、識別子は表示可能な ASCII に限定する。","tags":["storage","solidity","proxies","diamonds","layout"],"related":[2535,7201,721],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-8042/","markdown":"## 何を解決するのか\n\nプロキシ、ダイヤモンド（[ERC-2535](/eip-2535/)）、`DELEGATECALL` 経由で実行されるライブラリは、すべて 1 つのコントラクトのストレージを共有します。2 つのコードがどちらもスロット 0 を使うと、互いに上書きし合ってしまいます。Solidity 0.6.4（2020 年 3 月）以降、構造体を任意のストレージスロットに置けるようになり、「ダイヤモンドストレージ」パターンが一般的な解決策になりました。各モジュールに、`keccak256(\"a.unique.string\")` の位置に専用の構造体を持たせるというものです。\n\nその後 [ERC-7201](/eip-7201/) が名前空間付きストレージを標準化しましたが、*異なる*計算式だったため、すでに素のダイヤモンドストレージを使っている多くのコントラクトはどの標準にも含まれませんでした。ERC-8042 は、その元のよりシンプルな計算式と、それを安全に保つルールを文書化します。\n\n## 仕組み\n\n- **ダイヤモンドストレージ識別子**は、表示可能な ASCII（`0x20`〜`0x7E`）のみで構成された文字列です。\n- 構造体の位置は `keccak256(identifier)` です。それ以上のものはありません。\n- 推奨事項: コンパイル時の Solidity 文字列リテラルを使う（コンパイラが ASCII を強制します）、`\"myproject.erc721.registry\"` のような、一意で人間が読める名前を選ぶ、スペースを避ける、`unicode\"…\"` リテラルや `\\x`/`\\u` エスケープは決して使わない。\n- ツールは、新しい計算式 ID を使って、構造体に ERC-7201 の NatSpec タグを付けられます: `@custom:storage-location erc8042:\u003cid\u003e`。\n\nERC-7201 との比較:\n\n| | ERC-8042 | ERC-7201 |\n| --- | --- | --- |\n| 計算式 | `keccak256(id)` | `keccak256(abi.encode(uint256(keccak256(id)) - 1)) \u0026 ~0xff` |\n| 識別子のルール | 表示可能な ASCII、可読 | 空白なし、それ以外は自由 |\n\nシンプルな計算式を安全に保っているのが、ASCII のルールです。Solidity 自身のマッピングや配列のスロットは、ゼロバイトを含む入力をハッシュしますが、表示可能な ASCII 文字列ではそれを再現できません。そのため、ダイヤモンドストレージの位置をそれらと衝突するように細工することはできません。\n\n## サンプルコード\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary CounterStorage {\n    bytes32 constant POSITION = keccak256(\"myproject.counter.storage\");\n\n    /// @custom:storage-location erc8042:myproject.counter.storage\n    struct Layout {\n        uint256 count;\n        mapping(address =\u003e uint256) perUser;\n    }\n\n    function layout() internal pure returns (Layout storage s) {\n        bytes32 position = POSITION;\n        assembly { s.slot := position }\n    }\n}\n\ncontract CounterFacet {\n    function increment() external {\n        CounterStorage.Layout storage s = CounterStorage.layout();\n        s.count += 1;\n        s.perUser[msg.sender] += 1;\n    }\n\n    function count() external view returns (uint256) {\n        return CounterStorage.layout().count;\n    }\n}\n```\n\n## 知っておくべきこと\n\n- **ステータス: Final。**\n- 一意性を守るのはあなたの責任です。2 つのモジュールが同じ文字列を使うと、同じストレージを共有することになります。識別子には、プロジェクト名や標準名をプレフィックスとして付けてください。\n- ERC-8042 と ERC-7201 のどちらも有効な選択肢です。ERC-7201 は任意の、あるいは機械生成の名前空間 ID を許容します。ERC-8042 は可読な文字列を重視し、既存のダイヤモンドのデプロイと一致します。\n- アップグレードで識別子を変更したり、構造体のフィールドの順序を入れ替えたりしてはいけません。新しいフィールドを末尾に追加するのが、通常の安全な方法です。\n- このパターンはプロキシに限定されません。どのコントラクトでも、ストレージを整理するために使えます。\n"},"ko":{"lang":"ko","tldr":"원래의 \"다이아몬드 스토리지\" 패턴을 공식화한다. 구조체를 스토리지 슬롯 keccak256(\"some.readable.id\")에 두고, 식별자는 출력 가능한 ASCII로 제한한다.","tags":["storage","solidity","proxies","diamonds","layout"],"related":[2535,7201,721],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-8042/","markdown":"## 어떤 문제를 해결하나요?\n\n프록시, 다이아몬드([ERC-2535](/eip-2535/)), 그리고 `DELEGATECALL`로 실행되는 라이브러리는 모두 하나의 컨트랙트 스토리지를 공유합니다. 두 코드가 모두 슬롯 0을 사용하면 서로를 덮어씁니다. Solidity 0.6.4(2020년 3월)부터 구조체를 임의의 스토리지 슬롯에 둘 수 있게 되었고, \"다이아몬드 스토리지\" 패턴이 일반적인 해결책이 되었습니다. 각 모듈에 `keccak256(\"a.unique.string\")` 위치의 전용 구조체를 주는 방식입니다.\n\n이후 [ERC-7201](/eip-7201/)이 네임스페이스 스토리지를 표준화했지만 *다른* 공식을 사용했기 때문에, 이미 평범한 다이아몬드 스토리지를 쓰고 있는 많은 컨트랙트는 어떤 표준에도 포함되지 않았습니다. ERC-8042는 그 원래의 더 단순한 공식과, 이를 안전하게 지키는 규칙을 문서화합니다.\n\n## 어떻게 동작하나요?\n\n- **다이아몬드 스토리지 식별자**는 출력 가능한 ASCII(`0x20`~`0x7E`)로만 이루어진 문자열입니다.\n- 구조체의 위치는 `keccak256(identifier)`입니다. 그게 전부입니다.\n- 권장 사항: 컴파일 타임 Solidity 문자열 리터럴을 사용하고(컴파일러가 ASCII를 강제합니다), `\"myproject.erc721.registry\"`처럼 고유하고 읽기 쉬운 이름을 고르며, 공백을 피하고, `unicode\"…\"` 리터럴이나 `\\x`/`\\u` 이스케이프는 절대 사용하지 마세요.\n- 도구는 새 공식 id를 사용하여 구조체에 ERC-7201 NatSpec 태그를 붙일 수 있습니다: `@custom:storage-location erc8042:\u003cid\u003e`.\n\nERC-7201과의 비교:\n\n| | ERC-8042 | ERC-7201 |\n| --- | --- | --- |\n| 공식 | `keccak256(id)` | `keccak256(abi.encode(uint256(keccak256(id)) - 1)) \u0026 ~0xff` |\n| 식별자 규칙 | 출력 가능한 ASCII, 읽기 쉬움 | 공백 없음, 그 외는 자유 |\n\n단순한 공식을 안전하게 지켜 주는 것이 ASCII 규칙입니다. Solidity 자체의 매핑과 배열 슬롯은 0 바이트를 포함하는 입력을 해시하는데, 출력 가능한 ASCII 문자열로는 이를 재현할 수 없으므로 다이아몬드 스토리지 위치를 이들과 충돌하도록 조작할 수 없습니다.\n\n## 샘플 코드\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary CounterStorage {\n    bytes32 constant POSITION = keccak256(\"myproject.counter.storage\");\n\n    /// @custom:storage-location erc8042:myproject.counter.storage\n    struct Layout {\n        uint256 count;\n        mapping(address =\u003e uint256) perUser;\n    }\n\n    function layout() internal pure returns (Layout storage s) {\n        bytes32 position = POSITION;\n        assembly { s.slot := position }\n    }\n}\n\ncontract CounterFacet {\n    function increment() external {\n        CounterStorage.Layout storage s = CounterStorage.layout();\n        s.count += 1;\n        s.perUser[msg.sender] += 1;\n    }\n\n    function count() external view returns (uint256) {\n        return CounterStorage.layout().count;\n    }\n}\n```\n\n## 알아둘 점\n\n- **상태: Final.**\n- 고유성은 여러분의 책임입니다. 두 모듈이 같은 문자열을 쓰면 같은 스토리지를 공유합니다. 식별자 앞에 프로젝트 이름이나 표준 이름을 접두사로 붙이세요.\n- ERC-8042와 ERC-7201 모두 유효한 선택입니다. ERC-7201은 임의의 또는 기계가 생성한 네임스페이스 id를 허용하고, ERC-8042는 읽기 쉬운 문자열을 선호하며 기존 다이아몬드 배포와 일치합니다.\n- 업그레이드할 때 식별자를 바꾸거나 구조체 필드의 순서를 바꾸지 마세요. 새 필드를 끝에 추가하는 것이 일반적인 안전한 방법입니다.\n- 이 패턴은 프록시에만 국한되지 않습니다. 어떤 컨트랙트든 스토리지를 정리하는 데 사용할 수 있습니다.\n"},"zh":{"lang":"zh","tldr":"将最初的\"钻石存储\"（diamond storage）模式正式化：把结构体放在存储槽 keccak256(\"some.readable.id\") 处，标识符限定为可打印 ASCII。","tags":["storage","solidity","proxies","diamonds","layout"],"related":[2535,7201,721],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-8042/","markdown":"## 它解决什么问题？\n\n代理合约、钻石（[ERC-2535](/eip-2535/)）以及通过 `DELEGATECALL` 运行的库，都共用同一个合约的存储。如果两段代码都使用槽 0，就会互相覆盖。自 Solidity 0.6.4（2020 年 3 月）起，结构体可以放在任意存储槽，\"钻石存储\"模式成为常见的解决办法：给每个模块在 `keccak256(\"a.unique.string\")` 处分配它自己的结构体。\n\n[ERC-7201](/eip-7201/) 后来标准化了命名空间存储，但使用的是*不同的*公式，因此已经在使用普通钻石存储的大量合约没有被任何标准涵盖。ERC-8042 记录了最初那个更简单的公式，以及保证其安全的规则。\n\n## 它如何运作\n\n- **钻石存储标识符**是仅由可打印 ASCII（`0x20`–`0x7E`）构成的字符串。\n- 结构体的位置是 `keccak256(identifier)`，仅此而已。\n- 建议：使用编译期的 Solidity 字符串字面量（编译器会强制 ASCII），选择唯一且易读的名称，例如 `\"myproject.erc721.registry\"`，避免空格，并且绝不使用 `unicode\"…\"` 字面量或 `\\x`/`\\u` 转义。\n- 工具可以使用新的公式 id，为结构体加上 ERC-7201 的 NatSpec 标签：`@custom:storage-location erc8042:\u003cid\u003e`。\n\n与 ERC-7201 的比较：\n\n| | ERC-8042 | ERC-7201 |\n| --- | --- | --- |\n| 公式 | `keccak256(id)` | `keccak256(abi.encode(uint256(keccak256(id)) - 1)) \u0026 ~0xff` |\n| 标识符规则 | 可打印 ASCII，可读 | 不含空白，其余不限 |\n\nASCII 规则是让这个简单公式保持安全的关键。Solidity 自身的映射和数组槽所哈希的输入包含零字节，而可打印 ASCII 字符串无法重现这一点，因此无法构造出与它们冲突的钻石存储位置。\n\n## 示例代码\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary CounterStorage {\n    bytes32 constant POSITION = keccak256(\"myproject.counter.storage\");\n\n    /// @custom:storage-location erc8042:myproject.counter.storage\n    struct Layout {\n        uint256 count;\n        mapping(address =\u003e uint256) perUser;\n    }\n\n    function layout() internal pure returns (Layout storage s) {\n        bytes32 position = POSITION;\n        assembly { s.slot := position }\n    }\n}\n\ncontract CounterFacet {\n    function increment() external {\n        CounterStorage.Layout storage s = CounterStorage.layout();\n        s.count += 1;\n        s.perUser[msg.sender] += 1;\n    }\n\n    function count() external view returns (uint256) {\n        return CounterStorage.layout().count;\n    }\n}\n```\n\n## 需要注意\n\n- **状态：Final。**\n- 唯一性由你自己负责：两个模块使用同一个字符串就会共享同一块存储。请在标识符前加上你的项目名或标准名作为前缀。\n- ERC-8042 和 ERC-7201 都是有效的选择。ERC-7201 允许任意或机器生成的命名空间 id；ERC-8042 偏好可读字符串，并与现有的钻石部署一致。\n- 升级时绝不要更改标识符或重新排列结构体字段。在末尾追加新字段是通常的安全做法。\n- 这种模式并不限于代理合约。任何合约都可以用它来组织存储。\n"}},"requiredBy":[8110,8317]}
