0Pricing
Blockchain Smart Contracts with Solidity · Aula

Padrão Diamond (proxies multifacetados)

Explore o padrão Diamond (EIP-2535) para criar contratos atualizáveis altamente modulares e escaláveis com múltiplas facetas.

Padrão Diamond (proxies multifacetados) é uma aula grátis de Blockchain Smart Contracts with Solidity no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Blockchain Smart Contracts with Solidity, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Blockchain Smart Contracts with Solidity inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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:

  1. A user calls a function on the Diamond proxy.
  2. The proxy looks at the function selector (the first 4 bytes of the call data).
  3. It then determines which facet contains that function.
  4. 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 diamondCut function 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 diamondCut function 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!

Perguntas Frequentes

A aula “Padrão Diamond (proxies multifacetados)” é grátis?

Sim — o texto completo de “Padrão Diamond (proxies multifacetados)” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Blockchain Smart Contracts with Solidity, atualize para CoddyKit PRO. O curso de Blockchain Smart Contracts with Solidity inclui 4 aulas no total.

O que vou aprender em “Padrão Diamond (proxies multifacetados)”?

Explore o padrão Diamond (EIP-2535) para criar contratos atualizáveis altamente modulares e escaláveis com múltiplas facetas. Você pratica Blockchain Smart Contracts with Solidity com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Blockchain Smart Contracts with Solidity?

Nenhuma experiência prévia é necessária. Blockchain Smart Contracts with Solidity no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “Padrão Diamond (proxies multifacetados)”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Blockchain Smart Contracts with Solidity?

Sim. Cada aula de Blockchain Smart Contracts with Solidity inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Por que usar contratos atualizáveis?
  2. Implementação do padrão de proxy UUPS
  3. Padrão Diamond (proxies multifacetados)
  4. Padrão de Proxy Transparente e Layout de Armazenamento
← Voltar para Blockchain Smart Contracts with Solidity