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 covers ERC2535, the Diamond pattern for modular and upgradeable smart contracts.

This explanation translates, summarizes, and expands on the following specification.

Overview

The standard proposes a flexible mechanism for managing upgradeable smart contracts.

For background on smart contract upgrades, see the following resources.

https://chaldene.net/upgradable-contracts

This architecture is called a diamond. A diamond can be upgraded or extended after its deployment. As a modular smart contract system, it can distribute functionality across contracts rather than requiring all functionality to fit within one contract's bytecode size limit.

34.png

A diamond is a contract exposing externally callable functions. The implementation of those functions can reside in separate contracts called facets. Facets are deployed independently and can share internal logic, libraries, and state through an appropriate storage layout in the diamond.

Imagine a diamond as a gemstone made up of several facets. Each facet provides functionality, and the functions exposed by the diamond can be added or replaced as needed. This makes the overall smart contract system modular and extensible.

35.png

Motivation

Extensive functionality at a single contract address

One advantage of diamonds is the ability to expose functionality through a single address. Different facets provide different functions, all accessible through the diamond. This simplifies integration, testing, and interaction with other contracts, software, and user interfaces.

Exceeding the approximately 24 KB contract size limit

When the combined implementation exceeds the approximately 24 KB deployed-code limit, related functionality may still need to be exposed through one contract address. A diamond addresses this by distributing code among facets; each deployed contract remains subject to the applicable individual code size limit.

An individual Ethereum contract has a deployed runtime code size limit of approximately 24 KB under EIP170. The proposed architecture addresses this constraint by separating functionality into independently deployed contracts and delegating execution to them.

Organizing contract code and data

For systems with several functions, diamonds provide a way to separate functionality, compose it, and share data where needed. This allows functionality to be combined while considering gas efficiency.

Upgrading functionality

Upgradeable diamonds can be updated by adding, replacing, or removing functions. Because the combined implementation is distributed across facets, functionality can continue to grow beyond the size limit of an individual contract. A subset of functions can be upgraded without redeploying all the unchanged functionality or replacing the diamond address.

Immutable diamonds

A diamond can be deployed as immutable, or an upgradeable diamond can later be made immutable by eliminating its ability to change functionality. This preserves contract state while removing the corresponding upgrade risks, provided all upgrade paths are disabled.

An immutable contract cannot have its code or exposed function routing changed through an upgrade mechanism. An upgradeable contract, by contrast, retains some mechanism for changing its implementation.

Reusing deployed contracts

Instead of deploying new facets for every diamond, existing compatible on-chain contracts can be reused. Reusing deployed facets allows customized diamonds to be assembled. This can be useful when building new smart contract platforms or reusable contract libraries.

Reusing existing contracts also offers the following potential benefits.

Lower costs Contract deployment consumes gas. Reusing compatible deployed contracts can avoid additional deployment gas for the same implementation.

Less deployment work Contract deployment requires preparation and transaction confirmation. Reusing deployed contracts avoids some of the work and time required to deploy them from scratch. This is particularly useful when creating multiple diamonds that use common functionality.

Code reliability Existing contracts may have a history of testing and production use. A prior audit can provide additional evidence of their reliability. However, reusing previously tested code does not guarantee correctness in a new diamond; storage compatibility and interactions still need review.

Contract compatibility Existing contracts may already have been integrated into other projects and contracts. Reusing compatible interfaces and functionality can simplify the development of compatible dApps.

This standard improves upon EIP1538.

Sharing facets

A deployed facet can be shared by multiple diamonds. The following diagram illustrates the same facets being used by different diamonds.

  • Diamond1 uses FacetA.
  • Diamond2 uses FacetA.
  • Diamond1 uses FacetB.
  • Diamond2 uses FacetB.
  • Diamond1 manages its own data for FacetA and FacetB.
  • Diamond2 manages its own data for FacetA and FacetB.

This enables implementation code to be shared while each diamond retains its own state.

facetreuse.png

Upgradeable diamonds and centralized private databases

The following discusses differences between upgradeable diamonds and centralized private databases.

Decentralized autonomous organizations (DAOs) and upgrades

An upgradeable diamond can be governed through a mechanism such as a decentralized autonomous organization. This allows upgrades to be authorized according to the community's governance rules.

Integration with the Ethereum ecosystem

Upgradeable diamonds can integrate with the Ethereum ecosystem. This facilitates interaction with other contracts and applications and enables composition of complex functionality.

