Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article examines ERC8042, which defines a way to locate structs in contract storage using the keccak256 hash of a human-readable, meaningful string.

The explanation is based on the following specification and discussion.

I also cover various EIPs, BIPs, SLIPs, CAIPs, ENSIPs, RFCs, and ACPs.

Overview

ERC8042 formally standardizes the Diamond Storage pattern, first introduced and widely adopted through ERC2535 Diamonds.

For more on ERC2535, see the following article.

[ERC2535] Understanding the Diamond Pattern

Diamond Storage uses the keccak256 hash of a meaningful, human-readable string to determine where a struct is located in contract storage. Although the pattern was originally developed for proxy contracts, any smart contract can use it to organize storage and manage data access.

While ERC7201 standardizes a general-purpose mechanism for storage namespaces, ERC8042 standardizes the simpler Diamond Storage convention while retaining backward compatibility with many projects already deployed in production.

For more on ERC7201, see the following article.

[ERC7201] Namespaced Storage Layout

Motivation

Several issues motivated the proposal.

Formalizing Diamond Storage

In March 2020, Solidity added the ability to assign structs to arbitrary storage locations. This enabled a new pattern in which different areas of storage could be used independently. The pattern was first widely adopted through ERC2535 Diamonds and became known as Diamond Storage. However, Diamond Storage itself had not been documented as a formal standard. Without a standard, its exact behavior and usage remained underspecified, making it difficult for tools and frameworks to handle Diamond Storage consistently.

Differences from the ERC7201 formula

In June 2023, ERC7201 was introduced to standardize the storage namespace pattern. However, its proposed storage location formula differed from the formula that Diamond Storage had already established and used widely. Diamond Storage determines a storage location using a simple computation, keccak256("string identifier"), whereas ERC7201 uses a more complex formula. As a result, existing Diamond Storage layouts did not necessarily match those defined by ERC7201.

How the proposal addresses these issues

By formally standardizing Diamond Storage, ERC8042 supports both adoption in new projects and verification of past Diamond Storage implementations. Developers can choose between ERC7201 and ERC8042. For those who prefer Diamond Storage's simplicity, ASCII-restricted identifiers, and direct hash-based computation of storage locations, ERC8042 provides a lightweight alternative. Tools can also use the standard when detecting and accessing data in smart contract storage.

Specification

Diamond Storage defines where structs are located in contract storage. This section covers identifiers, storage location computation, recommendations, and NatSpec annotations.

The following diagram illustrates the overall mechanism of Diamond Storage.

flowchart TD
    A["文字列識別子"] --> B["keccak256でハッシュ化"]
    B --> C["ストレージ位置 (bytes32)"]
    C --> D["構造体をこの位置に配置"]
    D --> E["getStorage()でポインタ取得"]
    E --> F["各関数からアクセス"]

Diamond Storage identifiers

A Diamond Storage identifier is defined as a string containing only printable ASCII characters. Specifically, only characters with codes in the range 0x20 through 0x7E are permitted. This range includes letters, digits, symbols, and spaces.

Computing storage locations

In Diamond Storage, the storage location of a struct is determined by the keccak256 hash of its Diamond Storage identifier. In Solidity, this can be expressed as follows.

javascript
bytes32 constant STORAGE_POSITION = keccak256("myproject.erc721.registry");

This code hashes the string "myproject.erc721.registry" with keccak256 and uses the result as the struct's storage location. The simplicity of this calculation is a distinguishing feature of Diamond Storage. Unlike ERC7201, it requires no intermediate conversions or additional operations: hashing the identifier directly determines the storage location.

flowchart LR
    A["文字列識別子"] -->|keccak256| B["ストレージ位置 (bytes32)"]
    B -->|"assembly: s.slot := position"| C["構造体へのポインタ"]

Recommendations

ERC8042 provides the following recommendations and requirements for using Diamond Storage safely and effectively.

Use Solidity string literals

Solidity string literals are recommended for defining identifiers. A string literal is an ASCII string enclosed in quotes, for example "this is a string literal". For ordinary unescaped characters, the Solidity compiler enforces the printable ASCII range (0x20 through 0x7E). Using string literals, subject to the restrictions below, therefore makes it easier to create identifiers that conform to the specification.

