---
eip: 8042
label: ERC-8042
title: Diamond Storage
status: Final
type: Standards Track
category: ERC
created: 2025-10-11
requires: 7201
official: https://eips.ethereum.org/EIPS/eip-8042
source: https://github.com/ethereum/ERCs/blob/master/ERCS/erc-8042.md
canonical: https://eips.huatuo.xyz/zh/eip-8042/
lang: zh
tldr: "将最初的\"钻石存储\"（diamond storage）模式正式化：把结构体放在存储槽 keccak256(\"some.readable.id\") 处，标识符限定为可打印 ASCII。"
tags: [storage, solidity, proxies, diamonds, layout]
---

# ERC-8042: Diamond Storage

> Define storage locations for structs using human-readable, meaningful strings.

**TL;DR:** 将最初的"钻石存储"（diamond storage）模式正式化：把结构体放在存储槽 keccak256("some.readable.id") 处，标识符限定为可打印 ASCII。

## 它解决什么问题？

代理合约、钻石（[ERC-2535](/eip-2535/)）以及通过 `DELEGATECALL` 运行的库，都共用同一个合约的存储。如果两段代码都使用槽 0，就会互相覆盖。自 Solidity 0.6.4（2020 年 3 月）起，结构体可以放在任意存储槽，"钻石存储"模式成为常见的解决办法：给每个模块在 `keccak256("a.unique.string")` 处分配它自己的结构体。

[ERC-7201](/eip-7201/) 后来标准化了命名空间存储，但使用的是*不同的*公式，因此已经在使用普通钻石存储的大量合约没有被任何标准涵盖。ERC-8042 记录了最初那个更简单的公式，以及保证其安全的规则。

## 它如何运作

- **钻石存储标识符**是仅由可打印 ASCII（`0x20`–`0x7E`）构成的字符串。
- 结构体的位置是 `keccak256(identifier)`，仅此而已。
- 建议：使用编译期的 Solidity 字符串字面量（编译器会强制 ASCII），选择唯一且易读的名称，例如 `"myproject.erc721.registry"`，避免空格，并且绝不使用 `unicode"…"` 字面量或 `\x`/`\u` 转义。
- 工具可以使用新的公式 id，为结构体加上 ERC-7201 的 NatSpec 标签：`@custom:storage-location erc8042:<id>`。

与 ERC-7201 的比较：

| | ERC-8042 | ERC-7201 |
| --- | --- | --- |
| 公式 | `keccak256(id)` | `keccak256(abi.encode(uint256(keccak256(id)) - 1)) & ~0xff` |
| 标识符规则 | 可打印 ASCII，可读 | 不含空白，其余不限 |

ASCII 规则是让这个简单公式保持安全的关键。Solidity 自身的映射和数组槽所哈希的输入包含零字节，而可打印 ASCII 字符串无法重现这一点，因此无法构造出与它们冲突的钻石存储位置。

## 示例代码

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

library CounterStorage {
    bytes32 constant POSITION = keccak256("myproject.counter.storage");

    /// @custom:storage-location erc8042:myproject.counter.storage
    struct Layout {
        uint256 count;
        mapping(address => uint256) perUser;
    }

    function layout() internal pure returns (Layout storage s) {
        bytes32 position = POSITION;
        assembly { s.slot := position }
    }
}

contract CounterFacet {
    function increment() external {
        CounterStorage.Layout storage s = CounterStorage.layout();
        s.count += 1;
        s.perUser[msg.sender] += 1;
    }

    function count() external view returns (uint256) {
        return CounterStorage.layout().count;
    }
}
```

## 需要注意

- **状态：Final。**
- 唯一性由你自己负责：两个模块使用同一个字符串就会共享同一块存储。请在标识符前加上你的项目名或标准名作为前缀。
- ERC-8042 和 ERC-7201 都是有效的选择。ERC-7201 允许任意或机器生成的命名空间 id；ERC-8042 偏好可读字符串，并与现有的钻石部署一致。
- 升级时绝不要更改标识符或重新排列结构体字段。在末尾追加新字段是通常的安全做法。
- 这种模式并不限于代理合约。任何合约都可以用它来组织存储。


---

This is an unofficial plain-language summary. Read the full specification: https://eips.ethereum.org/EIPS/eip-8042