Transparency and verifiable history

Public on-chain storage and verified source code can make diamond functionality and its change history transparent. These properties provide evidence that users can inspect when assessing the contract's trustworthiness.

Detecting issues through transparency

Publicly inspectable state and change history can help observers identify and respond to problems or misconduct. Transparency makes community monitoring possible, although it does not automatically reveal every vulnerability.

Security and expert audits

Security and domain experts can audit the change history of an upgradeable diamond. Such review can improve confidence in the code and its operation.

Making a diamond immutable

An upgradeable diamond can later be made immutable. Removing every implementation-change path can keep its exposed functionality fixed while allowing state changes through its existing functions.

Upgradeable diamonds can support transparent, collectively governed improvements and provide verifiable evidence about their evolution. Centralized private databases do not necessarily provide the same public transparency or governance properties.

Benefits of diamonds

1. Functionality at a stable address

A diamond provides its exposed functionality through a stable address.

A smart contract is deployed at a particular address. Without an upgrade or delegation mechanism, adding functionality may require deploying a new contract at another address.

A diamond instead combines different implementations and versions of functions through one address. Users and other contracts can continue interacting with that address to access the diamond's functionality. New functions can be exposed through newly added facets without changing the diamond's address.

Consider a practical example. Suppose a project develops a smart contract containing several functions. With a conventional non-upgradeable contract, adding functionality requires deploying a new implementation at another address. With a diamond, new functionality can be attached to the existing diamond address. Users continue using the same address while gaining access to the additional functions.

A diamond thus combines multiple functions behind a stable address, simplifying integration.

The following resource provides background on upgradeable contracts.

https://chaldene.net/upgradable-contracts

Understanding Smart Contract Upgrades

2. Multiple functions at one address

A diamond combines functionality from independently deployed facets through one address. Facets provide separate implementations and can share internal logic, libraries, and state variables through compatible storage layouts.

3. Events emitted from one address

Events emitted by delegate-called facet code originate from the diamond address, simplifying event processing.

4. Atomic changes to multiple functions

A diamond can atomically add, replace, and remove multiple external functions in one transaction.

Upgrading a conventional non-upgradeable system may require deploying a new contract and migrating data from the old one. This can be complex and require multiple transactions.

Diamonds provide a mechanism for simplifying the activation of an upgrade. For example, adding functionality to a non-upgradeable contract would require deploying a replacement and changing the address used by clients. A diamond can instead atomically activate the new function mappings in a single transaction after the required facets have been deployed.

Suppose a diamond currently offers two functions: payment and transfer. To add a new function called bounce in this illustrative example, submit a cut transaction referencing the new facet implementation. The transaction atomically exposes the new function through the diamond. Other existing function mappings can remain unchanged, although interactions and shared state still need to be tested.

The same approach applies to replacing or removing existing functions. The required function mapping changes can be grouped into one transaction rather than separate update transactions.

Atomic operations An atomic operation consists of steps that succeed or fail together. Either every step takes effect or none does; no partially committed result remains.

Atomicity is important for maintaining consistency and reliable transactions. Smart contract operations often require several steps to occur in a particular order. Atomicity ensures that a failure reverting the operation also rolls back the associated state changes.

Consider what it means to atomically add, replace, and remove multiple external functions in a diamond. Multiple mapping changes are executed within one transaction. If a required change fails and reverts the transaction, the other changes are rolled back. Either all changes take effect or none of them do. This property is important for preserving state consistency.

5. Fine-grained upgrades

Diamonds support fine-grained upgrades by changing only the function mappings that need updating.

6. Control over exposed functions

Diamonds allow granular control over which functions are available and when.

A diamond is composed of multiple independently deployed facets. Each facet provides particular functionality. The diamond combines selected functions from those facets.

Consider the following ways to manage exposed functions.

Controlling function availability and timing Particular facets contain the functions providing the required functionality. Authorized diamond governance controls which facets supply the exposed functions. Functions can also be enabled or disabled at specified times through the relevant management mechanism.

Adding and removing functionality New functionality can be exposed by adding function selectors associated with a new facet. Similarly, removing selectors for unnecessary functionality changes what the diamond exposes.

Enabling and disabling functions based on conditions A design can allow particular functions to be enabled or disabled in response to specified events or conditions. This allows functionality to be made available or restricted as required.

