0Pricing
Blockchain Smart Contracts with Solidity · Lección

Modificadores y el patrón checks-effects-interactions

Utilice modificadores de funciones para imponer precondiciones de forma clara y aplique el patrón checks-effects-interactions para escribir contratos más seguros.

Modificadores y el patrón checks-effects-interactions 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.

What Are Modifiers?

A modifier is reusable code that runs before (or around) a function body. It is ideal for enforcing preconditions like access control without repeating the same checks everywhere.

Declaring a Modifier

The special _; placeholder marks where the function body executes. Code before it runs first; code after runs when the function returns.

modifier onlyOwner() {
    require(msg.sender == owner, "Not owner");
    _;
}

Applying a Modifier

Attach a modifier to a function declaration. The check runs automatically on every call, keeping the function body focused on logic.

function withdraw() public onlyOwner {
    payable(owner).transfer(address(this).balance);
}

Modifiers with Parameters

Modifiers can take arguments, making them flexible for validating dynamic conditions such as minimum values.

modifier costs(uint price) {
    require(msg.value >= price, "Not enough");
    _;
}

Stacking Multiple Modifiers

You can apply several modifiers to one function; they run left to right. Keep them small and single-purpose so combinations stay predictable.

function buy() public payable onlyWhenOpen costs(1 ether) {
    // ...
}

The Reentrancy Danger

When a contract calls out to an external address, that address can call back into your contract before the first call finishes. This reentrancy can drain funds if state is updated too late.

Checks-Effects-Interactions

The checks-effects-interactions pattern orders your function in three phases: validate inputs (checks), update state (effects), then call external contracts (interactions). External calls come last.

A Vulnerable Withdraw

This sends ETH before zeroing the balance, leaving a reentrancy window.

// VULNERABLE
function withdraw() public {
    uint amt = balances[msg.sender];
    payable(msg.sender).call{value: amt}("");
    balances[msg.sender] = 0; // too late!
}

The Safe Version

Update state before the external call so a reentrant call sees a zero balance.

// SAFE
function withdraw() public {
    uint amt = balances[msg.sender];
    balances[msg.sender] = 0;   // effects first
    payable(msg.sender).call{value: amt}(""); // interaction last
}

Reentrancy Guards

For extra safety, add a reentrancy guard modifier that sets a lock flag during execution, rejecting nested calls. Libraries like OpenZeppelin provide nonReentrant.

Combining the Patterns

Use modifiers for the checks phase (access and validation), structure the body as effects-then-interactions, and add a guard on functions that move value. Together they form a strong defensive baseline.

Quick Check

Check your knowledge of safe contract patterns.

Recap

You learned defensive Solidity patterns:

  • Modifiers centralize preconditions like access control
  • They can take parameters and be stacked
  • Checks-effects-interactions orders functions to prevent reentrancy
  • Add a reentrancy guard on value-moving functions

These patterns are foundational to writing secure contracts.

Preguntas frecuentes

¿La lección «Modificadores y el patrón checks-effects-interactions» es gratis?

Sí — el texto completo de «Modificadores y el patrón checks-effects-interactions» 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 «Modificadores y el patrón checks-effects-interactions»?

Utilice modificadores de funciones para imponer precondiciones de forma clara y aplique el patrón checks-effects-interactions para escribir contratos más seguros. 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 «Modificadores y el patrón checks-effects-interactions»?

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. Herencia e interfaces
  2. Librerías y contratos abstractos
  3. Gestión de errores con Revert/Require
  4. Modificadores y el patrón checks-effects-interactions
← Volver a Blockchain Smart Contracts with Solidity