> 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/concepts/architecture.md).

# Architecture

Gotts is structured as a layered system where user intent flows through skills, agents, and protocol-level tools before reaching the blockchain.

## System Layers

```
User / Agent Intent
       |
       v
Skills (user-facing interface)
       |  Parse intent, validate, delegate
       v
Agents (autonomous execution)
       |  Multi-step workflows, safety delegation
       v
MCP Server (protocol access + vault ops)
       |  On-chain reads/writes, safety middleware, vault tools
       v
Agent Proxy (optional, reactive defense)
       |  announce -> delay window -> execute (cancellable)
       v
Uniswap Protocol (V2, V3, V4, UniswapX) + ERC-4626 Vaults + ERC-8004 Identity
```

**Skills** are the user-facing interface. They parse natural language intent, validate parameters, and delegate to one or more agents. Each skill maps to a slash command (e.g., `/execute-swap`, `/deposit-vault`).

**Agents** execute multi-step workflows autonomously. They coordinate with other agents via a strict delegation DAG (no cycles allowed). Every write operation routes through the `safety-guardian` agent before broadcast.

**MCP Server** (Gotts Safe) provides 154 tools for direct protocol interaction: data queries, swap execution, liquidity management, vault operations, and identity management. Tools are organized into profiles for selective activation.

**Agent Proxy** adds a mandatory time delay between transaction authorization and execution. A monitoring bot can cancel suspicious transactions during the delay window.

## Package Map

The monorepo contains 14 workspace packages across three layers:

### Runtime Packages

| Package                | npm Name                | Type      | Description                                |
| ---------------------- | ----------------------- | --------- | ------------------------------------------ |
| `packages/safe`        | `@gotts.ai/safe`        | Published | Gotts Safe: unified MCP server (154 tools) |
| `packages/testnet`     | `@gotts.ai/testnet`     | Published | Generic EVM test toolkit                   |
| `packages/vault`       | `@gotts.ai/vault`       | Published | Gotts Vaults: ERC-4626 + V4 hooks + SDK    |
| `packages/agent-proxy` | `@gotts.ai/agent-proxy` | Published | Time-delayed proxy contracts + SDK         |
| `packages/devenv`      | `@gotts.ai/devenv`      | Internal  | Local Uniswap development environment      |
| `packages/portal`      | `@gotts.ai/portal`      | Internal  | Agent management dashboard                 |

### Primitive Packages

| Package               | npm Name               | Type           | Description                                            |
| --------------------- | ---------------------- | -------------- | ------------------------------------------------------ |
| `packages/core`       | `@gotts.ai/core`       | Published      | Config I/O, error hierarchy, constants                 |
| `packages/chain`      | `@gotts.ai/chain`      | Internal       | 13-chain registry, ETH math, address utils, RPC client |
| `packages/crypto`     | `@gotts.ai/crypto`     | Internal       | P-256 key generation, signing, DER encoding            |
| `packages/policy`     | `@gotts.ai/policy`     | Internal       | Privy policy DSL, builders, validators                 |
| `packages/wallet`     | `@gotts.ai/wallet`     | Published      | GottsWallet, EIP-1193 provider, agent registration     |
| `packages/test-utils` | `@gotts.ai/test-utils` | Internal (dev) | MSW test handlers and fixtures                         |

### Configuration Packages

| Package                      | npm Name                      | Type     | Description                     |
| ---------------------------- | ----------------------------- | -------- | ------------------------------- |
| `packages/typescript-config` | `@gotts.ai/typescript-config` | Internal | Shared TypeScript configuration |
| `packages/eslint-config`     | `@gotts.ai/eslint-config`     | Internal | Shared ESLint configuration     |

## Primitive Layer

The primitive packages form a foundational layer below `@gotts.ai/safe`, `@gotts.ai/vault`, and `@gotts.ai/portal`. They provide shared infrastructure for configuration, cryptography, blockchain interaction, and wallet management.

