EIP-2535: A standard for organizing and upgrading a modular smart contract system.
Multi-Facet Proxies for full control over your upgrades
The EIP-2535 standard has several projects already using it, most notably Aavegotchi holding many millions of dollars.
What is it and should you use it instead of the commonly used proxy upgrade pattern?

What is a diamond?

delegatecall
to forward it to a second logic contract. As a reminder, delegatecall will execute a function defined in the called contract (logic), but within the context of the calling contract (proxy). In other words, we can have our logic defined separately from our data.
This allows us to change the logic contract without changing the underlying data. All you need to do is change the address of the logic contract defined in our proxy, usually done via governance or at a minimum controlled via a multi-sig wallet.
With this proxy pattern we effectively have upgradability for smart contracts, but it comes with some limitations.
- What if you want to upgrade only a small part of a complex contract? You will still need to upgrade to a completely new logic contract. This makes it more difficult to see what actually changed.
- Reusability of logic contracts by multiple proxies is possible, but it's not very practicable. You can only create identical proxy instances using one logic contract. There is no way to combine logic contracts or use only parts of one.
- You cannot have a modular permission system which for example would allow some entities to only upgrade a subset of existing functions. Instead it's an all or nothing approach.
- One must take special care when accessing data within the logic contract after upgrades, because the data in the proxy contract never changes with upgrades. That means if you were to stop using a state variable in the logic contract, you would still need to keep it in the variable definitions. And when you add state variables, you may only append them to the end of the definitions.
- Logic contracts can easily reach the 24kb max contract size limit.
So this is where diamonds come in. The core idea is identical to the proxy pattern, but with the difference that you can have multiple logic contracts.

- When you have multiple logic contracts, how can the diamond storage know which one to delegate the call to?
- How can multiple logic contracts share the same state without overwriting the data?
- Can the logic contracts share data between each other?
DiamondCut: The managing interface
The diamond storage must implement the diamondCut
function. With this function one can (un-)register functions for a specific logic contract. Once a function is registered, the diamond storage can recognize the function selector of any call within its fallback function, retrieve the correct facet address and then run delegatecall for it.
If you remember the PolyNetwork hack, you will know that a function selector collision is possible, meaning two different functions result in the same 4 bytes function signature. This is easily prevented by a simple check which prevents adding function selectors that already exist. The diamond reference implementations perform this check when upgrading.
Great, now we know how the delegatecall works. But how can we ensure the data integrity?
interface IDiamondCut {
enum FacetCutAction {Add, Replace, Remove}
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
}
contract FacetA {
struct FacetData {
address owner;
bytes32 dataA;
}
function facetData()
internal
pure
returns(FacetData storage facetData) {
bytes32 storagePosition = keccak256("diamond.storage.FacetA");
assembly {facetData.slot := storagePosition}
}
function setDataA(bytes32 _dataA) external {
FacetData storage facetData = facetData();
require(facetData.owner == msg.sender, "Must be owner.");
facetData.dataA = _dataA;
}
function getDataA() external view returns (bytes32) {
return facetData().dataA;
}
}
DiamondStorage: The data keeper
To avoid any storage slot collisions, we can use a simple trick for where to store the data. While usually Solidity will store data in subsequent slots as defined by the state variables, we can also explicitly set the storage slot with assembly.
When doing so we only need to ensure the storage slot is at a unique position which won't create conflicts with other facets. One can easily achieve this by hashing the facet name.
Now whenever we want to read or write FacetData
, we don't have to worry about overwriting other facets data, because our storage slot position is unique. And you can of course access this data from any other facet as well, you just need to inherit from FacetA
and use the facetData
function. That's why it's particularly helpful for creating reusable facets.
However an alternative design would be the AppStorage pattern which we won't go into detail here, but it sacrifices reusability for slightly improved code readability. AppStorage is useful when sharing state variables between facets that are specific to a project and won't be reused in diamonds for other projects or protocols.
DiamondLoupe: Finding out which functions are supported

