# foundry-invariant-fuzzing

> Foundry fuzz, fork and stateful invariant testing with handlers and ghost variables for DeFi logic.

foundry-invariant-fuzzing is a paid AI agent skill on Agensi by BanditXBT, in Security. It loads into your AI agent through the Agensi MCP server, always in its latest approved version.

- Price: $3.15 (one-time purchase)
- Creator: [BanditXBT](https://www.agensi.io/creators/banditxbt)
- Category: [Security](https://www.agensi.io/skills/security)
- Version: 1.0
- Last updated: 2026-11-21
- Security: scan passed (2026-11-21); every new listing is also reviewed by a person
- Listing: https://www.agensi.io/skills/foundry-invariant-fuzzing
- Tags: testing-debugging, web3-crypto, security

## About this skill

Unit tests prove examples; invariants prove the protocol cannot reach a bad state through *any* call sequence.

1. **Unit/regression:** one test per known behavior and per fixed bug (`test_RevertWhen_...`, `test_..._Succeeds`). Use `vm.expectRevert(abi.encodeWithSelector(...))` with exact errors.
2. **Stateless fuzz:** `function testFuzz_X(uint256 a, ...)`; constrain with `bound(x, min, max)` (not `vm.assume` for wide filters: it discards runs). Properties: round-trip (`deposit→withdraw ≤ deposit`), monotonicity, rounding direction, "never reverts for valid input", conservation of value.
3. **Fork tests:** `vm.createSelectFork(rpc, blockNumber)` pinned to a block for determinism; use for real tokens (USDT/USDC quirks, fee-on-transfer), real oracles, integration with live protocols. Run per target chain.
4. **Stateful invariants:** `invariant_*` functions checked after random call sequences.
5. **Formal/symbolic (when valuable):** Halmos for bounded symbolic checks on arithmetic-heavy functions (e.g., margin math); Echidna/Medusa for coverage-guided campaigns with corpus reuse.

- Write 5-10 protocol-level properties first (solvency, conservation, access, monotonic accumulators). For derivatives: `Σ user equity + insurance ≥ 0 and ≤ vault assets`, `OI_long == OI_short` (or within skew cap), `funding index never decreases unexpectedly`, `healthy account stays healthy after unrelated actions`, `liquidation never increases account risk`, `no position opens below initial margin`.
- **Handler pattern:** a `Handler` contract exposes bounded actor actions (`open`, `close`, `addCollateral`, `liquidate`, `warp time`, `move oracle price`, `donate`, `pause`). Use `targetContract(handler)`; bound all inputs; pick actors from a fixed set (`vm.startPrank(actors[seed % n])`).
- **Ghost variables** track expected totals off-protocol (sum of deposits, realized PnL) to compare against on-chain state.
- Include **adversarial actions** (donation, dust amounts, zero values, price jumps, time jumps, reentrant token) so the fuzzer explores them; guard against false positives from unreachable states.
- Avoid revert-hiding: set `fail_on_revert = false` only with handlers that already bound inputs; track call and revert counts in the handler (ghost counters) to ensure meaningful calls happen, and inspect with `forge test -vvv`.

1. List invariants → write handler → run small → inspect call distribution → increase runs/depth.
2. On failure: shrink, replay with `-vvvv`, minimal repro test, find the root cause by minimizing the call sequence and inspecting state at the first violated invariant (not just the last call), fix, keep the test.
3. **Mutation check:** break the contract on purpose (flip a `<`, remove a check, change rounding direction); the suite must fail. Use `vertigo-rs`/`gambit` if available; otherwise manual.
4. Gas and size: `forge snapshot`, `forge build --sizes` (24 KB limit); keep gas regressions in CI.
5. Coverage: `forge coverage --report lcov` to find unexercised branches; coverage guides, invariants decide.

## Requires

- Foundry

## How to use this skill

1. Connect your AI agent to Agensi once: add the MCP server https://mcp.agensi.io/mcp/auth and sign in with your Agensi account (OAuth, no API key). Steps for Claude, ChatGPT, Claude Code, Codex, Cursor, VS Code and other agents: https://www.agensi.io/docs/mcp-setup
2. Ask your agent: "Use the foundry-invariant-fuzzing skill from Agensi" and describe your task.
3. Buy it on the listing or let your agent ask you first; your agent then loads it from Agensi when it needs it. Every paid skill has a money-back guarantee: https://www.agensi.io/docs/money-back-guarantee

## Frequently asked questions

### What does foundry-invariant-fuzzing do?

Foundry fuzz, fork and stateful invariant testing with handlers and ghost variables for DeFi logic.

### Which AI agents support foundry-invariant-fuzzing?

This skill uses the open SKILL.md standard. Use it through an MCP-compatible agent connected to Agensi, and check the compatibility information on this page for confirmed agents and required capabilities.

### How do I use foundry-invariant-fuzzing?

Connect your AI agent to Agensi through MCP, then ask it to use foundry-invariant-fuzzing on your task. Your agent loads the latest approved version each time. Paid skills require a purchase or active subscription. Skill files are not available for download; your licence does not allow you to save, copy or export any part of a skill.

---

Source: [Agensi](https://www.agensi.io), the marketplace of skills for AI agents. Any MCP-compatible agent (Claude, ChatGPT, Claude Code, Codex, Cursor, VS Code and more) connects at https://mcp.agensi.io/mcp/auth and signs in with an Agensi account; setup for every agent: https://www.agensi.io/docs/mcp-setup. Append .md to any skill, guide or docs address on agensi.io for its markdown version.
