Blockchain Smart Contracts with Solidity · Lekcja

Fuzzing i testowanie inwariantów

Naucz się, jak fuzzing oparty na właściwościach i testowanie inwariantów wykrywają brzegowe błędy w smart kontraktach pomijane przez stałe testy jednostkowe, korzystając z Foundry jako przykładowego frameworka.

Lekcja 4 z 413 kroki

Fuzzing i testowanie inwariantów to bezpłatna lekcja Blockchain Smart Contracts with Solidity na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Blockchain Smart Contracts with Solidity, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Blockchain Smart Contracts with Solidity zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Bezpłatny start

Ucz się Blockchain Smart Contracts with Solidity dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
12
Lekcje
48

Często zadawane pytania

Czy lekcja „Fuzzing i testowanie inwariantów” jest bezpłatna?

Tak — pełny tekst „Fuzzing i testowanie inwariantów” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Blockchain Smart Contracts with Solidity, przejdź na CoddyKit PRO. Kurs Blockchain Smart Contracts with Solidity zawiera 4 lekcji w sumie.

Co nauczysz się w „Fuzzing i testowanie inwariantów”?

Naucz się, jak fuzzing oparty na właściwościach i testowanie inwariantów wykrywają brzegowe błędy w smart kontraktach pomijane przez stałe testy jednostkowe, korzystając z Foundry jako przykładowego… Ćwiczysz Blockchain Smart Contracts with Solidity z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Blockchain Smart Contracts with Solidity?

Nie wymagamy żadnego doświadczenia. Blockchain Smart Contracts with Solidity w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Fuzzing i testowanie inwariantów”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Blockchain Smart Contracts with Solidity?

Tak. Każda lekcja Blockchain Smart Contracts with Solidity zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Zaawansowane testowanie z Foundry/Hardhat
  2. Podstawy weryfikacji formalnej
  3. Wdrażanie i monitorowanie na mainnecie
  4. Fuzzing i testowanie inwariantów
← Powrót do Blockchain Smart Contracts with Solidity