Cointime

Download App
iOS & Android

Diamond Proxy Contracts: Best Practices

Validated Project

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.

What is a Diamond Proxy?

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.

Architecture

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.

Fallback Function Implementation

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

Adding, Replacing, and Removing Facets

The 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.

Each 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 AddReplace, and 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.

Querying Facets

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:

The 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.

Storage Slot Management

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.

Diamond Storage

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

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.

Other

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.

Comparison with Transparent Proxies and UUPS Proxies

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.

  1. EIP-2535
  2. EIP-1967
  3. Diamond proxy reference implementation
  4. OpenZeppelin implementation

Diamond Proxy Contract Security Best Practices

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.

1. Break up the contract logic into separate facets to enable modular design and upgrades

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

2. The proxy contract must be initialized with a valid 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 DiamondCutFacet and diamondCut().

Source: Mugen’s Diamond-3-Hardhat

3. To add new state variables to a storage struct, add them to the end of the struct

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.

4. When using the AppStorage pattern, do not declare and use state variables outside the struct

The 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.

5. Do not put structs directly in another struct

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.

6. Do not add new state variables to structs that are used in arrays

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.

7. Do not use the same storage slot for different structs

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.

8. Do not leave the initialize() function unprotected

The 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 initialize / setter functions, or ensure that the function is called when the contract is deployed and cannot be called again.

9. Do NOT allow any facet to be able to call selfdestruct()

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.

Summary

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.

Read more: https://www.certik.com/resources/blog/7laIe0oZGK6IoYDwn0g2Jp-diamond-proxy-contracts-best-practices

Comments

All Comments

Recommended for you

  • Cointime May 4th News Express

    1. Hong Kong Bitcoin Spot ETF has held 4,218 BTC since its listing three days ago

  • Blockchain Asset Management announces launch of a dedicated blockchain fund for accredited investors

    Blockchain Asset Management, a cryptocurrency fund with a scale of $100 million, announced the launch of an exclusive blockchain fund for qualified investors. The specific amount of funds raised by the fund has not been disclosed yet, but it is said to have reached "eight figures", which means it is in the tens of millions of dollars. In addition, the investment threshold for the new fund is $100,000, and all investors are required to meet the approved standards (annual income exceeding $200,000, net assets exceeding $1 million).

  • Renault's BWT Alpine F1 Team announces partnership with ApeCoinDAO

    The BWT Alpine F1 team under Renault announced a partnership with ApeCoinDAO on X platform, which will introduce APE into the Alpine F1 ecosystem and collaborate with global token holders to launch peripheral products and digital assets inspired by the first ApeCoin. It is reported that according to the cooperation between the two parties, in the future, BAYC NFTs may be able to wear equipment and clothing with the Alpine team logo.

  • BTC breaks through $63,000

    The market shows BTC has broken through $63,000 and is currently trading at $63,014.9, with a daily increase of 6.11%. The market is volatile, so please exercise caution in risk management.

  • The total gas consumption on the Base chain exceeds 10,000 ETH

    According to the blockchain analysis platform Dune Analytics, the total gas consumption on the Base chain has exceeded 10,000 ETH, reaching 10,839.5062 ETH at the time of writing (equivalent to over $33.6 million at current prices). The average gas usage amount is about $0.1754 per transaction (0.000059661 ETH), and the total number of blocks has reached 13.41 million, with an average transaction volume of about 14.63 transactions per block. In addition, the data shows that the total transaction volume on the Base chain has exceeded 196.2 million, with over 8.366 million users and over 184 million user transactions at the time of writing. Furthermore, the total number of contracts created on the Base chain has exceeded 64 million, reaching 64,056,573 in the current period.

  • A wallet received 2,000 ETH from Alemeda/FTX

    As monitored by The Data Nerd, 6 hours ago, wallet 0xaEa received 2,000 ETH (approximately $6.23 million) from Alemeda/FTX. Within a week, it received a total of 8,000 ETH (approximately $24.71 million) from Alameda and deposited 6,000 ETH into Binance.

  • A single transaction with a transaction fee of up to 1.5 BTC appeared on the Bitcoin chain

    According to on-chain data tracking service monitoring , there has been a single transaction on the Bitcoin network with a transaction fee as high as 1.5 BTC, worth about $100,254. It is reported that the sender of the transaction is an address starting with "bc1p4n" and the recipient is an address starting with "bc1pqv".

  • 2 wallets deposited 211 billion SHIB into Coinbase within 10 hours

    According to The Data Nerd's monitoring, within 10 hours, 2 wallets (with the same amount of SHIB) deposited a total of 211 billion SHIB (about 5.16 million US dollars) into Coinbase. These wallets accumulated these SHIBs last week, and if sold at the current price, it would cause a small loss (about 120,000 US dollars).

  • USDT issuance on TON chain reaches $100 million

    According to official data, the issuance and circulation of USDT on the TON chain has reached 100 million US dollars, making TON the fastest-growing blockchain for Tether USDT issuance in Web3 history.

  • USDC circulation decreased by $200 million in the past week, with a total circulation of $33.1 billion

    According to official data, Circle issued a total of 2.8 billion USDC and redeemed approximately 3 billion USDC in the past 7 days, resulting in a decrease in circulation of approximately 200 million USDC. The total circulation of USDC is 33.1 billion US dollars, with a reserve of 33.2 billion US dollars, including approximately 3.4 billion US dollars in cash, and Circle Reserve Fund holding approximately 29.8 billion US dollars.