0Pricing
Web3 & DApp Development Fundamentals · レッスン

ファジングと不変条件

プロパティテスト

「ファジングと不変条件」はCoddyKit上の無料Web3 & DApp Development Fundamentalsレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはWeb3 & DApp Development Fundamentals学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Web3 & DApp Development Fundamentalsコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Beyond Hardcoded Inputs

Unit tests check specific inputs you thought of. But bugs often hide in inputs you did not think of. Property-based testing flips this: you state a property that should always hold, and the tool generates many random inputs trying to break it.

Foundry supports two flavors: fuzz tests and invariant tests.

Writing a Fuzz Test

A fuzz test is simply a test function with parameters. Foundry automatically calls it many times with randomized argument values, hunting for a counterexample.

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

Bounding Inputs

Random inputs may be unrealistic. Constrain them with:

  • vm.assume(cond) — discard runs that fail the condition
  • bound(x, min, max) — map any value into a range

Prefer bound for ranges since assume can waste runs by rejecting too many inputs.

function testFuzz(uint256 x) public {
    x = bound(x, 1, 1000); // always in [1, 1000]
    // ...
}

What Makes a Good Property

A good fuzz property is a statement that must hold for all valid inputs. Examples:

  • Depositing then withdrawing returns the same amount
  • Total supply never changes on a transfer
  • A user can never withdraw more than they deposited

Think in terms of universal truths, not specific values.

function testFuzzTransferConservesSupply(uint256 amt) public {
    uint256 supplyBefore = token.totalSupply();
    token.transfer(bob, bound(amt, 0, token.balanceOf(address(this))));
    assertEq(token.totalSupply(), supplyBefore);
}

Reading Fuzz Output

When a fuzz test fails, Foundry prints the exact counterexample that broke the property and the number of runs. It also stores a corpus so the failing input is replayed on future runs until you fix it.

$ forge test
[FAIL. Reason: assertion failed]
  Counterexample: calldata=0x..., args=[115792089237316195...]

Configuring the Fuzzer

Control fuzzing in foundry.toml. The runs setting is how many random inputs each fuzz test gets. More runs increase confidence but take longer.

# foundry.toml
[fuzz]
runs = 1000
max_test_rejects = 65536

Invariant Testing

Invariants go a step further. Instead of one function call, Foundry executes long random sequences of calls to your contract, then checks that a property still holds after every sequence.

Invariant functions are named with the invariant_ prefix.

function invariant_totalSupplyConstant() public {
    assertEq(token.totalSupply(), INITIAL_SUPPLY);
}

Handlers

For meaningful invariant tests you usually write a handler contract that exposes a curated set of actions. The fuzzer calls the handler's functions in random order, keeping the call sequences valid and focused.

Register target contracts with targetContract in setUp().

function setUp() public {
    handler = new Handler(token);
    targetContract(address(handler));
}

Ghost Variables

Handlers often track ghost variables: bookkeeping totals updated as actions run. Invariants compare the contract's real state against these ghost values.

For example, summing every deposit in the handler and asserting it equals the vault's total assets catches accounting drift.

// inside handler
uint256 public ghostTotalDeposited;
function deposit(uint256 a) external {
    vault.deposit(a);
    ghostTotalDeposited += a;
}

Fuzz vs Invariant

Knowing which to reach for:

  • Fuzz tests a single function against random arguments — good for input validation and pure logic
  • Invariant tests random sequences of actions — good for stateful systems like vaults, AMMs, and token accounting

Use both: fuzz for unit-level properties, invariants for system-level guarantees.

Best Practices

Effective property testing:

  • State properties as universal truths, not examples
  • Use bound over heavy assume
  • Increase runs for critical contracts
  • Write focused handlers for invariants
  • Track ghost variables for accounting checks

Property tests catch the edge cases humans miss.

Quick Check

What is the key difference between a fuzz test and an invariant test in Foundry?

Recap

You learned property-based testing:

  • Fuzz tests take parameters; Foundry generates random inputs
  • Use bound and vm.assume to constrain inputs
  • Invariant tests run random call sequences via handlers
  • Ghost variables track expected state for accounting invariants
  • Counterexamples are saved and replayed

Next: the cast and anvil CLI tools.

よくある質問

「ファジングと不変条件」レッスンは無料ですか?

はい。「ファジングと不変条件」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Web3 & DApp Development Fundamentalsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Web3 & DApp Development Fundamentalsコースには全4レッスンが含まれています。

「ファジングと不変条件」で何を学びますか?

プロパティテスト ブラウザで直接実行するハンズオンコードでWeb3 & DApp Development Fundamentalsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Web3 & DApp Development Fundamentalsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのWeb3 & DApp Development Fundamentalsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「ファジングと不変条件」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このWeb3 & DApp Development Fundamentalsレッスンでコードを書いて実行できますか?

はい。すべてのWeb3 & DApp Development Fundamentalsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. FoundryとHardhatの比較
  2. forgeによるテスト
  3. ファジングと不変条件
  4. castとanvil
← Web3 & DApp Development Fundamentalsに戻る