Composing functionality Facets are separate contracts providing different functionality. Authorized administrators or governance can compose their exposed functions into a diamond with the desired capabilities.

This flexibility allows applications to customize which functionality is available and when.

7. Upgrades through DAOs and governance

A diamond can be upgraded through authorization mechanisms such as a DAO or a multisignature contract.

Upgrading through a decentralized autonomous organization (DAO)

Consider a project that builds its smart contract system using a diamond. The project's community wishes to add functionality or fix a bug. A DAO can govern the upgrade.

  1. Proposal and voting Participants submit an upgrade proposal through the DAO's governance system. The proposal describes the new functionality or requested changes.

  2. Community approval DAO participants vote on the proposal according to its governance rules. Under a simple majority rule, a proposal receiving the required majority can be accepted.

  3. Execute the upgrade After the proposal is approved, the DAO executes or authorizes the diamond upgrade transaction. The requested functions are added or changed.

Upgrading through a multisignature contract

As another example, a project team provides a service using a diamond. The team wants to upgrade the diamond to improve the service or its security. A multisignature contract can authorize the operation.

  1. Configure the multisignature contract The team establishes a multisignature contract requiring approval from a configured threshold of key holders.

  2. Propose the upgrade The team prepares the proposed upgrade and initiates the multisignature approval process. The proposal includes the changes and the rationale.

  3. Obtain key-holder approvals Key holders review the proposal and assess its necessity and potential impact. The upgrade is authorized when the required approval threshold is met.

  4. Execute the upgrade Once approved, the multisignature contract executes the upgrade transaction, activating the new diamond functionality at the existing address.

These examples illustrate how a DAO or multisignature contract can coordinate authorization and execution of diamond upgrades.

8. Events identifying changes

Diamonds emit events recording changes to exposed functions.

9. Displaying change history

The upgrade history can be displayed to support transparency and review.

10. Displaying current state

The diamond's current facets and exposed function selectors can be inspected.

11. Immutable diamonds

An upgradeable diamond can later be made immutable.

12. Addressing contract code size limits

A diamond distributes functionality across facets, so the total implementation can exceed the runtime bytecode limit of one contract.

13. Separating and combining functionality

Functionality can be separated into different facets and composed through a diamond.

14. Reusing existing contracts

Diamonds can be assembled using compatible deployed facets.

15. Organizing code

Diamonds and facets provide a modular approach to organizing contract code.

16. Large-scale modularity

Even large diamond systems can be organized into modules to simplify management.

17. Gas savings

Combining functionality behind one diamond can reduce gas consumption in appropriate workflows.

Interactions with multiple separate contracts can incur additional call overhead. A diamond can combine their functionality within one execution context and transaction. This may reduce overhead associated with external interactions and separate transactions.

Facet implementations can share the diamond's storage layout, and common internal functions can be compiled into the relevant facets. This can make shared data access and state updates more efficient. As a result, some workflows involving several operations may consume less gas, although the savings depend on the implementation.

Compare invoking several contracts individually with executing compatible functionality through one diamond. Separate interactions may incur additional overhead, whereas combining operations can reduce it. A diamond's own selector lookup and delegate calls also consume gas.

18. Optimizing external functions

Facets can share internal function implementations to support gas-efficient designs.

19. Optimizing particular use cases

A diamond can expose specialized external functions optimized for common workflows.

20. Supporting tooling and user interfaces

The diamond architecture supports development tools and user interfaces.

Together, these features support modular smart contract design and development.

Specification

Terminology

Diamond

Here, a diamond refers to a smart contract rather than a gemstone. It associates function selectors with separate implementation contracts called facets and delegates calls to the appropriate facet. The diamond maintains its own contract storage.

Facet

A facet is a smart contract or deployed Solidity library providing functions to a diamond. Facets provide externally callable functions. A diamond can combine functions supplied by multiple independent facets. When executed through the diamond using delegatecall, a facet's state accesses operate on the diamond's storage rather than its own deployed storage.

Loupe facet

A loupe facet provides introspection functions for a diamond. These functions expose information about the diamond's facets and function selectors.

Immutable function

An immutable function is a function of the diamond that cannot be replaced or removed. It is fixed as part of the diamond's available functionality.

Mapping

In this context, a mapping means an association between two elements. The term describes the association without prescribing its implementation.

Contract

The term encompasses smart contracts and Solidity libraries.

