> loading_
# To get started with the new `StdInvariant.Handler`, you can create a test setup like the one below.
# This example shows how to test a simple ERC20 token by defining a custom handler that inherits from our new base contract.
```solidity
// MyTokenInvariantTest.t.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
import "forge-std/Test.sol";
import "forge-std/StdInvariant.sol";
import "src/MyToken.sol"; // The contract under test
// 1. Define your test contract inheriting from `Test`.
contract MyTokenInvariantTest is Test {
MyToken token;
TokenHandler handler;
function setUp() public {
token = new MyToken();
// 2. Instantiate your handler, passing in the contract to test.
handler = new TokenHandler(token);
// 3. Set the handler contract as the target for the fuzzer.
// Foundry will now call functions on `handler`.
targetContract(address(handler));
}
// 4. Define your invariant. This property will be checked after every call to the handler.
function invariant_totalSupplyIsConstant() public {
assertEq(token.totalSupply(), 1_000_000e18);
}
}
// 5. Create a handler that inherits from the new `StdInvariant.Handler`.
contract TokenHandler is Handler {
MyToken internal token;
constructor(MyToken _token) {
token = _token;
// 6. Use the built-in `actors` array to define which addresses
// can interact with the contract during the test.
address actor1 = vm.addr(1);
address actor2 = vm.addr(2);
actors.push(actor1);
actors.push(actor2);
}
// 7. Define functions the fuzzer can call. The handler automatically
// selects a sender from the `actors` array for each external call.
function transfer(address to, uint256 amount) public {
token.transfer(to, amount);
}
function approve(address spender, uint256 amount) public {
token.approve(spender, amount);
}
}
```