---
description: Smart Contract Testing
alwaysApply: false
---

# Smart Contract Testing

Testing strategies using Foundry for smart contract verification.

## Testing Philosophy

- Test behavior, not implementation
- 100% branch coverage minimum
- Fuzz everything — random inputs catch edge cases humans miss
- Invariants are mandatory — properties that must always hold
- Fork tests for real protocol integrations

## Test Types

| Type | Target | Purpose |
|------|--------|---------|
| Unit | 100% branches | Individual function correctness |
| Fuzz | 10,000+ runs | Edge cases via random inputs |
| Invariant | 10,000+ calls | System properties always hold |
| Fork | Critical paths | Real protocol integrations |

## Test Structure

- File per function or concern: `Vault.deposit.t.sol`, `Vault.withdraw.t.sol`
- Use named actors: `makeAddr("user")`, `makeAddr("attacker")`
- Setup in `setUp()`: deploy contracts, mint tokens, set approvals

## Fuzz Testing

```solidity
function testFuzz_deposit(uint256 amount) public {
    amount = bound(amount, 1, INITIAL_BALANCE);
    vm.prank(user);
    vault.deposit(amount, user);
    assertEq(vault.balanceOf(user), amount);
}
```

- Use `bound()` to constrain inputs to valid ranges
- Use `vm.assume()` to skip invalid addresses/states

## Invariant Testing

- Create handler contracts that perform valid sequences of actions
- Track ghost variables (e.g., `ghost_totalDeposited`) for accounting invariants
- Key invariants: total assets >= total shares, sum of balances == total supply, deposit-withdraw accounting

## Fork Testing

- Fork at specific block for reproducibility: `vm.createFork(rpcUrl, blockNumber)`
- Use `deal()` to set token balances
- Test against real deployed contracts (Uniswap, Aave, etc.)

## Key Cheatcodes

```solidity
vm.prank(user);                    // next call from user
vm.warp(block.timestamp + 1 days); // set timestamp
deal(address(token), user, 1000e18); // set balance
vm.expectRevert(Error.selector);   // expect revert
vm.expectEmit(true, true, false, true); // expect event
vm.snapshot() / vm.revertTo(id);   // save/restore state
```

## Running Tests

```bash
forge test                          # all tests
forge test -vvvv                    # with traces
forge test --gas-report             # gas benchmarks
forge coverage                      # coverage report
```
