0Pricing
Blockchain Smart Contracts with Solidity · Lección

Fuzzing y pruebas de invariantes

Aprenda cómo el fuzzing basado en propiedades y las pruebas de invariantes detectan errores en casos límite de smart contracts que las pruebas unitarias fijas no encuentran, utilizando Foundry como framework de ejemplo.

Fuzzing y pruebas de invariantes 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.

Limits of Example Tests

You have written unit tests with specific inputs. But attackers find the one input you did not try. Fixed examples cannot cover the huge space of possible values. This is where fuzzing helps.

What Is Fuzzing?

Fuzz testing runs a test many times with randomly generated inputs. Instead of asserting on one value, you assert a property that should hold for all inputs.

A Fuzz Test in Foundry

In Foundry, any test function parameter is automatically fuzzed. The framework feeds in many random values.

function testFuzz_DepositIncreasesBalance(uint256 amount) public {
    vm.assume(amount > 0 && amount < 1e30);
    vault.deposit(amount);
    assertEq(vault.balanceOf(address(this)), amount);
}

Bounding Inputs

Random values can be absurd (like the max uint256). Use vm.assume to discard bad inputs or bound to map a value into a valid range so tests stay meaningful.

function testFuzz_Transfer(uint256 amount) public {
    amount = bound(amount, 1, token.balanceOf(address(this)));
    token.transfer(bob, amount);
    assertEq(token.balanceOf(bob), amount);
}

Thinking in Properties

The shift is from 'with input X expect Y' to 'no matter the input, this rule holds'. Common properties:

  • Total supply never changes on a transfer
  • A user can never withdraw more than they deposited
  • Balances never underflow

What Are Invariants?

An invariant is a property that must hold after any sequence of operations, not just one call. Invariant testing fires many random function calls in random order, then checks the invariant after each step.

Declaring an Invariant

In Foundry, functions prefixed with invariant_ are checked after each randomized call sequence.

function invariant_TotalSupplyEqualsSumOfBalances() public {
    assertEq(token.totalSupply(), handler.sumOfBalances());
}

The Handler Pattern

Raw random calls often revert or wander into useless states. A handler contract wraps the target with guided, valid actions and tracks expected totals (ghost variables) for the invariant to check.

contract Handler {
    Token token;
    uint256 public sumOfBalances;

    function transfer(uint256 toSeed, uint256 amount) external {
        // bounded, valid transfer logic that updates ghost totals
    }
}

Shrinking Failures

When a fuzzer finds a failing input, it shrinks it to the simplest counterexample. This makes the bug far easier to understand and reproduce than a random gigantic number.

Tuning Test Runs

More runs find deeper bugs but take longer. Configure run counts in foundry.toml for CI versus quick local checks.

[fuzz]
runs = 1000

[invariant]
runs = 256
depth = 50

When to Use Each

Use fuzzing to harden individual functions against unexpected single inputs. Use invariant testing to verify system-wide rules survive any sequence of actions. Together they catch classes of bugs fixed tests never reach.

Quick Check

Test your understanding of property-based testing.

Recap

You learned fuzzing and invariant testing:

  • Fuzzing runs functions with many random inputs against properties
  • vm.assume and bound keep inputs valid
  • Invariants check system rules across random call sequences
  • Handlers guide actions; shrinking simplifies failures

These techniques uncover edge cases that example-based tests miss.

Preguntas frecuentes

¿La lección «Fuzzing y pruebas de invariantes» es gratis?

Sí — el texto completo de «Fuzzing y pruebas de invariantes» 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 «Fuzzing y pruebas de invariantes»?

Aprenda cómo el fuzzing basado en propiedades y las pruebas de invariantes detectan errores en casos límite de smart contracts que las pruebas unitarias fijas no encuentran, utilizando Foundry como f… 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 «Fuzzing y pruebas de invariantes»?

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. Pruebas avanzadas con Foundry/Hardhat
  2. Fundamentos de verificación formal
  3. Despliegue y monitorización en mainnet
  4. Fuzzing y pruebas de invariantes
← Volver a Blockchain Smart Contracts with Solidity