Unless otherwise stated, references to functions in this discussion mean externally callable functions rather than Solidity internal functions. References to external functions also apply to public functions.

Overview

Diamond overview A diamond invokes functions supplied by facets through delegatecall.

Gemstone analogy: A gemstone diamond is shaped by cutting its facets. Similarly, a smart contract diamond is shaped by adding, replacing, or removing the functions supplied by facets.

The analogy illustrates the relationship between a diamond and its facets.

Notes on implementing interfaces

Interface implementation A diamond can implement a particular interface in either of two ways. One is to implement the interface directly in the diamond contract (for example, contract Contract is Interface). The other is to expose the required functions through the diamond's facets. Both approaches are permitted by this proposal.

Fallback function

When an externally callable function is invoked and is not implemented directly in the diamond, its fallback function handles the call. The fallback uses the four-byte function selector at the beginning of the calldata to locate the corresponding facet. It then executes that facet's implementation through delegatecall.

The fallback and delegatecall make the facet function behave as though it were implemented at the diamond address. The original call's msg.sender and msg.value are preserved, while direct storage reads and writes through the delegated code use the diamond's storage.

Consider the following example. A diamond has three facets, each implementing different functions. When a mapped function is called on the diamond, the fallback selects the facet using the function selector and delegates execution to it. This allows function mappings to be added, replaced, or removed without changing the diamond address.

The mechanism supports modular smart contract design and upgrades.

For more about delegatecall and its execution context, see the following resource.

https://chaldene.net/solidity-delegatecall

https://chaldene.net/upgradable-contracts

Understanding Smart Contract Upgrades

javascript
// Find facet for function that is called and execute the
// function if a facet is found and return any value.
fallback() external payable {
  // get facet from function selector
  address facet = selectorTofacet[msg.sig];
  require(facet != address(0));
  // Execute external function from facet using delegatecall and return any value.
  assembly {
    // copy function selector and any arguments
    calldatacopy(0, 0, calldatasize())
    // execute function call using the facet
    let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
    // get any return value
    returndatacopy(0, 0, returndatasize())
    // return any return value or error back to the caller
    switch result
      case 0 {revert(0, returndatasize())}
      default {return (0, returndatasize())}
  }
}

The following diagram illustrates the diamond structure.

DiamondDiagram.png

As described above, the example has FacetA through FacetC. Functions 1 through 7 are defined across these facets, and the diamond maintains their routing information. The diamond looks up the called selector and invokes the corresponding implementation.

Function selectors A function selector is the first four bytes of the Keccak-256 hash of the canonical function signature, including the function name and parameter types. Why use only four bytes rather than the entire function signature hash? A compact selector reduces calldata and dispatch overhead, at the cost of a finite selector space and possible collisions. For details, see the following article.

https://rootbabu.medium.com/function-selector-solidity-day26-573bbeec8186

Storage

The following summarizes the storage considerations.

Storage:

Diamonds and proxy contracts need storage layouts that allow independent implementations to share state without unintended collisions. The standard does not prescribe a specific layout; separate proposals or conventions may define suitable patterns. Examples of patterns suitable for diamonds include Diamond Storage and AppStorage.

Diamond Storage Diamond Storage is a common pattern for managing a diamond's storage. It assigns a designated storage location to a particular struct or module. The diamond's storage layout can thus be organized into separate namespaces for different functionality. This helps prevent accidental storage collisions while allowing facets to share explicitly defined storage structures.

AppStorage AppStorage is another pattern for organizing diamond storage. It typically uses a shared application-level struct at a consistent storage location, accessed by compatible facets. The layout can organize application data for sharing among facets; it does not enforce isolation from arbitrary delegated code.

These patterns help facets manage shared state and support modular code organization. Either can be adapted to a diamond's requirements, provided layout compatibility is maintained.

Facets can share state variables by using the same struct at the same storage location. They can also share internal logic by inheriting common contracts or using common libraries. This allows separate facet implementations to share state and functionality.

The following diagram illustrates designated private-to-module and shared storage regions.

diamondstorage1.png

All illustrated data reside in the diamond's storage. Different facets are designed to access different regions, although the EVM does not enforce this separation for delegate-called code.

The intended layout is as follows.

  • FacetA accesses DataA.
  • FacetB accesses DataB.
  • The diamond's own code accesses DataD.
  • FacetA and FacetB share access to DataAB.
  • The diamond's own code, FacetA, and FacetB share access to DataABD.

