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