Proxy contracts are important tools for smart contract developers. Various proxy patterns have emerged to standardize the usage and implementation of proxy contracts. We have previously outlined upgradeable proxy contract security best practices. In this article, we introduce another proxy pattern that has gained traction in the developer community, the Diamond proxy pattern.
A diamond proxy contract, also known as a "diamond," is a design pattern for Ethereum smart contracts that is introduced by Ethereum Improvement Proposal (EIP) 2535. The diamond pattern allows a contract to have an unlimited number of functions by separating the contract's functions into smaller contracts called "facets." The diamond acts as a proxy that routes function calls to the appropriate facets.
The diamond pattern is designed to address the issue of the maximum contract size limit imposed by the Ethereum network. By breaking down a large contract into smaller facets, the diamond pattern allows developers to build more complex and feature-rich smart contracts that would otherwise exceed the size limit.
Diamond proxies offer significant flexibility compared to traditional upgradeable contracts. They allow for partial upgrades, or the ability to add, replace, or remove selected functionalities while leaving other parts untouched. They also circumvent the bytecode size limit of a single contract by delegating calls to different implementation contracts, thus allowing for more complex functionalities in one contract address. This article provides an overview of EIP-2535, including a comparison with the widely used Transparent Proxy Pattern and the UUPS Proxy Pattern, and its security considerations for the developer community.
In the context of EIP-2535, a “diamond” is a proxy contract with function implementations provided by different logic contracts called “facets.” Compared to traditional proxy patterns, the “diamond” is equivalent to the proxy contract, and different “facets” correspond to the implementation contracts. Different facets of one diamond proxy can share internal functions, libraries and state variables. The key components of a diamond are as follows:
Diamond: The central contract that acts as a proxy and routes function calls to the appropriate facets. It contains a mapping of function selectors to facet addresses.
Facets: Individual contracts that implement specific functionality. Each facet contains a set of functions that can be called by the diamond.
Diamond Loupe: A set of standard functions defined in EIP-2535 that provide information about the facets and function selectors used in the diamond. The diamond loupe allows developers and users to inspect and understand the structure of the diamond.
DiamondCut: A function used to add, replace, or remove facets and their corresponding function selectors in the diamond. Only an authorized address (e.g., the diamond's owner or a multi-signature contract) can perform a diamond cut.
Similar to traditional proxies, when there is a function call on a diamond proxy, the proxy’s fallback function is triggered. The main difference with diamond proxies is that in the fallback function there is a
selectorToFacet mapping that stores and determines which logic contract address has the implementation of the function that is being called. Then, it executes that function using
delegatecall just like a traditional proxy.
All proxies use the
fallback() function to delegate function calls to external addresses. Below is shown the implementation of the diamond proxy and the implementation of a traditional proxy. Note that the assembly code blocks are very similar, with the only difference being the
facet address in the
delegatecall of the diamond proxy, and the
impl address in the
delegatecall of the traditional proxy. The main difference is that in the diamond proxy, the
facet address is determined by a hashmap from the caller’s
msg.sig (function selector) to the facet
address, whereas in traditional proxy, the
impl address is not dependent on the caller input.
Diamond proxy fallback function
Traditional proxy fallback function
selectorToFacet mapping determines which contract contains the implementation of each function selector. The project team oftentime needs to be able to add, replace, or remove such function selector to implementation contract mapping. EIP-2535 specifies that a
diamondCut() function is mandatory for this purpose. A sample interface is shown below.
FacetCut struct contains a facet address and array of 4-bytes function selectors to be updated in a diamond proxy contract. The
FaceCutAction allows one to
Remove function selectors. The implementation of the
diamondCut() function should include adequate access control, prevent storage slot collision, revert on failure, and emit events appropriately.
In order to query which functions a diamond proxy has and which facets are used, the “diamond loupe” is used. A “diamond loupe’ is a special facet that implements the following interface defined in EIP-2535:
facets() function should return all facet addresses and their four byte function selectors. The
facetFunctionSelectors() function should return all the function selectors supported by a specific facet. The
facetAddresses() function should return all the facet addresses used by a diamond. The
facetAddress() function should return the facet that supports the given selector, or address(0) if not found. Note that there should not be more than one facet address that has the same function selector.
Given that the diamond proxy delegates different function calls to different implementation contracts, the proper management of storage slots to prevent collision is critically important. EIP-2535 referenced several possible storage slot management approaches.
A facet can declare state variables in structs. Any number of structs, each with a different storage position, can be used by a facet. Each struct is given a specific position in contract storage. Facets can declare their own state variables that do not conflict with the storage locations of state variables declared in other facets. A sample library and diamond storage contract is provided in EIP-2535, as shown below:
AppStorage is a specialized version of diamond storage. This pattern is used to more conveniently and easily share state variables between facets. An AppStorage struct is defined to contain an arbitrary number and type of state variables needed for an application. A facet always declares the AppStorage struct as the first and only state variable, in storage slot position 0. Different facets can then access the variables from the struct.
There can be other storage slot management strategies, including a mixture of diamond storage and AppStorage, such that some structs are shared amongst different facets, and some are unique to specific facets. In all cases, it is critically important to prevent accidental storage slot collisions.
The two main proxy patterns currently used by the Web3 developer community are the transparent proxy pattern and the UUPS proxy pattern. In this section, we briefly compare the diamond proxy pattern with the transparent proxy and the UUPS proxy patterns.
Proxies and upgradeable solutions are complex systems, and OpenZeppelin provides library code and comprehensive documentation for UUPS/Transparent/Beacon upgradeable proxies. However, for the diamond proxy pattern, while OpenZeppelin has affirmed its benefits, they have decided not to include the implementation of the EIP-2535 Diamonds in their libraries. Developers using existing third-party libraries or implementing the solution on their own must exercise extra caution in their implementation. Therefore, we have compiled a list of security best practices for the developer community's reference.
By breaking up the contract logic into smaller, more manageable modules, developers can more easily test and audit their code. Additionally, this approach allows developers to focus on building and maintaining specific facets of a contract, rather than managing a complex, monolithic codebase. The end result is a more flexible and modular codebase that can be easily updated and modified without affecting other parts of the contract.
Source: Aavegotchi Github
DiamondCut facet contract address during deployment
When the diamond proxy contract is deployed, it must add the address of the
DiamondCutFacet contract to the Diamond proxy contract, with the
diamondCut() function implemented. The
diamondCut() function is used to add, remove or replace facets and functions, and the Diamond proxy cannot work properly without
Source: Mugen’s Diamond-3-Hardhat
When adding new state variables to a storage struct in a smart contract, it is important to add them to the end of the struct. Adding new state variables to the beginning or middle of a struct can cause the new state variable to overwrite existing state variable data, and any state variables after the new state variable will likely reference the wrong storage location.
AppStorage pattern, do not declare and use state variables outside the struct
AppStorage pattern requires that one and only one struct is declared for a diamond proxy, and the struct is shared by all facets. If multiple structs are desired or needed, the
DiamondStorage pattern should be used instead.
Do not put structs directly in another struct unless you don’t plan on ever adding more state variables to the inner structs. You won't be able to add new state variables to inner structs in upgrades without overwriting the storage slot of variables declared after the struct.
The solution is to add new state variables to the structs that are stored in mappings, rather than putting structs directly in structs, as the storage slot for variables in mappings is calculated differently and is not continuous in storage.
When a new state variable is added to a struct, it changes the size and layout of the struct. This can cause problems if the struct is used as an element in an array, as the size of the array will be affected by the size of the struct. If the size and layout of the struct is changed, then the size and layout of the array will also change, which can lead to issues with indexing or other operations that rely on the size and layout of the struct being consistent.
Similar to other proxy patterns, each variable should have a unique storage slot. Otherwise, two different structs at the same location will overwrite each other.
initialize() function unprotected
initialize() function is commonly used to set important variables such as the address of privileged roles. If left uninitialized when the contract is deployed, a bad actor could call it and take control of the contract.
The recommendation is to include proper access control on the
setter functions, or ensure that the function is called when the contract is deployed and cannot be called again.
If any facet in a contract is able to call the
selfdestruct() function, it can potentially destroy the entire contract and cause a loss of funds or data. This is particularly dangerous in the diamond proxy pattern, where multiple facets may have access to the proxy contract's storage and data.
We have seen an increasing number of projects adopting the Diamond proxy pattern in their smart contracts, due to its flexibility and other advantages compared to traditional proxies. However, the additional flexibility could also mean a broader attack surface for malicious actors. We hope this article is useful to the developer community in understanding the mechanics of the diamond proxy pattern and its security considerations. Project teams should conduct rigorous testing and third party audits to reduce the risk of exploits related to implementation of diamond proxy contracts.