Стандарт Diamond (прокси с несколькими фасетами)
Изучите стандарт Diamond (EIP-2535) для создания высокомодульных и масштабируемых обновляемых контрактов с несколькими фасетами.
«Стандарт Diamond (прокси с несколькими фасетами)» — бесплатный урок Blockchain Smart Contracts with Solidity на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Blockchain Smart Contracts with Solidity, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Blockchain Smart Contracts with Solidity содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Intro to Diamond Standard
Welcome to the final lesson on upgradeable contracts! We've explored UUPS, but what if your contract grows too big or needs extreme modularity?
The Diamond Standard (EIP-2535) is a powerful pattern that allows a single proxy contract to delegate calls to multiple implementation contracts, called facets.
Single Proxy Limitations
Traditional proxy patterns, like UUPS or Transparent proxies, typically delegate all calls to a single implementation contract.
While effective, this can lead to:
- Contract Size Limit: Ethereum contracts have a 24KB limit. A single, monolithic implementation can hit this quickly.
- Complexity: A single contract managing many features becomes hard to maintain and audit.
- Upgrade Costs: Upgrading means redeploying the entire large implementation contract, even if only a small part changed.
Facets: Modular Contracts
The Diamond Standard solves this by breaking down your contract's logic into smaller, independent pieces called facets.
Think of facets as:
- Individual smart contracts, each handling specific functionalities.
- Like 'plugins' or 'modules' for your main proxy.
- Each facet has its own set of functions.
The Diamond proxy then decides which facet to forward a call to.
How Diamond Proxies Work
At its core, a Diamond proxy works similarly to other proxies:
- A user calls a function on the Diamond proxy.
- The proxy looks at the function selector (the first 4 bytes of the call data).
- It then determines which facet contains that function.
- Finally, it delegates the call (using
delegatecall) to the correct facet.
The magic is that the proxy maintains a mapping of function selectors to facet addresses.
Diamond Storage: Shared State
A crucial aspect of the Diamond Standard is how state is managed. Even though logic is split across facets, they all operate on the same storage within the Diamond proxy contract.
This is achieved by:
- Defining a shared storage struct (e.g.,
AppStorage). - Each facet accesses this shared storage using a specific Solidity pattern (often via a library).
- This ensures consistency and allows facets to interact with the same data.
Managing Facets with `diamondCut`
The central function for managing your Diamond is diamondCut. This function allows you to:
- Add new facets (new functionality).
- Replace existing facets (upgrade or fix bugs).
- Remove facets (deprecate functionality).
diamondCut is typically only callable by the contract's owner, making it the secure upgrade mechanism for your multi-faceted contract.
A Simple Facet Example
Here's what a very basic Solidity facet might look like. Remember, facets are just regular contracts that implement specific logic.
Try compiling this simple example:
pragma solidity ^0.8.0;
contract MySimpleFacet {
// Facets interact with shared storage
// located in the Diamond proxy contract.
// They don't declare state variables directly
// in the way a standalone contract would.
function getFacetVersion() external pure returns (string memory) {
return "MySimpleFacet v1.0";
}
function greetUser(string memory _name) external pure returns (string memory) {
return string(abi.encodePacked("Hello, ", _name, " from MySimpleFacet!"));
}
}The Diamond Proxy Itself
The Diamond proxy contract itself is remarkably lean. Its primary responsibilities are:
- Storing the mapping of function selectors to facet addresses.
- Implementing the
diamondCutfunction for upgrades. - The fallback function, which handles delegating calls to the correct facet.
It acts as the central router for all incoming calls, directing them to the appropriate piece of logic.
Why Choose Diamond Standard?
The Diamond Standard offers significant advantages for complex DApps:
- Unlimited Contract Size: Easily bypass the 24KB limit by splitting logic into many small facets.
- Extreme Modularity: Develop and deploy features independently.
- Gas Efficiency: Only upgrade (deploy) the specific facets that change, not the entire contract.
- Clear Separation of Concerns: Improves code readability, testing, and security auditing.
- Incremental Development: Add new features over time without affecting existing ones.
Diamond Standard Check
The Diamond Standard (EIP-2535) provides a robust framework for building highly modular and upgradeable smart contracts. Which of the following statements accurately describe its key benefits or characteristics?
Recap: Multi-facet Proxies
In this lesson, we explored the Diamond Standard (EIP-2535), a powerful pattern for building highly modular and upgradeable smart contracts.
- We learned about facets, which are individual contracts containing specific logic.
- The Diamond proxy delegates calls to these multiple facets based on function selectors.
- All facets share the Diamond proxy's storage.
- The
diamondCutfunction is used to add, replace, or remove facets. - Key benefits include overcoming the 24KB contract size limit, extreme modularity, and efficient upgrades.
You're now equipped with knowledge of advanced upgradeability patterns!
Изучай Blockchain Smart Contracts with Solidity с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 12
- Уроки
- 48
Часто задаваемые вопросы
Урок «Стандарт Diamond (прокси с несколькими фасетами)» бесплатный?
Да — полный текст урока «Стандарт Diamond (прокси с несколькими фасетами)» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Blockchain Smart Contracts with Solidity, подпишись на CoddyKit PRO. Курс Blockchain Smart Contracts with Solidity содержит 4 уроков всего.
Чему я научусь в уроке «Стандарт Diamond (прокси с несколькими фасетами)»?
Изучите стандарт Diamond (EIP-2535) для создания высокомодульных и масштабируемых обновляемых контрактов с несколькими фасетами. Ты практикуешь Blockchain Smart Contracts with Solidity с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Blockchain Smart Contracts with Solidity?
Предыдущий опыт не требуется. Blockchain Smart Contracts with Solidity на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Стандарт Diamond (прокси с несколькими фасетами)»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Blockchain Smart Contracts with Solidity?
Да. Каждый урок Blockchain Smart Contracts with Solidity включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Зачем нужны обновляемые контракты
- Реализация прокси-шаблона UUPS
- Стандарт Diamond (прокси с несколькими фасетами)
- Шаблон прозрачного прокси и размещение данных в хранилище