This layout allows distinct facets to share selected state while organizing their separate responsibilities.

Solidity libraries as facets

Both smart contracts and deployed Solidity libraries can serve as diamond facets.

A Solidity library must expose at least one externally callable function to serve as a useful deployed facet.

A library containing only internal functions does not provide externally callable functions for use as a diamond facet. Instead, its internal functions are compiled into the bytecode of the facets or contracts using them. This enables reuse of internal function implementations. An internal-only library therefore cannot itself supply external functions as a facet.

Solidity library facets have the following properties.

  • The deployed library code is separate from the diamond.
    • Its mapped selectors can still be removed from the diamond; the original description of permanence concerns the deployed code rather than the selector mapping.
  • Solidity libraries cannot declare ordinary nonconstant state variables.
    • When executed via delegatecall, their code can still access the diamond's storage.
  • Storage references can be obtained through patterns such as Diamond Storage rather than ordinary state-variable declarations.

Solidity libraries can support internal logic sharing, code reuse, and modular diamond implementations.

Adding, replacing, and removing functions

IDiamond interface

Diamonds must expose the event defined by the IDiamond interface. It provides a standardized record of changes to diamond functionality.

At diamond deployment

When the diamond is deployed, its initially exposed external functions, including any immutable functions, are recorded through DiamondCut events. This makes the initial function set observable.

When functions are added, replaced, or removed

A DiamondCut event must be emitted when external functions are added, replaced, or removed. This applies to each change to the diamond's exposed function mappings. The changes are therefore publicly recorded through DiamondCut events.

The event history supports transparency around upgrades and functionality changes. Users and developers can track when the diamond's function mappings changed.

javascript
interface IDiamond {
    enum FacetCutAction {Add, Replace, Remove}
    // Add=0, Replace=1, Remove=2

    struct FacetCut {
        address facetAddress;
        FacetCutAction action;
        bytes4[] functionSelectors;
    }

    event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}
FacetCutAction

An enum representing an action on the diamond's function mappings.

  • Add (addition) = 0.
  • Replace (replacement) = 1.
  • Remove (removal) = 2.
FacetCut

A struct holding information about changes to a diamond's function mappings.

  • facetAddress
    • Address of the facet involved in the operation, subject to the action's requirements.
  • action
    • Action to perform: add, replace, or remove.
  • functionSelectors
    • Array of four-byte function selectors.
DiamondCut

An event emitted when functions are added, replaced, or removed from the diamond. Records changes to the diamond's exposed functionality.

  • _diamondCut
    • Array of FacetCut structs describing the changes.
  • _init
    • Address containing initialization code.
  • _calldata
    • Initialization calldata.

IDiamondCut interface

Mapping function selectors to facet addresses

A diamond maintains an association between function selectors and facet addresses. Adding, replacing, or removing functions changes this association.

Implementing IDiamondCut

A diamond that supports changing its function mappings after deployment must implement the specified IDiamondCut interface. The interface provides standardized management of selector-to-address mappings.

Role of diamondCut

The diamondCut function adds, replaces, or removes multiple functions from one or more facets in a single transaction. Executing related changes within one transaction prevents inconsistent intermediate configurations from being committed between separate upgrade transactions.

Related changes can also be applied atomically, helping preserve a consistent state.

Purpose of diamondCut

The standard specifies diamondCut for interoperability. Diamond tooling, software, and user interfaces can rely on the standardized cut function. This provides a consistent way for different applications and tools to manage upgrades.

The diamondCut function manages changes to selector-to-facet mappings and supports atomic upgrades. Secure authorization and initialization remain implementation responsibilities.

javascript
interface IDiamondCut is IDiamond {
    /// @notice Add/replace/remove any number of functions and optionally execute
    ///         a function with delegatecall
    /// @param _diamondCut Contains the facet addresses and function selectors
    /// @param _init The address of the contract or facet to execute _calldata
    /// @param _calldata A function call, including function selector and arguments
    ///                  _calldata is executed with delegatecall on _init
    function diamondCut(
        FacetCut[] calldata _diamondCut,
        address _init,
        bytes calldata _calldata
    ) external;
}
diamondCut

A function for changing or upgrading a diamond. It supports changing multiple functions associated with multiple facets within one transaction.

  • _diamondCut
    • Array containing facet addresses, actions, and function selectors.
    • Specifies which functions are added, replaced, or removed.
  • _init
    • Address of the contract or facet containing the code to execute with _calldata.
    • The code at this address is invoked with the supplied calldata through delegatecall.
  • _calldata
    • Encoded function call containing the selector and arguments.
    • The initialization call is executed against _init using delegatecall in the diamond's context.