Hexadecimal escape sequences (\xNN) and Unicode escape sequences (\uNNNN) must not be used in Diamond Storage identifiers. Compile-time constant string literals are also recommended.

Use unique, human-readable, meaningful strings

Diamond Storage identifiers should be unique, human-readable, and meaningful. Human-readable means that people can ordinarily read and understand the string. Meaningful means that the string appropriately names or describes the storage area, or follows a naming pattern that does so.

For example, "myproject.erc721.registry" is a meaningful identifier that combines a project name, a standard name, and a purpose hierarchically. By contrast, a random combination of words such as "car.fish.piano.run" does not name or describe the storage area and is therefore not a meaningful identifier.

Do not use Unicode literals

Unicode literals, such as unicode"Hello 😃", must not be used to create Diamond Storage identifiers. Such literals can contain invisible or non-ASCII characters, which would violate the specification.

Avoid space characters

Including space characters (0x20) in Diamond Storage identifiers is discouraged. Spaces may cause problems with tooling, including tools that interpret the NatSpec annotations described below.

NatSpec annotations

ERC7201 defines the NatSpec annotation @custom:storage-location <FORMULA_ID>:<NAMESPACE_ID> to specify the storage location of a struct. The <FORMULA_ID> identifies the formula used to compute the storage location. ERC8042 defines the formula ID erc8042.

The ERC8042 formula is defined as follows.

text
erc8042(id: string literal) = keccak256(id)

In Solidity, this corresponds to the expression keccak256(id). The NatSpec annotation uses the format @custom:storage-location erc8042:<NAMESPACE_ID>.

Here is an example of the annotation.

javascript
/// @custom:storage-location erc8042:myproject.erc721.registry
struct ERC721RegistryStorage {
    address[] erc721Contracts;
    uint256 registryLimit;
}

This NatSpec annotation indicates that the ERC721RegistryStorage struct is stored at the location keccak256("myproject.erc721.registry"). Tools and frameworks can read the annotation to determine the struct's storage location automatically.

Additional considerations

Comparing ERC8042 and ERC7201

Both ERC8042 and ERC7201 provide mechanisms for managing smart contract storage locations, but their design choices and formulas differ.

The following diagram compares their computation flows.

Comparison of the ERC8042 and ERC7201 storage location computation flows

ERC7201 characteristics

ERC7201 applies a formula to a namespace ID to derive a storage location. A namespace ID is a string that contains no whitespace, but the standard imposes no other character restriction. It can therefore be a meaningful string such as mycompany.projectA.erc721 or an arbitrary identifier, including machine-generated strings made from bytes that satisfy the no-whitespace requirement.

The ERC7201 storage location formula is expressed in Solidity as follows.

javascript
keccak256(abi.encode(uint256(keccak256(bytes(namespace_id))) - 1)) & ~bytes32(uint256(0xff))

The formula consists of two parts. The first part, keccak256(abi.encode(uint256(keccak256(bytes(namespace_id))) - 1)), is designed to prevent the input bytes to the second keccak256 operation from overlapping with inputs used for Solidity storage layout computations for types such as mappings and dynamic arrays. This permits namespace IDs to contain arbitrary bytes subject to the namespace ID restriction, without relying on the printable-ASCII constraint of ERC8042. The second part, & ~bytes32(uint256(0xff)), ensures that the resulting storage location is a multiple of 256, leaving room for potential future gas optimizations.

ERC8042 characteristics

ERC8042 restricts identifiers to printable ASCII characters and recommends meaningful, human-readable strings.

The ERC8042 storage location formula is expressed in Solidity as follows.

javascript
keccak256(string_literal)

The formula is much simpler than ERC7201. It requires no intermediate conversions or additional operations; the string is hashed directly.

Comparison table

The following table summarizes the main differences between ERC8042 and ERC7201.

