Foundry Testing & Script Skill
Rules and patterns for Foundry tests. Find examples in the actual codebase.
Bundled References
| Reference |
Content |
When to Read |
.claude/skills/foundry-testing/references/test-infrastructure.md |
Constants, defaults, mocks |
When setting up tests |
.claude/skills/foundry-testing/references/cheat-codes.md |
Common cheatcode patterns |
When using vm cheatcodes |
.claude/skills/foundry-testing/references/invariant-patterns.md |
Handlers, stores, invariants |
When writing invariant tests |
.claude/skills/foundry-testing/references/formal-verification.md |
Halmos, Certora, symbolic exec |
When proving correctness |
.claude/skills/foundry-testing/references/deployment-scripts.md |
Script patterns, verification |
When writing deploy scripts |
.claude/skills/foundry-testing/references/deployment-checklist.md |
Pre-mainnet deployment steps |
Before deploying to production |
.claude/skills/foundry-testing/references/gas-benchmarking.md |
Snapshot, profiling, CI |
When measuring gas performance |
.claude/skills/foundry-testing/references/sablier-conventions.md |
Sablier-specific patterns |
When working in Sablier repos |
Test Types
| Type |
Directory |
Naming |
Purpose |
| Integration |
tests/integration/concrete/ |
*.t.sol |
BTT-based concrete tests |
| Fuzz |
tests/integration/fuzz/ |
*.t.sol |
Property-based testing |
| Fork |
tests/fork/ |
*.t.sol |
Mainnet state testing |
| Invariant |
tests/invariant/ |
Invariant*.t.sol |
Stateful protocol properties |
| Scripts |
scripts/solidity/ |
*.s.sol |
Deployment/initialization |
1. Integration Tests (Concrete)
Naming Convention
| Pattern |
Usage |
test_RevertWhen_{Condition} |
Revert on input |
test_RevertGiven_{State} |
Revert on state |
test_When_{Condition} |
Success path |
Rules
- Stack modifiers to document BTT path (modifiers are often empty - just document the path)
- Expect events BEFORE action -
vm.expectEmit() then call function
- Assert state AFTER action - Check state changes after function executes
- Use revert helpers for common patterns (
expectRevert_DelegateCall, expectRevert_Null)
- Named parameters in assertions -
assertEq(actual, expected, "description")
Mock Rules
- Place all mocks in
tests/mocks/
- One mock per scenario (not one mega-mock)
- Naming:
*Good, *Reverting, *InvalidSelector, *Reentrant
2. Fuzz Tests
Naming Convention
testFuzz_{FunctionName}_{Scenario}
Rules
- Bound before assume -
_bound() is more efficient than vm.assume()
- Bound in dependency order - Independent params first, then dependent
- Never hardcode params with validation constraints
- Document fuzzed scenarios in NatSpec
Bounding Pattern
// 1. Bound independent params first
cliffDuration = boundUint40(cliffDuration, 0, MAX - 1);
// 2. Bound dependent params based on constraints
totalDuration = boundUint40(totalDuration, cliffDuration + 1, MAX);
3. Fork Tests
Rules
- Create fork with
vm.createSelectFork("ethereum")
- Use
deal() to give tokens to test users
- Use
assumeNoBlacklisted() for USDC/USDT
- Use
forceApprove() for non-standard tokens (USDT)
Token Quirks
| Token |
Issue |
Solution |
| USDC/USDT |
Blacklist |
assumeNoBlacklisted() |
| USDT |
Non-standard |
forceApprove() |
| Fee-on-transfer |
Balance diff |
Check actual received amount |
4. Invariant Tests
Architecture
tests/invariant/
├── handlers/ # State manipulation (call functions with bounded params)
├── stores/ # State tracking (record totals, IDs)
└── Invariant.t.sol
Rules
- Target handlers only -
targetContract(address(handler))
- Exclude protocol contracts -
excludeSender(address(vault))
- Use stores to track totals for invariant assertions
- Early return in handlers if preconditions not met
5. Solidity Scripts
Rules
- Inherit from
BaseScript with broadcast modifier
- Use env vars:
ETH_FROM, MNEMONIC
- Simulation first, then broadcast
Commands
# Simulation
forge script scripts/Deploy.s.sol --sig "run(...)" ARGS --rpc-url $RPC
# Broadcast
forge script scripts/Deploy.s.sol --sig "run(...)" ARGS --rpc-url $RPC --broadcast --verify
Running Tests
# By type
forge test --match-path "tests/integration/concrete/**"
forge test --match-path "tests/fork/**"
forge test --match-contract Invariant_Test
# Specific test
forge test --match-test test_WhenCallerRecipient -vvvv
# Fuzz with more runs
forge test --match-test testFuzz_ --fuzz-runs 1000
# Coverage
forge coverage --report lcov
Debugging
Verbosity Levels
| Flag |
Shows |
-v |
Logs for failing tests |
-vv |
Logs for all tests |
-vvv |
Stack traces for failures |
-vvvv |
Stack traces + setup traces |
-vvvvv |
Full execution traces |
Console Logging
import { console2 } from "forge-std/console2.sol";
console2.log("value:", someValue);
console2.log("address:", someAddress);
console2.logBytes32(someBytes32);
Debugging Commands
# Trace specific failing test
forge test --match-test test_MyTest -vvvv
# Gas report for a test
forge test --match-test test_MyTest --gas-report
# Debug in interactive debugger
forge debug --debug tests/MyTest.t.sol --sig "test_MyTest()"
# Inspect storage layout
forge inspect MyContract storage-layout
Debugging Tips
- Label addresses -
vm.label(addr, "Recipient") for readable traces
- Check state with logs - Add
console2.log before reverts
- Isolate failures - Run single test with
--match-test
- Compare gas - Use
--gas-report to spot unexpected costs
- Snapshot comparisons - Use
vm.snapshot() / vm.revertTo() to isolate state changes
Best Practices Summary
- Use constants from
Defaults/Constants - never hardcode
- Specialized mocks - one per scenario, all in
tests/mocks/
- Modifiers in
Modifiers.sol - centralize BTT path modifiers
- Label addresses with
vm.label() for traces
- Events before actions -
vm.expectEmit() then call
- Bound before assume - more efficient
External References
Example Invocations
Test this skill with these prompts:
- Integration test: "Write a concrete test for
withdraw that expects Errors.Flow_Overdraw when amount exceeds
balance"
- Fuzz test: "Create a fuzz test for
deposit that bounds amount between 1 and type(uint128).max"
- Fork test: "Write a fork test for USDC deposits on mainnet with blacklist handling"
- Invariant test: "Create an invariant handler for the
deposit and withdraw functions"
- Deploy script: "Write a deployment script for SablierFlow with verification"
1---2name: foundry-testing3user-invocable: true4description:5 Write Foundry-based tests and scripts. Trigger phrases - foundry testing, write test, fuzz test, fork test, invariant6 test, deploy script, gas benchmark, coverage, or when working in tests/ or scripts/ directories.7metadata:8 source: https://skillmd.com/skills/sablier-labs/foundry-testing9---1011# Foundry Testing & Script Skill1213Rules and patterns for Foundry tests. Find examples in the actual codebase.1415## Bundled References1617| Reference | Content | When to Read |18| ------------------------------------------------------------------- | ------------------------------ | ------------------------------ |19| `.claude/skills/foundry-testing/references/test-infrastructure.md` | Constants, defaults, mocks | When setting up tests |20| `.claude/skills/foundry-testing/references/cheat-codes.md` | Common cheatcode patterns | When using vm cheatcodes |21| `.claude/skills/foundry-testing/references/invariant-patterns.md` | Handlers, stores, invariants | When writing invariant tests |22| `.claude/skills/foundry-testing/references/formal-verification.md` | Halmos, Certora, symbolic exec | When proving correctness |23| `.claude/skills/foundry-testing/references/deployment-scripts.md` | Script patterns, verification | When writing deploy scripts |24| `.claude/skills/foundry-testing/references/deployment-checklist.md` | Pre-mainnet deployment steps | Before deploying to production |25| `.claude/skills/foundry-testing/references/gas-benchmarking.md` | Snapshot, profiling, CI | When measuring gas performance |26| `.claude/skills/foundry-testing/references/sablier-conventions.md` | Sablier-specific patterns | When working in Sablier repos |2728---2930## Test Types3132| Type | Directory | Naming | Purpose |33| ----------- | ----------------------------- | ------------------ | ---------------------------- |34| Integration | `tests/integration/concrete/` | `*.t.sol` | BTT-based concrete tests |35| Fuzz | `tests/integration/fuzz/` | `*.t.sol` | Property-based testing |36| Fork | `tests/fork/` | `*.t.sol` | Mainnet state testing |37| Invariant | `tests/invariant/` | `Invariant*.t.sol` | Stateful protocol properties |38| Scripts | `scripts/solidity/` | `*.s.sol` | Deployment/initialization |3940---4142## 1. Integration Tests (Concrete)4344### Naming Convention4546| Pattern | Usage |47| ----------------------------- | --------------- |48| `test_RevertWhen_{Condition}` | Revert on input |49| `test_RevertGiven_{State}` | Revert on state |50| `test_When_{Condition}` | Success path |5152### Rules53541. **Stack modifiers** to document BTT path (modifiers are often empty - just document the path)552. **Expect events BEFORE action** - `vm.expectEmit()` then call function563. **Assert state AFTER action** - Check state changes after function executes574. **Use revert helpers** for common patterns (`expectRevert_DelegateCall`, `expectRevert_Null`)585. **Named parameters in assertions** - `assertEq(actual, expected, "description")`5960### Mock Rules61621. Place all mocks in `tests/mocks/`632. One mock per scenario (not one mega-mock)643. Naming: `*Good`, `*Reverting`, `*InvalidSelector`, `*Reentrant`6566---6768## 2. Fuzz Tests6970### Naming Convention7172`testFuzz_{FunctionName}_{Scenario}`7374### Rules75761. **Bound before assume** - `_bound()` is more efficient than `vm.assume()`772. **Bound in dependency order** - Independent params first, then dependent783. **Never hardcode** params with validation constraints794. **Document fuzzed scenarios** in NatSpec8081### Bounding Pattern8283```solidity84// 1. Bound independent params first85cliffDuration = boundUint40(cliffDuration, 0, MAX - 1);8687// 2. Bound dependent params based on constraints88totalDuration = boundUint40(totalDuration, cliffDuration + 1, MAX);89```9091---9293## 3. Fork Tests9495### Rules96971. Create fork with `vm.createSelectFork("ethereum")`982. Use `deal()` to give tokens to test users993. Use `assumeNoBlacklisted()` for USDC/USDT1004. Use `forceApprove()` for non-standard tokens (USDT)101102### Token Quirks103104| Token | Issue | Solution |105| --------------- | ------------ | ---------------------------- |106| USDC/USDT | Blacklist | `assumeNoBlacklisted()` |107| USDT | Non-standard | `forceApprove()` |108| Fee-on-transfer | Balance diff | Check actual received amount |109110---111112## 4. Invariant Tests113114### Architecture115116```117tests/invariant/118├── handlers/ # State manipulation (call functions with bounded params)119├── stores/ # State tracking (record totals, IDs)120└── Invariant.t.sol121```122123### Rules1241251. **Target handlers only** - `targetContract(address(handler))`1262. **Exclude protocol contracts** - `excludeSender(address(vault))`1273. **Use stores** to track totals for invariant assertions1284. **Early return** in handlers if preconditions not met129130---131132## 5. Solidity Scripts133134### Rules1351361. Inherit from `BaseScript` with `broadcast` modifier1372. Use env vars: `ETH_FROM`, `MNEMONIC`1383. Simulation first, then broadcast139140### Commands141142```bash143# Simulation144forge script scripts/Deploy.s.sol --sig "run(...)" ARGS --rpc-url $RPC145146# Broadcast147forge script scripts/Deploy.s.sol --sig "run(...)" ARGS --rpc-url $RPC --broadcast --verify148```149150---151152## Running Tests153154```bash155# By type156forge test --match-path "tests/integration/concrete/**"157forge test --match-path "tests/fork/**"158forge test --match-contract Invariant_Test159160# Specific test161forge test --match-test test_WhenCallerRecipient -vvvv162163# Fuzz with more runs164forge test --match-test testFuzz_ --fuzz-runs 1000165166# Coverage167forge coverage --report lcov168```169170---171172## Debugging173174### Verbosity Levels175176| Flag | Shows |177| -------- | --------------------------- |178| `-v` | Logs for failing tests |179| `-vv` | Logs for all tests |180| `-vvv` | Stack traces for failures |181| `-vvvv` | Stack traces + setup traces |182| `-vvvvv` | Full execution traces |183184### Console Logging185186```solidity187import { console2 } from "forge-std/console2.sol";188189console2.log("value:", someValue);190console2.log("address:", someAddress);191console2.logBytes32(someBytes32);192```193194### Debugging Commands195196```bash197# Trace specific failing test198forge test --match-test test_MyTest -vvvv199200# Gas report for a test201forge test --match-test test_MyTest --gas-report202203# Debug in interactive debugger204forge debug --debug tests/MyTest.t.sol --sig "test_MyTest()"205206# Inspect storage layout207forge inspect MyContract storage-layout208```209210### Debugging Tips2112121. **Label addresses** - `vm.label(addr, "Recipient")` for readable traces2132. **Check state with logs** - Add `console2.log` before reverts2143. **Isolate failures** - Run single test with `--match-test`2154. **Compare gas** - Use `--gas-report` to spot unexpected costs2165. **Snapshot comparisons** - Use `vm.snapshot()` / `vm.revertTo()` to isolate state changes217218---219220## Best Practices Summary2212221. Use constants from `Defaults`/`Constants` - never hardcode2232. Specialized mocks - one per scenario, all in `tests/mocks/`2243. Modifiers in `Modifiers.sol` - centralize BTT path modifiers2254. Label addresses with `vm.label()` for traces2265. Events before actions - `vm.expectEmit()` then call2276. Bound before assume - more efficient228229## External References230231- [Foundry Book](https://getfoundry.sh)232233---234235## Example Invocations236237Test this skill with these prompts:2382391. **Integration test**: "Write a concrete test for `withdraw` that expects `Errors.Flow_Overdraw` when amount exceeds240 balance"2412. **Fuzz test**: "Create a fuzz test for `deposit` that bounds amount between 1 and type(uint128).max"2423. **Fork test**: "Write a fork test for USDC deposits on mainnet with blacklist handling"2434. **Invariant test**: "Create an invariant handler for the `deposit` and `withdraw` functions"2445. **Deploy script**: "Write a deployment script for SablierFlow with verification"