0Pricing
Blockchain Smart Contracts with Solidity · Lección

Patrón Transparent Proxy y layout de almacenamiento

Aprenda el patrón Transparent Proxy, cómo delegatecall separa la lógica del almacenamiento y las reglas de layout de almacenamiento que debe seguir para actualizar contratos de forma segura.

Patrón Transparent Proxy y layout de almacenamiento es una lección gratuita de Blockchain Smart Contracts with Solidity en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Blockchain Smart Contracts with Solidity, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Blockchain Smart Contracts with Solidity incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Recap: Why Proxies

You have seen UUPS and the Diamond standard. Both rely on a foundational idea: a proxy holds the storage and forwards calls to a separate logic (implementation) contract. Upgrading means pointing the proxy at new logic.

How delegatecall Works

The magic behind proxies is delegatecall. It runs the logic contract's code but in the proxy's storage context, using the proxy's msg.sender and balance.

So storage lives in the proxy; behavior lives in the implementation.

A Minimal Proxy Fallback

A proxy forwards every unknown call to the implementation using assembly delegatecall in its fallback.

fallback() external payable {
    address impl = _implementation();
    assembly {
        calldatacopy(0, 0, calldatasize())
        let ok := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
        returndatacopy(0, 0, returndatasize())
        switch ok
        case 0 { revert(0, returndatasize()) }
        default { return(0, returndatasize()) }
    }
}

The Function Clash Problem

If the proxy itself has an upgradeTo function and the logic also has a function with the same selector, calls become ambiguous. The Transparent Proxy pattern solves this by routing based on the caller.

Admin vs User Routing

In a Transparent Proxy, the admin address can call admin functions (like upgrade) but cannot reach the implementation. Everyone else is always forwarded to the implementation. This removes clashes.

modifier ifAdmin() {
    if (msg.sender == _admin()) {
        _;
    } else {
        _fallback();
    }
}

Storage Slot Collisions

Both proxy and logic write to the same storage. If they used slot 0 for different variables, they would corrupt each other. Proxies store admin and implementation at fixed pseudo-random slots (EIP-1967) to avoid collisions.

// EIP-1967 implementation slot
bytes32 internal constant _IMPL_SLOT =
    0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

Reading the Implementation Slot

The proxy reads and writes that fixed slot directly with assembly so it never collides with logic variables.

function _implementation() internal view returns (address impl) {
    bytes32 slot = _IMPL_SLOT;
    assembly { impl := sload(slot) }
}

Storage Layout Rules

When upgrading the logic you must preserve the order and types of existing storage variables. New variables go at the end.

  • Never reorder existing variables
  • Never change a variable's type
  • Never insert a new variable before old ones

Storage Gaps

Inheritable base contracts reserve space for future variables with a __gap array so child contracts do not collide after an upgrade adds fields to the base.

contract Base {
    uint256 public value;
    // reserve 50 slots for future use
    uint256[50] private __gap;
}

Initializers Not Constructors

Constructors run only on the logic contract's own deployment, not through the proxy. Upgradeable contracts use an initialize function guarded so it runs exactly once.

bool private _initialized;

function initialize(uint256 v) external {
    require(!_initialized, 'already init');
    _initialized = true;
    value = v;
}

Transparent vs UUPS

Transparent proxies put the upgrade logic in the proxy (more deployment gas, simpler logic). UUPS puts it in the implementation (cheaper proxy, but you must include upgrade code in every version). Choose based on cost and team discipline.

Quick Check

Test your understanding of proxy storage.

Recap

You learned the Transparent Proxy pattern:

  • delegatecall runs logic in the proxy's storage
  • Admin-vs-user routing avoids function clashes
  • EIP-1967 fixed slots and __gap arrays prevent collisions
  • Use initialize, preserve storage layout, append new variables

Follow these rules and upgrades stay safe.

Preguntas frecuentes

¿La lección «Patrón Transparent Proxy y layout de almacenamiento» es gratis?

Sí — el texto completo de «Patrón Transparent Proxy y layout de almacenamiento» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Blockchain Smart Contracts with Solidity, actualiza a CoddyKit PRO. El curso de Blockchain Smart Contracts with Solidity incluye 4 lecciones en total.

¿Qué aprenderé en «Patrón Transparent Proxy y layout de almacenamiento»?

Aprenda el patrón Transparent Proxy, cómo delegatecall separa la lógica del almacenamiento y las reglas de layout de almacenamiento que debe seguir para actualizar contratos de forma segura. Practicas Blockchain Smart Contracts with Solidity con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Blockchain Smart Contracts with Solidity?

No se requiere experiencia previa. Blockchain Smart Contracts with Solidity en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Patrón Transparent Proxy y layout de almacenamiento»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Blockchain Smart Contracts with Solidity?

Sí. Cada lección de Blockchain Smart Contracts with Solidity incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. ¿Por qué utilizar contratos actualizables?
  2. Implementación del patrón de proxy UUPS
  3. Estándar Diamond (proxies multifaceta)
  4. Patrón Transparent Proxy y layout de almacenamiento
← Volver a Blockchain Smart Contracts with Solidity