Guide: Creating a New Diamond Facet
In this project we use the EIP-2535 “Diamond” pattern to compose modular contracts. A Diamond is a proxy that delegates calls to multiple Facets, each holding related logic.
Overview#
In this project we use the EIP-2535 “Diamond” pattern to compose modular contracts. A Diamond is a proxy that delegates calls to multiple Facets, each holding related logic. For example, “A Facets can be compared to an implementation contract… [it] holds the external function logic the proxy (Diamond) will call”. Facets allow us to split functionality into separate contracts that can be upgraded independently. Each facet has its own isolated state (using the Diamond Storage pattern) to avoid storage conflicts. This guide explains our conventions for adding a new facet, including folder structure, contract layout, and testing.
Folder Structure#
Facets live under src/garden/facets/, grouped by what they are:
src/garden/facets/
├── baseFacets/<name>/ # the kernel: ownership, cut, upgrade, loupe
├── indexFacets/ # index connection and rebalancing
└── utilityFacets/<chain>/<protocol>/ # DeFi integrations, one folder per chainA new DeFi integration therefore goes in utilityFacets/<chain>/<protocol>/, for example utilityFacets/arbitrumOne/uniswapV3/. Put it under the chain it targets; the same protocol on two chains gets a folder under each.
Each facet folder holds the files it actually needs, not a fixed set:
<Name>Facet.sol– the external facet contract. Always present.<Name>Base.sol– abstract contract with the internal logic. Always present.<Name>Storage.sol– the storage library. Only if the facet keeps state. A stateless facet (most swap integrations) has none.I<Name>.sol– the external interface. Utility facets define their own; base facets usually implement a standard that already lives insrc/interfaces/(for exampleIERC173for ownership).
Tests mirror the src path under test/, with a subfolder per test kind:
test/garden/facets/baseFacets/ownership/unit/OwnershipFacet.t.solunit/ is the one every facet has. fuzz/ and invariant/ exist where that facet warrants them. One test contract per facet, named <Facet>Test, in <Facet>.t.sol, which keeps forge test --match-contract OwnershipFacetTest useful.
Facet Contract Layout#
Within each facet folder, we follow a strict contract layout:
<FacetName>Storage.sol: Implements the Diamond Storage pattern. Derive the slot throughLibStorageSlot.deriveStorageSlot(type(YourStorage).name), never by hardcoding a string or inlining the hash formula. Declare aSTORAGE_LAYOUT_VERSION, and make_storageLayoutVersionthe first field of the struct: upgrades validate it, so a layout with it anywhere else is wrong. For example:
library TransferStorage {
uint256 internal constant STORAGE_LAYOUT_VERSION = 1;
struct Layout {
/// @notice Storage layout version — MUST be first field. Validated during upgrades.
uint256 _storageLayoutVersion;
// Add required variables after it, append-only
uint256 lastTransferBlock;
}
/// @dev Storage slot is derived from keccak256(bytes(type(TransferStorage).name))
function layout() internal pure returns (Layout storage l) {
bytes32 position = LibStorageSlot.deriveStorageSlot(type(TransferStorage).name);
assembly {
l.slot := position
}
}
}This isolates the facet's state so that each facet can be understood as its own unit. Two consequences worth knowing before you pick a name: the library name is the storage key, so it can never be renamed once deployed, and new struct fields may only be appended. See Security Considerations for what enforces this.
<FacetName>Base.sol: An abstract contract defining internal functions and logic. This contract imports the storage library and any required interfaces, and implements internal (or internal view) functions. It may also read/write storage via Layoutstorage s = <FacetName>Storage.layout(). For example, a Transfer facet’s base might have:
abstract contract TransferBase is ITransferBase {
using SafeERC20 for IERC20;
function _transferEth(address payable to, uint256 amount) internal {
if (amount > address(this).balance) revert Transfer_Failed();
(bool success,) = to.call{ value: amount }("");
if (!success) revert Transfer_Failed();
TransferStorage.layout().lastTransferBlock = block.timestamp;
emit ETHTransferExecuted(msg.sender, to, amount);
}
function _erc20Transfer(address token, address to, uint256 amount) internal {
IERC20(token).safeTransfer(to, amount);
TransferStorage.layout().lastTransferBlock = block.timestamp;
emit ERC20TransferExecuted(token, msg.sender, to, amount);
}
function _erc20TransferFrom(address token, address from, address to, uint256 amount) internal {
IERC20(token).safeTransferFrom(from, to, amount);
TransferStorage.layout().lastTransferBlock = block.timestamp;
emit ERC20TransferExecuted(token, from, to, amount);
}
}The <FacetName>Base contract also implements any internal helpers and emits events defined in its interface.
<FacetName>Facet.sol: The public-facing facet contract. It inherits from the Base abstract, the external interface, and a generic Facet marker (provided by our framework). This contract defines the external functions that users or the Diamond owner can call. It should include an initializer (if needed) and apply access control (e.g. onlyDiamondOwner) on mutating calls. In code:
contract TransferFacet is ITransfer, TransferBase {
function transferEth(address payable to, uint256 amount) external override {
_transferEth(to, amount);
}
function erc20Transfer(address token, address to, uint256 amount) external override {
_erc20Transfer(token, to, amount);
}
function erc20TransferFrom(address token, address from, address to, uint256 amount) external override {
_erc20TransferFrom(token, from, to, amount);
}
}Here, ITransfer defines the external API, and onlyDiamondOwner (from Facet) protects state-changing calls. The initialize method (if any) is called when the facet is first added. As recommended: “compose initializer and protect external calls in <FacetName>Facet”.
I<FacetName>.sol: A Solidity interface defining only the external (public/external) functions of the facet. This is what clients of the diamond will use to interact with the facet. It should match the external methods in<FacetName>Facet.sol.
interface ITransfer {
function transferEth(address payable to, uint256 amount) external;
function erc20Transfer(address token, address to, uint256 amount) external;
function erc20TransferFrom(address token, address from, address to, uint256 amount) external;
}I<FacetName>Base.sol: A Solidity interface (or abstract interface) that contains all the internal types: custom errors, event declarations, enums, and struct definitions used by the facet. The<FacetName>Basecontract and<FacetName>Facetcan both use these definitions. This separation (external vs base interface) keeps the external interface clean while centralizing internal definitions for reuse. Custom errors should follow the naming conventionFacetName_Error, such asDiamondCut_InvalidFacet()orLending_Unauthorized()for clarity and consistency.
interface ITransferBase {
error Transfer_Failed();
event ETHTransferExecuted(address indexed from, address indexed to, uint256 amount);
event ERC20TransferExecuted(address indexed token, address indexed from, address indexed to, uint256 amount);
}Testing Facets#
Facet tests deploy a real Garden through the test harness and then call the facet through the Garden address, which is the only way the facet is ever reached in production. The harness lives in test/base/:
BaseTest.sol– shared setup and common test actors.DiamondTestBase.sol– what most facet tests extend. Gives you helpers to register a garden type and deploy a Garden.DexFacetTestBase.sol– for swap integrations, which need pool and router fixtures on top of the above.
The shape of a facet test#
Extend the right base, deploy a Garden in setUp(), then exercise the facet through an interface cast on the Garden address:
contract OwnershipFacetTest is DiamondTestBase {
address public garden;
function setUp() public override {
super.setUp();
_addGardenTypeEmpty(GARDEN_TYPE_1);
garden = _deployGarden(GARDEN_TYPE_1, gardenOwner);
}
function test_owner_returnsGardenOwner() public view {
assertEq(IERC173(garden).owner(), gardenOwner);
}
function test_transferOwnership_updatesOwner() public {
vm.prank(gardenOwner);
IERC173(garden).transferOwnership(alice);
assertEq(IERC173(garden).owner(), alice);
}
}Note the cast: IERC173(garden), not the facet contract directly. Calling the facet's own address would run its code against the facet's own storage rather than the Garden's, which is not how it behaves in production and will give you misleading results.
Naming and placement#
One test contract per facet, named <Facet>Test, in <Facet>.t.sol, under the mirrored src path plus unit/. Group tests inside the contract by the function under test rather than splitting them across files. Add fuzz/ or invariant/ siblings only when the facet has properties worth testing that way.
Before you open a PR#
forge test also runs three storage guards inherited by every suite. They catch two libraries sharing a name, and they fail if a storage library recorded in storage-registry.json has disappeared from the codebase. If one of those fails after you add a facet, the storage library name you chose collides with an existing one, so pick another rather than working around the guard.
Last updated:
Edit this page (opens in a new tab)