Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

writing-foundry-tests

БесплатноБез исполняемых скриптовНе проверен

Use when writing, modifying, or reviewing Foundry tests. Covers forge-std Test base, setUp, vm cheatcodes (prank, expectRevert by selector, expectEmit…

idchain-worldот idchain-world★ 19 звёзд на GitHub

Об этом скилле

Writing Foundry Tests

You are writing a Foundry test. Tests are the only thing that stands between your Solidity and a real user's money. Treat every test as a contract that must be read, maintained, and trusted for years.

The Iron Laws

  1. NO vm.expectRevert() BARE. Always pass the custom-error selector or the encoded error, e.g. vm.expectRevert(IERC20Errors.ERC20InsufficientBalance.selector). A bare expectRevert() matches any revert, including ones you introduced by accident. That is not a test, it is a placeholder.
  2. NO STRING-BASED REVERT MATCHING. vm.expectRevert("Insufficient balance") is banned for new code. Use custom errors + selector matching. Strings cost gas, break on typos, and silently pass when the revert reason changes.
  3. NO UNBOUNDED FUZZ INPUTS. Every fuzz parameter gets bound(x, min, max) or vm.assume(condition). Unbounded uint256 inputs waste runs on type(uint256).max overflows that prove nothing about your business logic.
  4. NO ASSERT WITHOUT A MESSAGE. Use assertEq(a, b, "balance after transfer"), not assertEq(a, b). When the assert fires in CI six months from now, the message is the only context the failing engineer has.
  5. NO TEST WITHOUT A test_ OR testFuzz_ OR invariant_ PREFIX. Foundry discovers tests by prefix. A helper named transferTokens silently stops being a test. Use _helperTransferTokens for helpers — underscore-prefixed private functions.
  6. NO SHARED MUTABLE STATE ACROSS TESTS. setUp() runs before every test. If you rely on state from another test, you have a test bug. Write each test as if it is the only one in the file.

Test file shape

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {Test} from "forge-std/Test.sol";
import {MyToken} from "../src/MyToken.sol";

contract MyTokenTest is Test {
    MyToken internal token;
    address internal alice = makeAddr("alice");
    address internal bob = makeAddr("bob");

    function setUp() public {
        token = new MyToken("Test", "TEST");
        deal(address(token), alice, 100 ether);
    }

    function test_Transfer_MovesBalance() public {
        vm.prank(alice);
        token.transfer(bob, 10 ether);

        assertEq(token.balanceOf(alice), 90 ether, "alice balance after transfer");
        assertEq(token.balanceOf(bob),   10 ether, "bob balance after transfer");
    }
}

Conventions:

  • One contract per test file, named <ContractUnderTest>Test.
  • makeAddr("alice") over raw hex addresses — the label shows in traces.
  • deal(token, to, amount) over manual mint calls when you want to set up balances without exercising the mint path.
  • internal visibility on test helpers (compiler hint) and test state (so subclassed test contracts can reach them).

The cheatcodes you actually use

Identity and balance

Cheatcode Effect
vm.prank(addr) Next call's msg.sender is addr. One call.
vm.startPrank(addr) / vm.stopPrank() All calls until stop are from addr.
vm.prank(caller, origin) Sets both msg.sender and tx.origin.
makeAddr("label") Deterministic address with a human label in traces.
deal(token, to, amount) Sets ERC20 balance directly (forge-std helper).
vm.deal(addr, ether) Sets native ETH balance.

Time and block

Cheatcode Effect
vm.warp(ts) Sets block.timestamp.
vm.roll(blockNum) Sets block.number.
skip(seconds) vm.warp(block.timestamp + seconds) (forge-std).
rewind(seconds) Mirror of skip.

Reverts

Always by selector for custom errors:

// Custom error in the contract:
error Unauthorized(address caller);

// In the test:
vm.expectRevert(abi.encodeWithSelector(Unauthorized.selector, alice));
vm.prank(alice);
token.adminOnly();

For errors with no args, use SelectorName.selector directly:

vm.expectRevert(MyContract.AlreadyInitialized.selector);
target.initialize();

Events

// Declare the event in the test file or import from the contract.
event Transfer(address indexed from, address indexed to, uint256 value);

function test_Transfer_EmitsEvent() public {
    vm.expectEmit(true, true, false, true, address(token));
    emit Transfer(alice, bob, 10 ether);

    vm.prank(alice);
    token.transfer(bob, 10 ether);
}

The four bool args are checkTopic1, checkTopic2, checkTopic3, checkData. Be explicit. The fifth arg (the emitter) prevents false positives from events emitted by other contracts in the same call.

Mocking external calls

vm.mockCall(
    address(oracle),
    abi.encodeWithSelector(IOracle.price.selector),
    abi.encode(uint256(2000e8))
);

vm.mockCallRevert for the unhappy path. Use mocks sparingly — prefer deploying a real minimal stub. Mocks hide integration drift.

Recording logs

vm.recordLogs();
target.doSomething();
Vm.Log[] memory entries = vm.getRecordedLogs();
Полный SKILL.md на GitHub

Установить writing-foundry-tests в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл writing-foundry-tests?

Use when writing, modifying, or reviewing Foundry tests. Covers forge-std Test base, setUp, vm cheatcodes (prank, expectRevert by selector, expectEmit, warp/roll, mockCall, recordLogs), fuzz bounds with vm.assume and bound, invariant testing with StdInvariant and handler contracts, and the assertion patterns that make failures debuggable.

Как установить скилл writing-foundry-tests?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл writing-foundry-tests запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить writing-foundry-tests с