0Pricing
Blockchain Smart Contracts with Solidity · Leçon

Fuzzing et tests d’invariants

Apprenez comment le fuzzing fondé sur les propriétés et les tests d’invariants détectent, avec Foundry comme framework d’exemple, les erreurs limites des contrats intelligents que les tests unitaires fixes ne repèrent pas.

Fuzzing et tests d’invariants est une leçon Blockchain Smart Contracts with Solidity gratuite sur CoddyKit. Ceci est la leçon 4 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Blockchain Smart Contracts with Solidity, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Blockchain Smart Contracts with Solidity comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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.

Questions Fréquemment Posées

La leçon « Fuzzing et tests d’invariants » est-elle gratuite ?

Oui — le texte complet de « Fuzzing et tests d’invariants » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Blockchain Smart Contracts with Solidity, passe à CoddyKit PRO. Le cours Blockchain Smart Contracts with Solidity comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Fuzzing et tests d’invariants » ?

Apprenez comment le fuzzing fondé sur les propriétés et les tests d’invariants détectent, avec Foundry comme framework d’exemple, les erreurs limites des contrats intelligents que les tests unitaires… Tu pratiques Blockchain Smart Contracts with Solidity avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Blockchain Smart Contracts with Solidity ?

Aucune expérience préalable n'est requise. Blockchain Smart Contracts with Solidity sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 4 sur 4.

Combien de temps prend la leçon « Fuzzing et tests d’invariants » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Blockchain Smart Contracts with Solidity ?

Oui. Chaque leçon Blockchain Smart Contracts with Solidity inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Tests avancés avec Foundry/Hardhat
  2. Bases de la vérification formelle
  3. Déploiement et surveillance sur le mainnet
  4. Fuzzing et tests d’invariants
← Retour à Blockchain Smart Contracts with Solidity