Property ERC8042 ERC7201
Identifier restrictions Printable ASCII only Arbitrary byte sequences without whitespace
Recommended identifiers Meaningful, human-readable strings No additional naming restriction
Formula keccak256(id) keccak256(abi.encode(uint256(keccak256(bytes(id))) - 1)) & ~bytes32(uint256(0xff))
Complexity Simple More complex
Guaranteed multiple of 256 No Yes
Adoption history Used since March 2020 Introduced in June 2023

ERC7201 is suitable when developers need to use arbitrary permitted byte sequences safely or generate random identifiers automatically. ERC8042 suits developers who prefer identifiers that people can read and a simple computation formula. Projects can choose between the standards according to their requirements.

History of Diamond Storage

ERC2535 Diamonds introduced the pattern of separate smart contract storage areas in March 2020. ERC7201 standardized the general pattern in June 2023, adopting less restrictive identifier requirements and a more complex computation formula. ERC8042 standardizes the original, simpler Diamond Storage approach for new projects while formally recognizing compatible implementations that had been used over the preceding five years.

Originally developed for proxy contracts, Diamond Storage can be used in any smart contract to organize storage and manage data access.

Reference implementation

The following is an example of a contract using Diamond Storage. It is designed as a registry that registers and manages the addresses of ERC721 contracts.

The diagram shows the structure of the reference implementation.

Contract structure of the reference implementation

For more on ERC721, see the following article.

[ERC721] An Introduction to the NFT Standard

javascript
/**
 * @title ERC721Registry
 * @notice A registry contract for tracking ERC721 contracts.
 *         Allows adding ERC721 contract addresses up to a configurable limit.
 * @dev EIP-8042 Diamond Storage is used to organize and manage access to storage.
 */
contract ERC721Registry {

  /// @notice Reverts when the registry reaches its configured capacity.
  error ERC721RegistryFull();

  /// @notice Struct storage position defined by keccak256 hash
  ///         of diamond storage identifier.
  bytes32 constant STORAGE_POSITION = keccak256("myproject.erc721.registry");

  /// @custom:storage-location erc8042:myproject.erc721.registry
  struct ERC721RegistryStorage {
    address[] erc721Contracts;
    uint256 registryLimit;
  }

  /// @notice Returns a pointer to the ERC721RegistryStorage struct in storage.
  function getStorage() internal pure  returns (ERC721RegistryStorage storage s) {
    bytes32 position = STORAGE_POSITION;
    assembly {
      s.slot := position
    }
  }

  /// @notice Sets the maximum number of ERC721 contracts the registry can hold.
  function setRegistryLimit(uint256 _newLimit) internal {
    getStorage().registryLimit = _newLimit;
  }

  /// @notice Adds an ERC721 contract address to the registry.
  function addERC721Contract(address _erc721Contract) internal {
    ERC721RegistryStorage storage s = getStorage();

    if(s.erc721Contracts.length == s.registryLimit) {
      revert ERC721RegistryFull();
    }

    s.erc721Contracts.push(_erc721Contract);
  }

  /// @notice Returns a list of all registered ERC721 contract addresses.
  function getERC721Registry() internal view returns (address[] memory) {
    return getStorage().erc721Contracts;
  }
}

Here are the key design choices in this contract.

Defining the storage location

First, the STORAGE_POSITION constant defines the storage location as the result of keccak256("myproject.erc721.registry"). The identifier "myproject.erc721.registry" combines a project name, a token standard, and a purpose hierarchically to help ensure uniqueness while retaining readability.

Storage struct

The ERC721RegistryStorage struct is the data structure placed in storage using the Diamond Storage pattern. Its NatSpec annotation, @custom:storage-location erc8042:myproject.erc721.registry, allows tools to identify the struct's storage location automatically.

Field Type Description
erc721Contracts address[] Dynamic array of registered ERC721 contract addresses.
registryLimit uint256 Maximum number of contracts that can be registered.
The getStorage function
javascript
function getStorage() internal pure  returns (ERC721RegistryStorage storage s) {
    bytes32 position = STORAGE_POSITION;
    assembly {
      s.slot := position
    }
}

