> For the complete documentation index, see [llms.txt](https://gotts.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gotts.gitbook.io/docs/gotts-vaults/vault/17-testing.md).

# Testing Strategy

> **Part of**: [Vault PRD](/docs/gotts-vaults/vault.md) | **Last Updated**: 2026-02-16

***

## Overview

This section defines the testing strategy for Gotts Vaults. It specifies invariant properties, fuzzing parameters, fork test scenarios, integration test matrices, and CI gate requirements per phase.

***

## 1. Invariant Properties (Formally Stated)

Invariant tests run continuously via Foundry's `invariant_*` test functions. Every invariant must hold after any sequence of valid operations.

### 1.1 Share Price Invariants

| ID    | Invariant                              | Formal Statement                                                                                  |
| ----- | -------------------------------------- | ------------------------------------------------------------------------------------------------- |
| INV-1 | Share price monotonicity (modulo fees) | `sharePrice(t+1) >= sharePrice(t) - maxFeeImpact` after any non-loss operation                    |
| INV-2 | No inflation attack                    | `deposit(1 wei)` must mint > 0 shares for any vault state (enforced by `_decimalsOffset`)         |
| INV-3 | Profit unlock linearity                | `unlockedProfit()` decreases linearly over `profitMaxUnlockTime`; never negative                  |
| INV-4 | Share price bounded rate of change     | `abs(sharePrice(t) - sharePrice(t-1)) / sharePrice(t-1) <= navMaxChangeBps` per snapshot interval |

### 1.2 Accounting Invariants

| ID    | Invariant                  | Formal Statement                                                                                                      |
| ----- | -------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| INV-5 | Total assets conservation  | `totalAssets() >= sum(adapterAssets[i]) + idleCapital - accruedFees` (within rounding tolerance of `_decimalsOffset`) |
| INV-6 | Share supply consistency   | `totalSupply() == sum(agentShares[agentId])` for all registered agents                                                |
| INV-7 | Deposit-withdraw roundtrip | For any deposit `d`, `withdraw(deposit(d))` returns `>= d - maxFeeImpact - roundingError`                             |
| INV-8 | No free shares             | `deposit(0)` mints 0 shares; `withdraw(0)` burns 0 shares                                                             |

### 1.3 Identity and Access Invariants

| ID     | Invariant                    | Formal Statement                                                                                                |
| ------ | ---------------------------- | --------------------------------------------------------------------------------------------------------------- |
| INV-9  | Identity gate                | No deposit/withdraw/rebalance can succeed for `agentId` where `identityRegistry.isValidAgent(agentId) == false` |
| INV-10 | Tier cap enforcement         | `agentDepositTotal[agentId] <= tierConfig[agentTier].maxDeposit` after any deposit                              |
| INV-11 | Factory registry consistency | `factory.isVault(v) == true` for every address `v` returned by `factory.getAllVaults()`                         |

### 1.4 Circuit Breaker Invariants

| ID     | Invariant             | Formal Statement                                                                                  |
| ------ | --------------------- | ------------------------------------------------------------------------------------------------- |
| INV-12 | Drawdown pause        | If `(highWaterMark - totalAssets()) / highWaterMark > maxDrawdownBps`, vault is paused            |
| INV-13 | Continuous dampening  | No single operation transitions vault from "fully operational" to "fully halted" (always gradual) |
| INV-14 | Oracle staleness gate | If oracle age > `oracleMaxStaleness`, NAV pricing is disabled                                     |

***

## 2. Fuzzing Parameter Ranges

Foundry fuzz tests use the following parameter ranges. Ranges are chosen to cover realistic values and boundary conditions.

| Parameter             | Min      | Max                                | Distribution | Notes                                                    |
| --------------------- | -------- | ---------------------------------- | ------------ | -------------------------------------------------------- |
| Deposit amount        | 1 wei    | 10^24 (1M tokens with 18 decimals) | Log-uniform  | Covers dust deposits through whale deposits              |
| Withdraw shares       | 1        | `totalSupply()`                    | Uniform      | Includes full-withdrawal edge case                       |
| Management fee        | 0        | 500 bps                            | Uniform      | Full range up to immutable cap                           |
| Performance fee       | 0        | 5000 bps                           | Uniform      | Full range up to immutable cap                           |
| Reputation score      | 0        | 1000                               | Uniform      | Covers all 5 tiers                                       |
| Agent count           | 1        | 100                                | Linear       | Gas cost scaling                                         |
| Time elapsed          | 1 second | 365 days                           | Log-uniform  | Covers profit unlock, oracle staleness, reputation decay |
| Price change          | -99%     | +1000%                             | Log-normal   | Stress test NAV calculation                              |
| Vault count (factory) | 0        | 10,000                             | Linear       | Registry pagination gas analysis                         |

***

## 3. Fork Test Scenarios

Fork tests run against real mainnet state to validate integration with deployed contracts.

### 3.1 Base Mainnet Fork

| Scenario                      | Fork Target                          | What It Tests                                                 |
| ----------------------------- | ------------------------------------ | ------------------------------------------------------------- |
| Vault creation with USDC base | Base mainnet at recent block         | Factory deploys vault, creates V4 pool, registers in registry |
| Deposit with real ERC-8004    | Base mainnet with ERC-8004 deployed  | Identity gating works against real registry                   |
| V4 pool initialization        | Base mainnet with V4 PoolManager     | NAVAwareHook and LaunchFeeHook initialize correctly           |
| Share token swap              | Base mainnet V4                      | Auto-created share pool supports swaps at NAV-aware price     |
| Circuit breaker trigger       | Base mainnet with price manipulation | Oracle divergence triggers circuit breaker correctly          |

### 3.2 Morpho/Aave Integration Fork (Expansion)

| Scenario           | Fork Target                             | What It Tests                                              |
| ------------------ | --------------------------------------- | ---------------------------------------------------------- |
| Adapter allocation | Base mainnet with Morpho Blue           | RecursiveLendingAdapter interacts with real Morpho pools   |
| Force exit         | Base mainnet with active Aave positions | `forceDeallocate()` unwinds positions with correct penalty |

### 3.3 Multi-Agent Simulation Fork

| Scenario                             | What It Tests                                                          |
| ------------------------------------ | ---------------------------------------------------------------------- |
| 5-agent swarm (from 05-local-dev.md) | Concurrent deposits, withdrawals, rebalances with race conditions      |
| Reputation progression               | Agent advances from Unverified to Verified through vault participation |
| am-AMM bid competition               | Multiple agents bid for management rights; transition works correctly  |

***

## 4. Integration Test Matrix

End-to-end tests that exercise complete workflows across contract + SDK + MCP tool boundaries.

| Test Suite             | Operations Tested                                                                  | Phase Gate |
| ---------------------- | ---------------------------------------------------------------------------------- | ---------- |
| Factory lifecycle      | `createVault` -> `isVault` -> `getAllVaults` -> `getVaultsByCreator`               | P1         |
| Deposit/withdraw       | `vault_deposit` -> `vault_get_agent_shares` -> `vault_withdraw` -> verify balances | P1         |
| Rebalance cycle        | `vault_rebalance` -> `vault_get_positions` -> `vault_collect_fees`                 | P1         |
| Identity gating        | Unregistered agent deposit -> expect revert; registered agent -> succeed           | P1         |
| Tier enforcement       | Deposit exceeding tier cap -> expect revert; within cap -> succeed                 | P1         |
| Reputation progression | `vault_enroll_reputation` -> deposit -> hold 30d -> `vault_claim_milestone`        | P4         |
| Proxy announce/cancel  | `proxy_announce` -> wait -> `proxy_cancel` -> verify cancelled                     | P3         |
| Proxy announce/execute | `proxy_announce` -> wait delay -> `proxy_execute` -> verify executed               | P3         |
| Circuit breaker        | Manipulate price -> verify vault pauses -> verify dampening curve                  | P3         |
| Share pool swap        | Create vault -> auto-pool -> swap shares for base asset on V4                      | P1         |

***

## 5. CI Gate Requirements

Each phase gate requires specific test suites to pass before promotion. Test suites are additive -- each phase includes all previous phase requirements.

| Phase               | Required Suites                                                            | Coverage Target                            | Additional Requirements                                                                                              |
| ------------------- | -------------------------------------------------------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |
| P0 (Baseline)       | Linting, type checking                                                     | --                                         | PRD alignment verified                                                                                               |
| P1 (Factory + Core) | INV-1 through INV-11, factory lifecycle, deposit/withdraw, identity gating | 90% line coverage on core contracts        | Fork test: vault creation on Base                                                                                    |
| P2 (MCP + SDK)      | All P1 + MCP tool integration tests, SDK client unit tests                 | 85% line coverage on SDK                   | All 24 core tools have at least 1 integration test                                                                   |
| P3 (Safety + Proxy) | All P2 + INV-12 through INV-14, proxy tests, circuit breaker tests         | 95% line coverage on safety-critical paths | Fork test: circuit breaker trigger; static analysis zero high-severity; formal verification scope document finalized |
| P4 (Reputation)     | All P3 + reputation progression, milestone claiming                        | 90% overall                                | Multi-agent simulation passes                                                                                        |
| P5 (Mainnet)        | All P4 + deployment scripts produce deterministic outputs                  | 95% overall                                | Full fork test suite passes; gas benchmarks within targets; all formal verification targets proven                   |

### CI Pipeline

```
PR -> lint + typecheck -> unit tests -> invariant tests (1000 runs)
     -> slither + aderyn (zero high-severity)
     -> fork tests (Base mainnet) -> integration tests
     -> gas benchmark (fail if >10% regression)
     -> coverage report (fail if below phase threshold)
```

***

## 6. Security-Specific Tests

| Category            | Test                                                         | Rationale                    |
| ------------------- | ------------------------------------------------------------ | ---------------------------- |
| Reentrancy          | Malicious ERC-20 callback during deposit/withdraw            | ReentrancyGuard validation   |
| Inflation attack    | Deposit 1 wei into empty vault                               | D-017 virtual shares offset  |
| Flash loan          | Flash-borrow + deposit + withdraw in same tx                 | D-062 NAV snapshot cadence   |
| Oracle manipulation | Flash-manipulate pool price, attempt deposit at inflated NAV | D-067 no-spot-assumptions    |
| Identity bypass     | Direct call to vault without factory registration            | INV-9, INV-11                |
| Frontrun            | Sandwich vault deposit with share pool trade                 | LaunchFeeHook MEV protection |

***

## 7. Static Analysis

All Solidity packages (`vault`, `agent-proxy`) must pass static analysis with zero high-severity findings before merge. Static analysis runs as part of the `foundry` CI job.

### 7.1 Slither

[Slither](https://github.com/crytic/slither) is the primary static analyzer for Solidity.

**Configuration** (`contracts/slither.config.json` per package):

```json
{
  "filter_paths": ["lib/", "test/", "script/"],
  "exclude_informational": true,
  "exclude_low": false,
  "exclude_medium": false,
  "exclude_high": false,
  "exclude_dependencies": true
}
```

**Severity gating**:

| Severity      | Policy                                                |
| ------------- | ----------------------------------------------------- |
| High          | Zero findings required for merge — no exceptions      |
| Medium        | Must be documented with rationale if accepted         |
| Low           | Reviewed and triaged; fix or document                 |
| Informational | Excluded from CI gate (`exclude_informational: true`) |

**CI integration**: Runs in the `foundry` CI job after `forge test`:

```bash
slither contracts/src/ --config-file contracts/slither.config.json
```

### 7.2 Aderyn

[Aderyn](https://github.com/Cyfrin/aderyn) is a complementary Solidity static analyzer providing additional detection rules.

**Configuration** (`contracts/aderyn.toml` per package):

```toml
[profile.default]
src = "contracts/src/"
exclude = ["lib/", "test/", "script/"]
```

**Severity gating**: Same as Slither — zero high-severity findings required for merge.

**CI integration**: Runs alongside Slither in the `foundry` CI job:

```bash
aderyn contracts/ --config aderyn.toml
```

***

## 8. Formal Verification

Critical contract properties are formally verified using [Certora Prover](https://www.certora.com/) and [Halmos](https://github.com/a]6z/halmos). Formal verification provides mathematical proof that invariants hold for all possible inputs, not just fuzzed samples.

### 8.1 Verification Targets

| Contract              | Property ID | Property                                   | Tool    | Phase |
| --------------------- | ----------- | ------------------------------------------ | ------- | ----- |
| AgentVaultCore        | INV-1       | Share price monotonicity (modulo fees)     | Certora | P5    |
| AgentVaultCore        | INV-2       | No inflation attack                        | Certora | P5    |
| AgentVaultCore        | INV-5       | Total assets conservation                  | Certora | P5    |
| AgentVaultCore        | INV-7       | Deposit-withdraw roundtrip                 | Certora | P5    |
| AgentVaultCore        | INV-8       | No free shares                             | Certora | P5    |
| AgentVaultCore        | —           | ERC-4626 share rounding (bounded)          | Halmos  | P5    |
| FeeModule             | —           | Fee caps never exceeded                    | Certora | P5    |
| FeeModule             | —           | High-water mark monotonicity               | Certora | P5    |
| CircuitBreaker        | INV-12      | Drawdown pause triggers correctly          | Certora | P5    |
| CircuitBreaker        | INV-13      | Continuous dampening (no instant halt)     | Certora | P5    |
| NAVAwareHook          | —           | Pool Favor Property (rounding favors pool) | Certora | P5    |
| DynamicFeeEngine      | —           | Fee monotonicity with increasing sigma     | Certora | P5    |
| AgentProxy            | —           | Delay enforcement (cannot execute before)  | Certora | P5    |
| AgentProxy            | —           | Cancel correctness (cancelled ⊕ executed)  | Certora | P5    |
| StrategyAuctionModule | —           | Rent conservation                          | Certora | P5    |

### 8.2 Spec File Location

All Certora specs live in `contracts/certora/` within each Solidity package:

```
packages/vault/contracts/certora/
├── AgentVaultCore.spec
├── FeeModule.spec
├── NAVAwareHook.spec
├── DynamicFeeEngine.spec
├── CircuitBreaker.spec
└── StrategyAuctionModule.spec

packages/agent-proxy/contracts/certora/
└── AgentProxy.spec
```

### 8.3 Phase Gating

| Phase | Requirement                                                                                                                |
| ----- | -------------------------------------------------------------------------------------------------------------------------- |
| P3    | Formal verification scope document finalized; spec skeletons created                                                       |
| P5    | All verification targets proven; Halmos bounded tests at production depth; formal verification report prepared for auditor |