interface IDiamondLoupe {
struct Facet {
address facetAddress;
bytes4[] functionSelectors;
}
function facets() external view returns (Facet[] memory facets_);
function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_);
function facetAddresses() external view returns (address[] memory facetAddresses_);
function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);
}
While these functions would be optional to have if one was to rely solely on events with something like The Graph, it was still decided to have the loupe within the standard, because they significantly improve the usability with deployed contracts.
So how would you actually implement all this?
How to implement a diamond
There is currently no reference implementation available via the Openzeppelin contracts, but it might happen soon. The EIP author Nick Mudge created three reference implementations which are all audited:
- diamond-1-hardhat (Simple implementation)
- diamond-2-hardhat (Gas-optimized)
- diamond-3-hardhat (Simple loupe functions)
Which one should you choose? They all do the same thing, so it doesn't matter too much. If you plan to do many upgrades and care about gas costs, consider going with diamond-2. It contains some complicated bitwise operations to reduce the storage space and will save you roughly 80,000 gas for every 20 functions added. Otherwise diamond-1 is probably a better choice since the code is much more readable.
This is the core logic of the diamond-1 for adding and removing functions with some checks removed for better readability:
struct FacetAddressAndSelectorPosition {
address facetAddress;
uint16 selectorPosition;
}
struct DiamondStorage {
// function selector => facet address and selector position in selectors array
mapping(bytes4 => FacetAddressAndSelectorPosition) facetAddressAndSelectorPosition;
bytes4[] selectors;
}
Basically one maintains an array of all available function signatures with a respective mapping which holds the facet address. The position in the mapping is required when removing a function again.
Adding functions
To add a new function is then as simple as
- adding it to the array
- updating the mapping
- incrementing the total function count
You can find the full source code example here.
function addFunctions(
address _facetAddr,
bytes4[] memory _functionSelectors
) internal {
DiamondStorage storage ds = diamondStorage();
uint16 selectorCount = uint16(ds.selectors.length);
for (uint256 idx; idx < _functionSelectors.length; idx++) {
bytes4 selector = _functionSelectors[idx];
ds.facetAddressAndSelectorPosition[selector] =
FacetAddressAndSelectorPosition(_facetAddr, selectorCount);
ds.selectors.push(selector);
selectorCount++;
}
}
function removeFunctions(
address _facetAddr,
bytes4[] memory _functionSelectors
) internal {
DiamondStorage storage ds = diamondStorage();
uint256 selectorCount = ds.selectors.length;
for (uint256 idx; idx < _functionSelectors.length; idx++) {
bytes4 selector = _functionSelectors[idx];
FacetAddressAndSelectorPosition memory old =
ds.facetAddressAndSelectorPosition[selector];
selectorCount--;
if (old.selectorPosition != selectorCount) {
// replace selector with last selector
bytes4 lastSelector = ds.selectors[selectorCount];
ds.selectors[old.selectorPosition] = lastSelector;
ds.facetAddressAndSelectorPosition[lastSelector]
.selectorPosition = old.selectorPosition;
}
// delete last selector
ds.selectors.pop();
delete ds.facetAddressAndSelectorPosition[selector];
}
}
Removing functions
Now for removing a function, you can find out the position in the array by checking its position from the mapping (selectorPosition
).
When removing elements from the middle of an array in Solidity, one creates empty slots in the array. That's why we also have to copy over the currently last selector to the empty slot and call pop.
You can find the full source code example here.
How to implement the Diamond Storage?
The storage itself consists mainly of the fallback function which
- takes the function selector from msg.sig
- reads the responsible facet address from our mapping which is stored at the predefined slot
DIAMOND_STORAGE_POSITION
to not collide with any other data - forwards the call to the facet using delegatecall
You can find the full source code example here.
fallback() external payable {
LibDiamond.DiamondStorage storage ds;
bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
address facet =
ds.facetAddressAndSelectorPosition[msg.sig].facetAddress;
require(facet != address(0));
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(
gas(),
facet,
0,
calldatasize(),
0,
0,
)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
This is also how you would use this yourself, make the diamond storage your main contract and add to it any facets you require. A small repository which gives you an example on how people are using that is here.
Should you use Diamonds?
Now with all that said, which one is better, proxy upgrade patterns or diamonds? Let's look at the pros and cons.
Pros:
- Facet reusability
- Modular upgradability
- Modular permission system
- Storage slot management
- Avoiding max contract size issues
Cons:
- More Complexity
- Harder to maintain
- Not many big real life projects yet
- Not supported by tools like Etherscan, but an alternative for at least Etherscan exists: Louper

The bottom line is diamonds are still bleeding edge and not a finalized or widely used standard. If the proxy upgrade pattern is good enough for you, go with that one. It will be easier to implement, maintain and Etherscan comes with full proxy support.
But if you want to take advantage of the additional features from diamonds, this is a perfectly reasonable alternative by now. A diamond is useful for organizing contract functionality into different sets of functionality that are accessible at the same address and share the same state variables. Say someone wants to implement ERC721 and ERC1155 in the same contract. It could be implemented as a diamond with one ERC721Facet and one ERC1155Facet. Plus any custom functionality could be added with more facets.
Diamonds might see more usage in the future once contract systems require more sophistication and tools are supporting it.
Solidity Developer
More great blog posts from Markus Waas
How to use ChatGPT with Solidity
Using the Solidity Scholar and other GPT tips
How to integrate Uniswap 4 and create custom hooks
Let's dive into Uniswap v4's new features and integration
How to integrate Wormhole in your smart contracts
Entering a New Era of Blockchain Interoperability
Solidity Deep Dive: New Opcode 'Prevrandao'
All you need to know about the latest opcode addition
How Ethereum scales with Arbitrum Nitro and how to use it
A blockchain on a blockchain deep dive
The Ultimate Merkle Tree Guide in Solidity
Everything you need to know about Merkle trees and their future
The New Decentralized The Graph Network
What are the new features and how to use it
zkSync Guide - The future of Ethereum scaling
How the zero-knowledge tech works and how to use it
Exploring the Openzeppelin CrossChain Functionality
What is the new CrossChain support and how can you use it.
Deploying Solidity Contracts in Hedera
What is Hedera and how can you use it.
Writing ERC-20 Tests in Solidity with Foundry
Blazing fast tests, no more BigNumber.js, only Solidity
ERC-4626: Extending ERC-20 for Interest Management
How the newly finalized standard works and can help you with Defi
Advancing the NFT standard: ERC721-Permit
And how to avoid the two step approve + transferFrom with ERC721-Permit (EIP-4494)
Moonbeam: The EVM of Polkadot
Deploying and onboarding users to Moonbeam or Moonriver
Advanced MultiSwap: How to better arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
Deploying Solidity Smart Contracts to Solana
What is Solana and how can you deploy Solidity smart contracts to it?
Smock 2: The powerful mocking tool for Hardhat
Features of smock v2 and how to use them with examples
How to deploy on Evmos: The first EVM chain on Cosmos
Deploying and onboarding users to Evmos
MultiSwap: How to arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
The latest tech for scaling your contracts: Optimism
How the blockchain on a blockchain works and how to use it
Ultimate Performance: The Aurora Layer2 Network
Deploying and onboarding users to the Aurora Network powered by NEAR Protocol
What is ecrecover in Solidity?
A dive into the waters of signatures for smart contracts
How to use Binance Smart Chain in your Dapp
Deploying and onboarding users to the Binance Smart Chain (BSC)
Using the new Uniswap v3 in your contracts
What's new in Uniswap v3 and how to integrate Uniswap v3
What's coming in the London Hardfork?
Looking at all the details of the upcoming fork
Welcome to the Matrix of blockchain
How to get alerted *before* getting hacked and prevent it
The Ultimate Ethereum Mainnet Deployment Guide
All you need to know to deploy to the Ethereum mainnet
SushiSwap Explained!
Looking at the implementation details of SushiSwap
Solidity Fast Track 2: Continue Learning Solidity Fast
Continuing to learn Solidity fast with the advanced basics
What's coming in the Berlin Hardfork?
Looking at all the details of the upcoming fork
Using 1inch ChiGas tokens to reduce transaction costs
What are gas tokens and example usage for Uniswap v2
Openzeppelin Contracts v4 in Review
Taking a look at the new Openzeppelin v4 Release
EIP-3156: Creating a standard for Flash Loans
A new standard for flash loans unifying the interface + wrappers for existing ecosystems
Tornado.cash: A story of anonymity and zk-SNARKs
What is Tornado.cash, how to use it and the future
High Stakes Roulette on Ethereum
Learn by Example: Building a secure High Stakes Roulette
How to implement generalized meta transactions
We'll explore a powerful design for meta transactions based on 0x
Utilizing Bitmaps to dramatically save on Gas
A simple pattern which can save you a lot of money
Using the new Uniswap v2 as oracle in your contracts
How does the Uniswap v2 oracle function and how to integrate with it
Smock: The powerful mocking tool for Hardhat
Features of smock and how to use them with examples
How to build and use ERC-721 tokens in 2021
An intro for devs to the uniquely identifying token standard and its future
Trustless token management with Set Protocol
How to integrate token sets in your contracts
Exploring the new Solidity 0.8 Release
And how to upgrade your contracts to Solidity 0.8
How to build and use ERC-1155 tokens
An intro to the new standard for having many tokens in one
Leveraging the power of Bitcoins with RSK
Learn how RSK works and how to deploy your smart contracts to it
Solidity Fast Track: Learn Solidity Fast
'Learn X in Y minutes' this time with X = Solidity 0.7 and Y = 20
Sourcify: The future of a Decentralized Etherscan
Learn how to use the new Sourcify infrastructure today
Integrating the 0x API into your contracts
How to automatically get the best prices via 0x
How to build and use ERC-777 tokens
An intro to the new upgraded standard for ERC-20 tokens
COMP Governance Explained
How Compound's Decentralized Governance is working under the hood
How to prevent stuck tokens in contracts
And other use cases for the popular EIP-165
Understanding the World of Automated Smart Contract Analyzers
What are the best tools today and how can you use them?
A Long Way To Go: On Gasless Tokens and ERC20-Permit
And how to avoid the two step approve + transferFrom with ERC20-Permit (EIP-2612)!
Smart Contract Testing with Waffle 3
What are the features of Waffle and how to use them.
How to use xDai in your Dapp
Deploying and onboarding users to xDai to avoid the high gas costs
Stack Too Deep
Three words of horror
Integrating the new Chainlink contracts
How to use the new price feeder oracles
TheGraph: Fixing the Web3 data querying
Why we need TheGraph and how to use it
Adding Typescript to Truffle and Buidler
How to use TypeChain to utilize the powers of Typescript in your project
Integrating Balancer in your contracts
What is Balancer and how to use it
Navigating the pitfalls of securely interacting with ERC20 tokens
Figuring out how to securely interact might be harder than you think
Why you should automatically generate interests from user funds
How to integrate Aave and similar systems in your contracts
How to use Polygon (Matic) in your Dapp
Deploying and onboarding users to Polygon to avoid the high gas costs
Migrating from Truffle to Buidler
And why you should probably keep both.
Contract factories and clones
How to deploy contracts within contracts as easily and gas-efficient as possible
How to use IPFS in your Dapp?
Using the interplanetary file system in your frontend and contracts
Downsizing contracts to fight the contract size limit
What can you do to prevent your contracts from getting too large?
Using EXTCODEHASH to secure your systems
How to safely integrate anyone's smart contract
Using the new Uniswap v2 in your contracts
What's new in Uniswap v2 and how to integrate Uniswap v2
Solidity and Truffle Continuous Integration Setup
How to setup Travis or Circle CI for Truffle testing along with useful plugins.
Upcoming Devcon 2021 and other events
The Ethereum Foundation just announced the next Devcon in 2021 in Colombia
The Year of the 20: Creating an ERC20 in 2020
How to use the latest and best tools to create an ERC-20 token contract
How to get a Solidity developer job?
There are many ways to get a Solidity job and it might be easier than you think!
Design Pattern Solidity: Mock contracts for testing
Why you should make fun of your contracts
Kickstart your Dapp frontend development with create-eth-app
An overview on how to use the app and its features
The big picture of Solidity and Blockchain development in 2020
Overview of the most important technologies, services and tools that you need to know
Design Pattern Solidity: Free up unused storage
Why you should clean up after yourself
How to setup Solidity Developer Environment on Windows
What you need to know about developing on Windows
Avoiding out of gas for Truffle tests
How you do not have to worry about gas in tests anymore
Design Pattern Solidity: Stages
How you can design stages in your contract
Web3 1.2.5: Revert reason strings
How to use the new feature
Gaining back control of the internet
How Ocelot is decentralizing cloud computing
Devcon 5 - Review
Impressions from the conference
Devcon 5 - Information, Events, Links, Telegram
What you need to know
Design Pattern Solidity: Off-chain beats on-chain
Why you should do as much as possible off-chain
Design Pattern Solidity: Initialize Contract after Deployment
How to use the Initializable pattern
Consensys Blockchain Jobs Report
What the current blockchain job market looks like
Provable — Randomness Oracle
How the Oraclize random number generator works
Solidity Design Patterns: Multiply before Dividing
Why the correct order matters!
Devcon 5 Applications closing in one week
Devcon 5 Applications closing
Randomness and the Blockchain
How to achieve secure randomness for Solidity smart contracts?