```
@gotts.ai/safe   @gotts.ai/vault   @gotts.ai/portal
       \               |               /
        \              |              /
         v             v             v
            @gotts.ai/wallet (Published)
           /       |        \
          v        v         v
  @gotts.ai/   @gotts.ai/   @gotts.ai/
    policy       crypto        core (Published)
      |                          |
      v                          |
  @gotts.ai/chain                |
      \                         /
       --------- shared -------
```

* **`@gotts.ai/core`** — Config I/O (`~/.gotts/config.json`), error hierarchy (`GottsError`, `ConfigError`, `AuthError`), Privy API constants. Published via tsup.
* **`@gotts.ai/chain`** — 13-chain registry (11 Uniswap chains + Sepolia + Anvil), ETH math (pure BigInt), address validation, `RpcClient`. Zero external deps.
* **`@gotts.ai/crypto`** — P-256 keygen via `@noble/curves`, DER encoding (PKCS8/SPKI), SHA-256 signing/verification, OS keychain storage. Zero workspace deps for auditability.
* **`@gotts.ai/policy`** — Privy signing policy DSL: `PolicyBuilder` fluent API, `buildSendOnlyPolicy` convenience, validators and address resolvers.
* **`@gotts.ai/wallet`** — `GottsWallet` (Privy + local modes), EIP-1193 provider bridge, Privy API client, `registerAgent` with three-tier ERC-8004 fallback. Published via tsup.
* **`@gotts.ai/test-utils`** — MSW-based test server factory with handlers for Privy, RPC, Portal, Agent0, and faucet APIs.

## MCP Server Architecture

Gotts Safe (`@gotts.ai/safe`) is a Model Context Protocol server that exposes Uniswap protocol access as MCP tools. It communicates over stdio (default) or HTTP and is designed to run as a subprocess of any MCP-compatible client (Claude Desktop, Cursor, custom agents).

### Startup Flow

```
CLI args parsed (--health flag check)
       |
       v
loadConfig(process.env)        Zod schema validates all GOTTS_* env vars
       |                       Cross-field validation (wallet for write profiles, etc.)
       v
initLogger(level, format)     Logger writes to stderr (stdout = MCP protocol)
       |
       v
McpServer created             @modelcontextprotocol/sdk server instance
       |
       v
registerTools(server, profiles)  Profile inheritance resolved, tool registrars called
       |
       v
StdioServerTransport.connect()   Server ready for MCP client connection
```

### Health Check (`--health`)

The `--health` flag runs a connectivity check against configured chains:

```bash
# Check all chains (uses public RPCs by default)
pnpm start -- --health

# Check with custom RPCs
GOTTS_RPC_ETHEREUM=https://... pnpm start -- --health
```

Exit codes: `0` (all healthy), `1` (some degraded), `2` (no RPC reachable).

### Provider Architecture

**Chain Provider** — Creates and caches a viem `PublicClient` per chain. Supports custom RPC URLs via `GOTTS_RPC_*` env vars, falling back to public RPCs. All 11 Uniswap-deployed chains are supported.

**Subgraph Provider** — Queries The Graph subgraphs (V2, V3, V4, ERC-8004) with automatic retry on rate limits (429) and service unavailability (503). Uses exponential backoff: 1s, 2s, 4s.

### Error Handling

All errors extend `GottsError` with structured fields:

```typescript
{
  code: "DATA_SUBGRAPH_ERROR",   // Machine-readable error code
  category: "data",               // Error category (7 types)
  message: "Subgraph query failed after 3 retries",
  suggestion: "Check subgraph status or try again later",
  retryable: true,
  retryAfterMs: 5000
}
```

Seven error categories: `safety`, `validation`, `execution`, `data`, `wallet`, `routing`, `config`. Each has a dedicated subclass (`SafetyError`, `ValidationError`, etc.) that auto-sets the category.

### Cache System

In-memory LRU cache with TTL expiry. Predefined TTL tiers:

| Tier             | TTL  | Use Case                   |
| ---------------- | ---- | -------------------------- |
| `POOL_STATE`     | 15s  | Prices, pool data          |
| `METADATA`       | 5min | Pool metadata, token lists |
| `TOKEN_METADATA` | 24h  | Name, symbol, decimals     |
| `OHLCV`          | 1h   | Historical candles         |
| `NONE`           | 0    | Simulations, nonces        |

## Agent Delegation Architecture

Agents coordinate via a strict delegation DAG (directed acyclic graph). This architecture ensures predictable execution flows, prevents infinite loops, and enables independent safety verification.

### DAG Constraints

* **Acyclic**: No cycles permitted. Agent A → B → A is impossible.
* **Max depth 3**: No delegation chain longer than A → B → C → terminal (e.g., competition-participant → token-deployer → liquidity-manager → safety-guardian).
* **No self-delegation**: An agent cannot delegate to itself.
* **CI-enforced**: `validate-dag.ts` runs cycle detection, terminal node enforcement, tool reference validation, and depth checks in every CI run.

### Terminal Nodes (8 Agents)

Terminal agents are leaf nodes that never delegate to other agents. They produce results using only MCP tools and must evaluate independently:

| Terminal Agent       | Category       | Why Terminal                                         |
| -------------------- | -------------- | ---------------------------------------------------- |
| `safety-guardian`    | Infrastructure | Must be independent — cannot be influenced by others |
| `risk-assessor`      | Strategy       | Independent evaluation without requesting agent bias |
| `wallet-provisioner` | Infrastructure | Setup-only — no execution delegation needed          |
| `pnl-analyst`        | Research       | Computation-only — reads data, produces reports      |
| `pool-researcher`    | Research       | Research-only — analyzes pools, never executes       |
| `token-analyst`      | Research       | Research-only — evaluates tokens, never trades       |
| `identity-verifier`  | Economy        | Verification-only — checks identity registries       |
| `position-monitor`   | Real-Time      | Alert-only — monitors positions, never transacts     |

### Safety-First Delegation

Every write operation routes through `safety-guardian` before broadcast. All three execution agents (trade-executor, liquidity-manager, cross-chain-executor) have mandatory delegation to safety-guardian. The safety-guardian:

* Enforces spending limits ($10K per-tx, $50K per-session, $100K per-day)
* Simulates transactions before approval
* Decodes and inspects calldata
* Provides APPROVE / WARNING / VETO / EMERGENCY HALT decisions
* Cannot approve transactions it cannot fully decode

### Composition Patterns

Agents compose into multi-step workflows along the DAG. Ten key patterns are verified in integration tests:

1. **Research-to-Trade**: opportunity-scanner → pool-researcher → risk-assessor → trade-executor → safety-guardian
2. **Autonomous LP**: lp-strategist → pool-researcher → liquidity-manager → safety-guardian
3. **Token Launch**: token-deployer → liquidity-manager → safety-guardian
4. **Real-Time Response**: market-monitor → risk-assessor → liquidity-manager → safety-guardian
5. **Yield Rotation**: yield-scout → risk-assessor → trade-executor → safety-guardian

Self-contained agents (hook-builder, integration-architect, integration-advisor) operate independently — they use MCP tools and filesystem tools but never delegate to other agents.

## Design Philosophy

**Safety-first.** Every write operation passes through simulation, validation, and safety checks before reaching the blockchain. The 15-layer defense architecture ensures that no single point of failure can result in loss of funds.

**Composable tools.** Each MCP tool does one thing well. Complex workflows are composed by agents orchestrating multiple tool calls, not by monolithic tools that try to do everything.

**Profile-based activation.** Operators choose which tool categories to expose via the `TOOL_PROFILE` environment variable. A data-only deployment loads only read tools. A vault deployment adds vault management tools. This minimizes attack surface.

**On-chain verification.** Agents independently verify all inputs via MCP tools against on-chain state. No transitive trust: agent A never trusts data from agent B without independent on-chain confirmation.