This function uses inline assembly to return a pointer to the ERC721RegistryStorage struct at the slot defined by STORAGE_POSITION. It has the pure modifier because the function itself does not read or write storage; it only computes and returns a storage pointer. Other functions access storage through getStorage(), providing a consistent way to access data under the Diamond Storage pattern.

The setRegistryLimit function

The single line getStorage().registryLimit = _newLimit; obtains the storage pointer and updates the registry's capacity. Because storage access follows the Diamond Storage pattern and goes through getStorage(), management of the struct's location is centralized in one place.

The addERC721Contract function

This function adds an ERC721 contract address to the registry. It first obtains the storage pointer through getStorage() and checks whether the number of registered contracts has reached the configured limit. If the count equals the limit, it reverts with the ERC721RegistryFull custom error. Otherwise, it appends the address to the array.

The getERC721Registry function

This function returns an array containing the addresses of all registered ERC721 contracts. It accesses the array through getStorage().erc721Contracts, copies the array from storage into memory, and returns it.

Compatibility

Diamond Storage had been used in the form described by this standard for five years when the proposal was written. ERC8042 recognizes and standardizes earlier Diamond Storage implementations that conform to its specification. In other words, a project already using a conforming Diamond Storage layout can comply with ERC8042 without changing its storage code.

ERC8042 follows the NatSpec annotation format defined by ERC7201 and uses the formula ID erc8042. This allows tools that support the ERC7201 annotation format to identify ERC8042 storage locations as well, provided they recognize the new formula ID.

Security

Identifier uniqueness

If two independent contracts or libraries use the same human-readable string within a shared storage context, they map to the same storage slot. Developers must verify that Diamond Storage identifiers are unique within the contract system to prevent unintended overlap or corruption of data. A common precaution is to prefix identifiers with the project, organization, or standard name, as in "myproject.erc721.registry".

Preventing storage collisions through ASCII input restrictions

Diamond Storage identifiers are restricted to printable ASCII characters to mitigate storage collisions.

Solidity storage slot encodings produced by abi.encode(p) generally include non-printable bytes, such as null bytes (0x00), because of the padding rules. If identifiers could contain these bytes, a malicious developer could construct an identifier such as "config\x00\x00...". Such an identifier's byte sequence could coincide with input to keccak256 used to compute storage locations for mappings, dynamic arrays, strings, or bytes values. A collision could cause overwritten data, corrupted contract state, or security vulnerabilities.

Restricting identifiers to printable ASCII removes the ordinary padded-input form of this risk. It does not make collisions mathematically impossible. In theory, a sufficiently large storage layout position p could happen to contain only printable ASCII bytes, although this is considered extremely unlikely in practice. Using meaningful, human-readable identifiers makes the practical likelihood of such a collision negligible and helps protect the integrity and security of contract storage.

Safety of string literals

Solidity string literals are recommended for Diamond Storage identifiers because the compiler enforces the printable ASCII restriction for ordinary unescaped characters. Even within a string literal, however, Unicode escape sequences (\uNNNN) and hexadecimal escape sequences (\xNN) must not be used. Such sequences could introduce non-printable bytes into an identifier.

Risks of Unicode literals

Unicode literals, such as unicode"Hello 😃", must not be used to create Diamond Storage identifiers. They can contain non-printable bytes or characters, and visually identical but distinct characters could be used to disguise an identifier. For example, the Cyrillic character а (\u0430) looks identical to the ASCII character a (\u0061). Unicode also contains control characters that change the display direction of text. These properties can lead to unintended storage collisions or introduce security risks that are difficult to spot during code review.

Collision resistance of keccak256

The location of a Diamond Storage struct is determined by the output of the keccak256 hash function. The 256-bit contract storage address space is so large that the probability of a Diamond Storage struct being placed at the same location as existing storage by chance is statistically negligible. Solidity also uses keccak256 to compute storage locations for mappings, dynamic arrays, strings, and bytes values. These types benefit from the collision resistance of the same hash function.

References

Conclusion

This article covered how ERC8042 standardizes Diamond Storage, defining storage locations using human-readable strings.

If you have questions, feel free to contact me by DM on Twitter.

Twitter @cardene777

I also publish articles on the following platforms.