The _diamondCut argument and FacetCut struct

The _diamondCut argument is an array of FacetCut structs. Each struct contains the facet address, action, and selectors to update.

For each FacetCut struct:

  • For Add, add the selector mapping.
    • Revert if a selector is already mapped.
  • For Replace, replace the selector mapping.
    • Revert if the selector already maps to the same facet or is not mapped.
  • For Remove, remove the selector mapping.
    • Revert if the selector was not previously mapped.
  • Attempts to replace or remove an immutable function must revert.
Executing _calldata

After the function mapping changes, execute _calldata against _init through delegatecall when applicable. This supports initialization, data setup, or cleanup following additions, replacements, and removals.

If _init is address(0), the delegate call is skipped. Under the specification described here, _calldata may be empty or contain custom information in that case; particular implementations can impose stricter requirements.

Together, the cut and initialization calldata support atomic changes to diamond functionality and state.

Inspecting facets and functions

Loupe and IDiamondLoupe

A loupe is a small magnifying instrument used to inspect gemstones.

Implementing IDiamondLoupe

Diamonds must implement IDiamondLoupe to expose information about their facets and functions. The interface allows tools to inspect the structure and exposed function selectors.

Like a jeweler's loupe, IDiamondLoupe enables inspection of the diamond's internal organization.

IDiamondLoupe interface

javascript
// A loupe is a small magnifying glass used to look at diamonds.
// These functions look at diamonds
interface IDiamondLoupe {
    struct Facet {
        address facetAddress;
        bytes4[] functionSelectors;
    }

    /// @notice Gets all facet addresses and their four byte function selectors.
    /// @return facets_ Facet
    function facets() external view returns (Facet[] memory facets_);

    /// @notice Gets all the function selectors supported by a specific facet.
    /// @param _facet The facet address.
    /// @return facetFunctionSelectors_
    function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_);

    /// @notice Get all the facet addresses used by a diamond.
    /// @return facetAddresses_
    function facetAddresses() external view returns (address[] memory facetAddresses_);

    /// @notice Gets the facet that supports the given selector.
    /// @dev If facet is not found return address(0).
    /// @param _functionSelector The function selector.
    /// @return facetAddress_ The facet address.
    function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);
}
Facet

Overview A struct holding a facet address and the list of function selectors exposed through that facet.

Parameters

  • facetAddress
    • Facet address.
  • functionSelectors
    • Array of function selectors exposed through the facet.

facets

Overview Returns all facet addresses and their associated function selectors.

Parameters None.

Return value

  • facets_
    • Array of Facet structs.
    • Each struct contains a facet address and its associated selectors.

facetFunctionSelectors

Overview Returns the function selectors associated with a specified facet.

Parameters

  • _facet
    • Facet address.

Return value

  • facetFunctionSelectors_
    • An array of bytes4 values.
    • The selectors exposed through the specified facet.

facetAddresses

Overview Returns all facet addresses used by the diamond.

Parameters None.

Return value

  • facetAddresses_
    • An array of addresses.
    • The facet addresses used by the diamond.

facetAddress

Overview Returns the facet address associated with the specified selector.

Parameters

  • _functionSelector
    • Function selector (bytes4).

Return value

  • facetAddress_
    • Facet address.
    • Returns address(0) if no facet is associated with the selector.

Inspect the reference implementation The reference implementation illustrates concrete ways to implement IDiamondLoupe. It provides useful examples for applying the interface in a project.

Using loupe functions Loupe functions can be used by user interface software. A user interface can call them to display the diamond's structure and functionality. This helps users understand the functions available through the diamond.

Use cases for loupe functions Loupe functions are useful to deployment, upgrade, and other diamond management tools. For example, an upgrade tool can inspect which facets currently supply particular selectors. Tests can also retrieve selector and facet information to verify the expected configuration.

These functions support managing and inspecting diamonds through a standard interface.

Implementation requirements

Diamond requirements

  • A diamond must have a fallback function and may have zero or more immutable functions.
    • Immutable functions are defined directly in the diamond.
  • Associate function selectors with facets.
    • This determines which implementation supplies each exposed function.
  • When a function is called on the diamond, directly defined immutable functions take precedence.
    • A matching immutable function executes directly.
    • Otherwise, the fallback handles the call.
    • The fallback finds the facet associated with the selector and invokes its implementation through delegatecall.
    • If no facet is associated with the selector, an optional default function may handle the call.
    • If neither a facet nor an applicable default mechanism exists, execution reverts.
  • Emit DiamondCut whenever functions are added, replaced, or removed.
    • This makes changes observable and traceable.
  • Implement the IDiamondLoupe interface.
    • This provides information about the diamond's facets and function selectors.

Immutable functions

  • Record immutable functions as additions through DiamondCut events.
  • Loupe functions must provide information about immutable functions.
  • The facet address reported for an immutable function is the diamond's own address.
  • Attempts to remove or replace an immutable function must revert.

Optional implementation features

  • A diamond may implement EIP165 supportsInterface.
  • This allows clients to detect supported interfaces.
  • For example, a diamond implementing the cut interface can report support for the interface ID IDiamondCut.diamondCut.selector.
  • Similarly, it can report support for the diamond loupe interface ID.
  • This facilitates integration with other contracts and tools.

These interfaces define common functionality for operating and managing diamonds. They support a flexible architecture for user interfaces, testing, and upgrade tooling.

Additional considerations

Using function selectors

User interfaces can retrieve function selectors and facet addresses to determine which functions are currently exposed. They can use this information, together with the appropriate ABI, to display and invoke the functions.

Gas considerations

Selector lookup and execution through delegatecall add gas overhead, which may be mitigated in the following ways.

  • The total diamond implementation can exceed the individual contract code size limit, allowing specialized gas-saving functions to be added.
    • For example, a diamond implementing ERC721 may also expose a convenient, optimized batch transfer function.
  • Some contract architectures require interactions with several contracts within one transaction.
    • Combining compatible functionality within a diamond may reduce external call and storage-access overhead.
  • Facets may contain only a small number of external functions, potentially reducing dispatch costs.
    • The dispatch cost depends on the compiler and generated bytecode, and larger dispatchers may consume more gas.
  • Some Solidity optimizer configurations trade larger bytecode for lower runtime gas consumption; the effect depends on the code and settings.

Retrieving function version information

Software and users can identify a function's current implementation by retrieving its facet address. Call facetAddress from the IDiamondLoupe interface. This function accepts a selector and returns its associated facet address.

Default functions

Solidity's fallback function can handle calls that do not match a defined function. A diamond may optionally implement an analogous default behavior for unmapped selectors. This default function handles calls for which the diamond has no explicit selector mapping.

The standard does not prescribe a specific implementation for default functions. Developers can choose how to implement the optional behavior.

Loupe functions and DiamondCut events

For a conventional contract, verified source code can help identify its functions.

A diamond's own verified source does not necessarily list all functions currently supplied through its facets. Additional introspection is therefore necessary.

Diamonds expose four standardized loupe functions that describe their current facets and associated function selectors.

These functions support the following use cases.

  • Display all currently exposed function selectors.
  • Query services such as Etherscan or local files to retrieve verified source code for the relevant facets.
  • Retrieve the relevant ABI information from explorers or other sources.
  • Test and verify whether transactions adding, replacing, or removing selectors succeeded.
  • Check available functions before invoking the diamond.
  • Support deployment and upgrade tools and programming libraries.
  • Help user interfaces display diamond information and invoke its functions.

The loupe interface gives users, libraries, and developer tools a common mechanism for inspecting diamond functionality.

Diamonds also support transparency by recording the history of changes to exposed functions. This history is recorded through DiamondCut events. The events are emitted when functions are added, replaced, or removed.

This allows observers to reconstruct and inspect the mapping change history. Transparent upgrade records provide evidence for assessing changes. The history is also useful when evaluating operation and security.

Sharing functions across facets

When a facet needs functionality defined elsewhere, several implementation approaches are available.

1. Copy internal function code

Copy an internal function implementation into another facet. This makes the logic available in multiple facets but may duplicate code.

2. Inherit a common contract

Define a common contract containing internal functions and have multiple facets inherit it. This centralizes source-code maintenance, though it can introduce deeper inheritance hierarchies and still duplicate compiled code.

3. Use Solidity libraries

Place common internal functions in a Solidity library and use that library in the relevant facets. This centralizes the shared source-code implementation.

4. Safely call a function exposed by another facet

An external function supplied by another facet can be invoked using an appropriate calling mechanism. Choose the target and call context carefully: a normal external call to a facet address uses that facet's own state, while a call through the diamond uses its configured routing.

5. Use delegatecall

A facet can use an appropriate delegate call to invoke another facet implementation within the diamond's execution context. delegatecall executes code at another address while retaining the caller's storage context and the original message sender and value.

javascript
DiamondStorage storage ds = diamondStorage();
bytes4 functionSelector = bytes4(keccak256("myFunction(uint256)"));
// get facet address of function
address facet = ds.selectorToFacet[functionSelector];
bytes memory myFunctionCall = abi.encodeWithSelector(functionSelector, 4);
(bool success, bytes memory result) = address(facet).delegatecall(myFunctionCall);

6. Create an internal version of a function

An internal implementation can also be provided instead of calling another facet's external function. Relevant facets can share this internal implementation through an appropriate source-code reuse pattern.

Facet reusability and composability

Facets provide a flexible mechanism for reusing and composing functionality.

1. Reusable facets

Once deployed, a compatible facet can be reused by multiple diamonds. This reduces duplicated implementation deployment and development work.

2. Combining different facets

Different combinations of facets can provide different sets of diamond functions. Each diamond can therefore be configured with a suitable combination.

3. Creating reusable facet sets

Sets of facets providing particular functionality can be assembled and reused across multiple diamonds. Reusing deployed facet sets can save time and deployment costs when creating new diamonds.

4. Facet composition

Facets can be combined with other facets. This supports integration and composition of functionality. A design may also impose compatibility constraints preventing unsuitable facet combinations.

5. Function signatures

Canonical function signatures are used to derive function selectors. Two external functions with the same selector cannot be exposed simultaneously through different mappings in the same diamond. Each selector identifies one exposed implementation at a time.

6. Selecting functions from a facet

A diamond can expose only a subset of a facet's external functions. This allows the diamond to include only the functionality it requires.

Backward compatibility

The architecture allows an upgradeable diamond to adapt to future standards and functionality. It can add new functions and replace or remove existing ones where authorized. Upgrades can address new requirements, although preserving compatibility for existing callers remains a design responsibility.

Reference implementation

The implementations are available through the following resource.

Source: https://eips.ethereum.org/EIPS/eip-2535

Security considerations

Ownership and authorization

⚠️ Note The design and implementation of diamond ownership and authorization are outside the scope of this standard. Examples in the standard and reference implementations illustrate possible approaches.

The proposal permits a variety of ownership and authorization schemes. These can range from simple coarse-grained controls to complex fine-grained policies. The standard does not mandate a particular authorization design. For example, one account could be authorized to add, replace, and remove functions. Alternatively, a DAO could have authority to change only particular functions.

Collective approval mechanisms can also be implemented. For example, an authorization function could require approval from several parties before executing a diamondCut. These are illustrative examples.

Development of ownership, control, and authorization standards and implementations for diamonds is encouraged.

Arbitrary execution through diamondCut

The diamondCut function can execute arbitrary initialization code through delegatecall with access to the diamond's storage. Access to this function must be carefully restricted.

Avoiding selfdestruct

Using selfdestruct in facets is strongly discouraged. Under historical EVM semantics, misuse could delete a diamond or facet. The precise deletion behavior depends on the active network rules; delegated code remains capable of dangerous state and balance effects.

Function selector collisions

A collision occurs when two different canonical function signatures yield the same four-byte selector. Without appropriate checks, adding a function with a colliding selector might inadvertently overwrite the existing mapping. A correctly implemented diamondCut rejects additions of selectors that are already mapped, preventing this accidental replacement through the Add action.

Transparency

A diamond emits events whenever one or more functions are added, replaced, or removed. The corresponding source code can be independently verified when available. This enables observers and software to monitor changes to the contract. An unauthorized or malicious function addition can be investigated through its recorded mapping change and implementation code.

Security and domain experts can review the diamond's change history for suspicious changes.

References

Nick Mudge (@mudgen), "ERC-2535: Diamonds, Multi-Facet Proxy," Ethereum Improvement Proposals, no. 2535, February 2020. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-2535.

Conclusion

This article covered ERC2535 and its Diamond pattern for modular and upgradeable smart contracts. I hope it helped clarify the architecture.

If you have questions, feel free to reach out through Twitter DM.

Twitter @cardene777