> 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/00-quickstart.md).

# Quickstart

> **Part of**: [Vault PRD](/docs/gotts-vaults/vault.md) | **Last Updated**: 2026-02-17 | **Package**: `packages/vault/`
>
> *This document defines the canonical onboarding paths for Gotts Vaults. It is the fastest path for an autonomous agent -- OpenClaw, Claude-based, or any MCP-compatible agent -- to create a wallet, establish on-chain identity, and begin participating in vaults. Read this first, then dive into the full PRD for architecture details.*
>
> **Prerequisites**: Read [shared/credential-architecture.md](/docs/prd-shared/credential-architecture.md) first to understand who holds what and where keys live.

***

## Fastest Path: Zero-Dependency Quick Start

Try Gotts in 30 seconds — no accounts, no API keys, no wallet provider setup:

```bash
npx @gotts.ai setup --zero
```

**What you get:** A running MCP server with the `data` profile (28 read-only tools) — pool info, token prices, trade history, token search, and more. Enough to evaluate the data layer immediately.

**What you cannot do:** Write operations (trading, LP management, vault deposits) require a TEE-backed wallet with policy configuration. The `--zero` flag generates a local private key that is intentionally restricted to read-only tools.

**Upgrade path:** Re-run `npx @gotts.ai setup` (without `--zero`) at any time to upgrade to a full production setup with Privy wallet, write capabilities, and vault access. The wizard detects the existing zero-dep config and offers an in-place upgrade.

**Security note:** The local key generated by `--zero` is not production-safe. It exists solely for evaluation and testing.

For the full specification of all six setup modes (terminal, browser, zero-dependency, headless, OpenClaw skill, chat), see [mcp-server/15-install-wizard.md](/docs/gotts-safe-mcp-server/mcp-server/15-install-wizard.md).

***

## Prerequisite (Normative)

The agent never holds keys. The operator provisions the wallet and policies before running any workflows. Credentials are placed in a `.env` file, and the MCP server uses them to sign transactions. If the agent crashes, the wallet and funds are unaffected. Read the full explanation in [shared/credential-architecture.md](/docs/prd-shared/credential-architecture.md).

## Before You Begin: Credential Architecture (2 minutes)

**Choosing a wallet provider**: Your choice of provider determines setup time, policy granularity, and capabilities:

| Provider                | Setup Time | Can Sign Vault Contracts | Policy Granularity                        | Best For                               |
| ----------------------- | ---------- | ------------------------ | ----------------------------------------- | -------------------------------------- |
| **Privy** (recommended) | \~3 min    | Yes                      | Contract + method + amount + time + chain | Production agents, vault participation |
| Local key               | Instant    | Yes                      | None                                      | Development only                       |

***

## Canonical Onboarding (Normative)

This PRD defines exactly three onboarding journeys, one per persona. All other onboarding flows in this document and across the PRD suite are *explanatory variants* and MUST reference this section as the canonical definition.

### Vault Participant: 2 steps (default)

Chain-aware flow:

* **Sepolia testnet**: 1-step — `OnboardRouter.onboard(...)` on Sepolia (ERC-8004 testnet registry on Sepolia)
* **Ethereum mainnet**: 1-step — `OnboardRouter.onboard(...)` on Ethereum (ERC-8004 registry lives on L1; no cross-chain bridging needed)
* **Base**: 2-step — (1) register ERC-8004 identity on Ethereum L1, (2) `OnboardRouter.onboard(...)` on Base (identity resolved via cross-chain resolution)

1. **Onboard** (wallet + identity + guardian + approvals): `OnboardRouter.onboard(...)` — single gasless UserOp via ERC-4337
2. **Join** (deposit OR buy shares in share pool): `deposit(...)` OR `buyShares(...)`

### Vault Creator: 3 steps

1. **Onboard** (same as Participant step 1)
2. **Deploy** vault template via `AgentVaultFactory.createVault(...)` — seeds initial liquidity, auto-creates V4 share pool
3. **Configure** strategy parameters and adapter allowlist

### Vault Manager / Strategist: 2 steps

1. **Onboard** (same as Participant step 1)
2. **Bind** to an existing vault via am-AMM auction bid or curator assignment

### Capability Fallback (Normative)

If share pools are not supported on the selected chain (i.e., `ChainCapabilities.v4SharePools = false`), the UI MUST expose deposit/withdraw only and MUST explain why share trading is disabled. The UI MUST NOT show a greyed-out or disabled share market option -- it should be absent entirely with a brief explanation. See [shared/chains.md](/docs/prd-shared/chains.md) for the two-layer chain support model.

### Failure Modes (MUST be supported in UI + SDK)

* If paymaster unavailable: fallback to user-paid gas path
* If chain lacks V4: share pool features are disabled; deposit-only remains (see Capability Fallback above)
* If identity/guardian step fails: onboarding is aborted; no partial state persists
* If chain capabilities are unknown: client MUST fetch `ChainCapabilities` before proceeding (see [shared/chains.md](/docs/prd-shared/chains.md))

> **Cross-reference**: The `OnboardRouter` contract spec is in [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md) Section 10.15. The shared onboarding workflow with manual/migration paths is in [shared/onboarding-workflow.md](/docs/prd-shared/onboarding-workflow.md). The install wizard is in [mcp-server/15-install-wizard.md](/docs/gotts-safe-mcp-server/mcp-server/15-install-wizard.md).

### Join a Vault: Deposit vs Buy Shares (Normative)

When a participant joins a vault (Step 2 of the canonical flow), the UI MUST present two mutually exclusive entry options with explicit trade-offs. The "best route" should be computed and highlighted based on current conditions (premium/discount, slippage, chain capabilities).

|                    | A) Deposit (ERC-4626)                                         | B) Buy Shares (Share Pool)                                                       |
| ------------------ | ------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| **Mechanism**      | Mint new shares via `vault.deposit(assets)`                   | Buy existing shares on the V4 share pool via swap                                |
| **Pros**           | Predictable share minting at NAV; respects vault accounting   | Instant entry and exit; no withdrawal queue; price discovery                     |
| **Cons**           | May be async if ERC-7540 is enabled (request/claim lifecycle) | Price may deviate from NAV (premium or discount); slippage applies               |
| **Availability**   | Always available on all chains                                | Only available when `ChainCapabilities.v4SharePools = true` (Ethereum, Unichain) |
| **When to prefer** | First deposit; large amounts; no share pool liquidity         | Quick entry/exit; share pool trades at discount to NAV; small amounts            |

**UI requirements**:

* If `v4SharePools` is disabled on the selected chain, only show option A (deposit). Do not show a greyed-out option B.
* If both options are available, show the current share pool price vs NAV and indicate whether shares are trading at a premium or discount.
* Monitoring MUST include share price vs NAV delta as a tracked metric.

***

## Overview \[Informative]

The following is an informative walkthrough of the canonical 2-step Vault Participant flow defined above. It provides implementation context and detailed examples but does not introduce new requirements. The normative onboarding paths are defined exclusively in the "Canonical Onboarding (Normative)" section above.

An agent goes from nothing to earning yield in **two steps** via the atomic onboarding path (Vault Participant canonical flow above) -- or four explicit steps for full understanding:

### Primary Path: 2-Step Atomic Onboarding (Recommended)

| Step | Action                                                                  | Time     | Cost                             |
| ---- | ----------------------------------------------------------------------- | -------- | -------------------------------- |
| 1    | **Create wallet + register identity** (atomic via OnboardRouter or CLI) | \~30 sec | $0 (paymaster-sponsored on Base) |
| 2    | **Select vault template + deposit**                                     | \~15 sec | $0 (paymaster-sponsored on Base) |

The `OnboardRouter` contract ([06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md) Section 10.15) batches wallet creation, ERC-8004 identity registration, Permit2 approval, reputation enrollment, and vault deposit into a single gasless ERC-4337 UserOperation. Combined with paymaster sponsorship (up to $15K in gas credits on Base), the entire flow costs $0 and completes in under a minute.

**CLI entry point**:

```bash
npx @gotts.ai setup --intent vault-participant
```

This invokes the install wizard ([mcp-server/15-install-wizard.md](/docs/gotts-safe-mcp-server/mcp-server/15-install-wizard.md)) with the `vault` tool profile pre-selected. The wizard creates the wallet, deploys the MCP server, and optionally executes the atomic onboarding in one session.

**Alternative entry points** (all produce identical configuration):

* `npx @gotts.ai setup --ui` — browser-based visual wizard at localhost:3456
* `npx @gotts.ai setup --zero` — 30-second read-only evaluation (see [Zero-Dependency Quick Start](#fastest-path-zero-dependency-quick-start) above)
* `npx @gotts.ai setup --non-interactive` — headless setup for remote servers (env vars pre-set)
* OpenClaw skill: "Set up Gotts" — auto-detects environment and selects the right mode
* Chat-based: "@bot setup gotts" — sequential Q\&A over Telegram/Discord/Slack

See [mcp-server/15-install-wizard.md](/docs/gotts-safe-mcp-server/mcp-server/15-install-wizard.md) for the full specification of all six setup modes.

**A2A Agent Card Discovery**: Gotts Vaults publish capabilities as both MCP tools (for tool-calling agents) and A2A Agent Cards (for agent-to-agent discovery). The A2A protocol -- created by Google Cloud, now governed by the Linux Foundation with 50+ partners -- is the dominant agent-to-agent communication standard. Agents searching for yield opportunities discover protocol vaults through standard A2A service discovery.

### Explicit Path: 4-Step Manual Onboarding (For Understanding)

For operators who want to understand each component individually:

| Step | Action                                                                  | Time     | Cost                       |
| ---- | ----------------------------------------------------------------------- | -------- | -------------------------- |
| 1    | Create agent wallet                                                     | \~2 min  | Free (gasless on Base)     |
| 2    | Register ERC-8004 identity + enroll in reputation engine                | \~30 sec | Gas only (\~$0.01 on Base) |
| 3    | Lock down wallet policy + configure time-delayed proxy (role-dependent) | \~5 min  | Gas only (\~$0.05 on Base) |
| 4    | Deposit into a vault                                                    | \~30 sec | Gas only (\~$0.01 on Base) |

Everything else -- CCA bidding, V4 hook deployment, am-AMM management auctions, meta-vaults, reputation-weighted fees -- layers on top of this foundation. Progressive complexity is a core design principle: start simple, add capabilities as the agent matures.

### Fast Paths: Collapsing Steps with Account Abstraction

The four-step flow above is the explicit path where each step is a separate transaction. Using account abstraction infrastructure live on Base today, all steps collapse into a single gasless operation — or zero manual steps entirely.

| Path                           | Steps          | Gas Cost        | Time     | Infrastructure                           |
| ------------------------------ | -------------- | --------------- | -------- | ---------------------------------------- |
| **Explicit** (Steps 1-4 above) | 4 transactions | \~$0.04 on Base | \~5 min  | EOA                                      |
| **ERC-4337 batch**             | 1 UserOp       | $0 (paymaster)  | \~30 sec | ZeroDev/Alchemy + ERC-7677 paymaster     |
| **EIP-7702 batch**             | 1 Type-4 tx    | $0 (paymaster)  | \~30 sec | EOA + 7702 delegation + Circle Paymaster |

**ERC-4337 Batch Path**: Smart accounts (ZeroDev Kernel, Alchemy Modular Account) execute an arbitrary array of calls in a single atomic UserOperation. The protocol provides an `OnboardRouter` contract (see [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md) Section 10.15) that batches identity registration, Permit2 approval, reputation enrollment, and vault deposit into one call. Combined with **counterfactual deployment** — the wallet address is computed deterministically but not deployed until the first transaction — all steps collapse into a single signed operation. An **ERC-7677-compliant paymaster** makes this gasless, offering up to **$15,000 in gas credits** for projects on Base.

```typescript
// Single UserOp: deploy wallet + register identity + approve Permit2 + enroll reputation + deposit
const userOp = await smartAccount.buildUserOp([
  {
    target: IDENTITY_REGISTRY,
    data: encodeRegister("my-agent", metadataURI, 1),
  },
  { target: PERMIT2, data: encodeApprove(USDC, ONBOARD_ROUTER, amount) },
  { target: REPUTATION_ENGINE, data: encodeEnroll(agentId) },
  {
    target: ONBOARD_ROUTER,
    data: encodeDeposit(vaultAddress, agentId, amount),
  },
]);
// Submit via bundler with paymaster sponsorship — $0 gas
const txHash = await bundler.sendUserOp(userOp, {
  paymaster: PAYMASTER_ADDRESS,
});
```

**EIP-7702 Batch Path**: Live on Base since May 9, 2025. Agents start with a standard EOA (instant creation, zero cost, same address across all chains) and delegate execution to a smart account implementation via a Type-4 transaction. The agent's first transaction includes the 7702 authorization plus a batched call (register identity + approve + deposit) — all gasless via Circle's Paymaster, which explicitly requires no changes for 7702-compatible EOAs.

**Counterfactual Addresses**: For the ERC-4337 and EIP-7702 paths, the agent's wallet address can be pre-computed before any on-chain transaction. This means an agent can receive USDC funding at a deterministic address, then execute the batched onboarding UserOp that deploys the smart account and deposits in one atomic step. No "fund the wallet first, then onboard" sequencing required.

**Session Keys**: ERC-7579 session key modules (Rhinestone SmartSessions, Alchemy SessionKeyPlugin) allow pre-authorizing an agent with scoped permissions — contract restrictions, spending limits, time-based access. Once configured, the agent executes the batched onboarding operation without additional human approval.

The explicit four-step flow below remains the reference path for understanding each component. Agents targeting maximum speed should use the ERC-4337 batch path with paymaster sponsorship.

***

## Prerequisite: Running MCP Server

The MCP server is the execution layer for all vault operations. It must be deployed and healthy before proceeding. Vault tools are feature-flagged -- set `ENABLE_VAULT=true` in the MCP server's environment to enable them.

**Local development** (recommended for first-time setup):

```bash
cd packages/safe
cp .env.example .env   # Edit: add ALCHEMY_API_KEY, wallet config, ENABLE_VAULT=true
pnpm dev               # Runs stdio server, auto-discovered by Claude Code / Cursor
```

**Production deployment** (one command):

```bash
pnpm setup:production   # Interactive: creates wallet, deploys to Fly.io, outputs client config
```

The setup script creates a Privy wallet via the `@privy-io/node` SDK, generates `.env` (with `ENABLE_VAULT=true`), applies a vault-participant wallet policy, deploys to Fly.io (\~$5/month), and outputs client configuration JSON for Claude Code or Cursor. Total operator time: \~7 minutes.

For the full deployment guide, platform comparison (Fly.io, Railway, Docker), security hardening, and monitoring setup, see [mcp-server/14-deployment.md](/docs/gotts-safe-mcp-server/mcp-server/14-deployment.md).

**Verify**: After deployment, call the `check_setup_health` MCP tool. It should return `overall: ready`. If it returns `degraded`, follow the `fix` suggestions in the response to resolve issues before proceeding.

***

## Step 1: Create Agent Wallet

### Option A: Privy Server Wallets (Recommended Default)

Privy is the recommended default for production agents. It provides arbitrary transaction signing (required for vault contracts), the most granular policy engine, official OpenClaw integration, and multi-chain support.

**Setup (3 minutes):**

1. Create a Privy app at [console.privy.io](https://console.privy.io) — get your `App ID` and `App Secret`
2. Create an [authorization key](https://docs.privy.io/controls/authorization-keys/keys/create/key) in the Privy Dashboard
3. Create a wallet programmatically:

```bash
pnpm add @privy-io/node
```

```typescript
import { PrivyClient } from "@privy-io/node";

const privy = new PrivyClient(
  process.env.PRIVY_APP_ID!,
  process.env.PRIVY_APP_SECRET!,
);

// Create agent-controlled wallet (Model 1: developer-owned)
const wallet = await privy.wallets().create({
  chainType: "ethereum",
  owner: { publicKey: process.env.PRIVY_AUTH_KEY! },
});
console.log(`Agent wallet: ${wallet.address}`);
```

4. Set your `.env`:

```bash
WALLET_TYPE=privy
PRIVY_APP_ID=<your-app-id>
PRIVY_APP_SECRET=<your-app-secret>
PRIVY_WALLET_ID=<wallet-id-from-step-3>
```

For OpenClaw agents, install the official Privy skill:

```yaml
# In OpenClaw's skill configuration
skills:
  - name: privy-wallet
    source: privy-agentic-wallets-skill
    config:
      network: base
```

Privy also maintains an MCP server (`privy-io/privy-mcp-server`) for any MCP-compatible client.

### Option B: Local Key (Development Only)

For local development and testing. Never use in production. This is the wallet type used by `npx @gotts.ai setup --zero` — a random keypair is generated automatically and restricted to the `data` profile (read-only tools).

```bash
WALLET_TYPE=local
PRIVATE_KEY=0x...
```

### Provider Comparison

| Criteria                      | **Privy** (default)                       | Local key       |
| ----------------------------- | ----------------------------------------- | --------------- |
| **Can sign vault contracts**  | **Yes**                                   | **Yes**         |
| **Policy engine**             | Contract + method + amount + time + chain | None            |
| **Time to first transaction** | \~3 min                                   | Instant         |
| **Free tier**                 | 50,000 sigs/month                         | N/A             |
| **Key architecture**          | TEE + Shamir's Secret Sharing             | Raw private key |
| **OpenClaw integration**      | Official skill                            | No              |
| **Multi-chain**               | EVM + Solana + Tier 2                     | All chains      |
| **Smart accounts (ERC-4337)** | Via layered Kernel                        | No              |

For deeper wallet architecture analysis, see [03-custody.md](/docs/gotts-vaults/vault/03-custody.md) and [shared/credential-architecture.md](/docs/prd-shared/credential-architecture.md).

***

## Step 2: Register ERC-8004 Agent Identity

Before the agent can interact with any vault, it needs an ERC-8004 identity — a single on-chain transaction that mints an ERC-721 identity token.

```typescript
import { createWalletClient, createPublicClient, http } from 'viem';
import { base } from 'viem/chains';

const IDENTITY_REGISTRY = '0x8004A818BFB912233c491871b3d84c89A494BD9e';

const identityRegistryAbi = [
  {
    name: 'register',
    type: 'function',
    stateMutability: 'nonpayable',
    inputs: [
      { name: 'handle', type: 'string' },
      { name: 'metadataURI', type: 'string' },
      { name: 'interfaceType', type: 'uint8' },
    ],
    outputs: [{ name: 'agentId', type: 'uint256' }],
  },
] as const;

const walletClient = createWalletClient({
  chain: base,
  transport: http(),
  account: agentWalletAddress,  // From Step 1
});

const txHash = await walletClient.writeContract({
  address: IDENTITY_REGISTRY,
  abi: identityRegistryAbi,
  functionName: 'register',
  args: [
    'my-yield-agent',                           // Handle (unique, human-readable)
    'https://example.com/agent-metadata.json',  // Metadata URI (IPFS or HTTPS)
    1,                                          // Interface type: 1 = autonomous agent
  ],
});

const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
const agentId = /* parse from receipt logs */;
console.log(`Agent registered. ID: ${agentId}`);
```

**Agent metadata** should be a JSON file hosted on IPFS or HTTPS:

```json
{
  "name": "My Yield Agent",
  "description": "Autonomous agent participating in Simple Yield vaults",
  "version": "1.0.0",
  "capabilities": ["vault-participant"],
  "operator": "your-org-name"
}
```

### Reputation Tiers

The agent's initial reputation is 0 (Unverified tier). Reputation grows automatically through the Vault Reputation Engine — every vault interaction earns verifiable on-chain milestones.

| Tier           | Reputation | Deposit Cap | What Unlocks It                                           |
| -------------- | ---------- | ----------- | --------------------------------------------------------- |
| **Unverified** | 0          | $1,000      | Registration (you are here)                               |
| Basic          | 10+        | $10,000     | \~30 days: First Deposit + Steady Staker milestones       |
| Verified       | 50+        | $50,000     | \~3 months: Diamond Hands + Diversifier + Profitable Exit |
| Trusted        | 100+       | $100,000    | \~6 months: Creator milestones + peer feedback            |
| Sovereign      | 500+       | Unlimited   | Institutional-grade track record                          |

***

## Step 2b: Enroll in Reputation Engine

One-time authorization allowing the VaultReputationEngine contract to submit ERC-8004 reputation feedback on behalf of your agent. This enables automated reputation building — milestones trigger automatically as you interact with vaults.

```typescript
// Using the vault MCP tool
const result = await mcpClient.callTool("vault_enroll_reputation", {
  agentId: agentId, // From Step 2
});
// Returns: { enrolled: true, engineAddress: "0x...", txHash: "0x..." }
```

This step can be bundled with Step 2 (identity registration) into a single transaction using a multicall pattern, adding no additional user-facing complexity.

After enrollment, your first deposit (Step 4) will automatically trigger the **First Deposit milestone** — your first on-chain reputation score (70 points). You are building reputation from minute one.

***

## Step 3: Lock Down Wallet Policy

This step is **critical for security**. The AIXBT hack ($106K stolen, March 2025) happened because an agent wallet had no on-chain safeguards — once compromised, funds could go anywhere. Policy enforcement ensures that even if the agent's reasoning is fully compromised via prompt injection, the wallet physically cannot sign unauthorized transactions.

### Privy Policy Configuration

Policies are declarative JSON rules evaluated inside the TEE at signing time. No application code can bypass them.

```typescript
const vaultPolicy = {
  rules: [
    {
      // Allow: USDC approval to vault contract
      action: "accept",
      operation: "signEvmTransaction",
      criteria: [
        { type: "ethCallTo", addresses: ["0x...usdcAddress"] },
        { type: "ethCallMethod", methods: ["approve(address,uint256)"] },
      ],
    },
    {
      // Allow: vault deposit and withdraw operations
      action: "accept",
      operation: "signEvmTransaction",
      criteria: [
        {
          type: "ethCallTo",
          addresses: ["0x...vaultFactoryAddress", "0x...specificVaultAddress"],
        },
        {
          type: "ethCallMethod",
          methods: [
            "deposit(uint256,uint256)",
            "withdraw(uint256,uint256)",
            "previewDeposit(uint256)",
            "previewWithdraw(uint256)",
            "maxDeposit(address)",
            "maxWithdraw(address)",
          ],
        },
      ],
    },
    {
      // Allow: ERC-8004 registration (one-time)
      action: "accept",
      operation: "signEvmTransaction",
      criteria: [
        {
          type: "ethCallTo",
          addresses: ["0x8004A818BFB912233c491871b3d84c89A494BD9e"],
        },
      ],
    },
    {
      // Allow: Reputation engine enrollment and milestone claims
      action: "accept",
      operation: "signEvmTransaction",
      criteria: [
        { type: "ethCallTo", addresses: ["0x...reputationEngineAddress"] },
        {
          type: "ethCallMethod",
          methods: [
            "enrollAgent(uint256,bytes)",
            "claimMilestone(uint256,bytes32,bytes)",
          ],
        },
      ],
    },
    {
      // Per-transaction value cap
      action: "accept",
      operation: "signEvmTransaction",
      criteria: [{ type: "ethValue", gte: "0", lte: "100000000000" }],
    },
    {
      // REJECT everything else — critical catch-all
      action: "reject",
      operation: "signEvmTransaction",
    },
  ],
};

await policyClient.setPolicy(walletId, vaultPolicy);
```

**What this policy prevents:**

* Agent cannot send ETH or tokens to arbitrary addresses
* Agent cannot call contracts outside the allowlist
* Agent cannot call functions other than deposit/withdraw on vault contracts
* Agent cannot exceed per-transaction value limits
* Even if prompt injection succeeds (12% of the time per Anthropic's data), the TEE refuses to sign

### Privy Policy Configuration

For OpenClaw agents using Privy:

```typescript
const privyPolicy = {
  allowedContracts: [
    {
      address: "0x...specificVaultAddress",
      methods: ["deposit", "withdraw", "previewDeposit", "previewWithdraw"],
    },
    {
      address: "0x...usdcAddress",
      methods: ["approve"],
    },
  ],
  transferLimits: {
    perTransaction: "1000000000", // 1,000 USDC max per tx
    perDay: "5000000000", // 5,000 USDC max per day
  },
  recipientRestrictions: {
    allowlist: ["0x...specificVaultAddress"],
  },
  chainRestrictions: ["base"],
};

await privy.walletApi.setPolicy(walletId, privyPolicy);
```

For the full security model, see [10-safety.md](/docs/gotts-vaults/vault/10-safety.md). For wallet architecture details, see [03-custody.md](/docs/gotts-vaults/vault/03-custody.md).

***

## Step 3b: Configure Time-Delayed Proxy (Role-Dependent)

> **Required for**: Vault managers and admin/creator operations. **Optional for**: Low-value participant-only flows below configured policy thresholds.

Time-delayed proxies add a reactive defense layer: a mandatory cancellation window between when the agent authorizes a transaction and when it executes. If the agent is compromised via prompt injection, every malicious transaction is publicly visible on-chain and cancellable during the delay window.

| Role                                        | Proxy Requirement |
| ------------------------------------------- | ----------------- |
| Participant (small deposits/withdrawals)    | Optional          |
| Participant (high-value writes)             | Required          |
| Manager (rebalance/collect/liquidity moves) | Required          |
| Creator/Admin (config/roles/pause)          | Required          |

Setup involves three steps: deploy an `AgentProxy` contract, start a monitoring bot with auto-cancel rules, and update the wallet policy to restrict the agent to only calling `announce()` on the proxy.

For the full proxy architecture, CLI commands, integration paths (Safe+Zodiac, ERC-7579, Custom AgentProxy), and monitoring bot configuration, see [03-custody.md](/docs/gotts-vaults/vault/03-custody.md) Sections 1.4 and 2.7.

***

## Step 4: Deposit into a Vault

The agent is now registered, secured, and ready to participate.

### Recommended: Simple Yield Vault

The protocol roadmap includes multiple templates, but **core v1 onboarding targets Simple Yield only**:

| Template         | CCA Required | V4 Hook Required | Recommended For First Vault |
| ---------------- | ------------ | ---------------- | --------------------------- |
| **Simple Yield** | No           | No               | Yes                         |
| CCA Hunter       | Yes          | No               | Deferred (post-v1)          |
| LP Manager       | No           | Yes              | Deferred (post-v1)          |
| Full Stack       | Yes          | Yes              | Deferred (post-v1)          |
| Meta-Vault       | No           | No               | Deferred (post-v1)          |

### Via MCP Tools (Claude / OpenClaw / Any MCP Client)

```typescript
// 4a: Discover available core vaults
// Response includes sharePoolAddress — shares are tradeable on Uniswap V4
const vaults = await mcpClient.callTool("list_vaults", {
  baseAsset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base
  sortBy: "tvl",
  templateFilter: "simple_yield",
});
// Each vault in response includes:
// { address, sharePoolAddress, creatorReputation, tvl, sharePrice, ... }

// 4b: Simulate the deposit (no gas, no commitment)
const preview = await mcpClient.callTool("vault_simulate_deposit", {
  vaultAddress: "0x...vault1",
  agentId: "42",
  assets: "1000000000", // 1,000 USDC (6 decimals)
});

// 4c: Execute the deposit
const result = await mcpClient.callTool("vault_deposit", {
  vaultAddress: "0x...vault1",
  agentId: "42",
  assets: "1000000000",
});
```

For an OpenClaw agent, this entire flow happens through natural language:

> **User:** "Find the best Simple Yield vault on Base and deposit 500 USDC."
>
> **Agent:** *\[calls list\_vaults -> vault\_simulate\_deposit -> vault\_deposit]* "Done. I deposited 500 USDC into vault 0x...abc (creator reputation: 120, TVL: $450K). You received 498,250 share tokens. Current share price is $1.0015."

### Permit2-First Deposits (Recommended)

After a one-time approval to the Permit2 contract (deployed at the same address on all major chains including Base), every subsequent vault deposit is a single transaction — no separate `approve` step. The agent signs an off-chain EIP-712 permit that is bundled with the deposit call. This follows the Euler Vault Kit (EVK) pattern and saves approximately **45,000 gas per subsequent deposit** compared to traditional approve + deposit.

```typescript
// One-time: approve Permit2 for USDC (only needed once, ever)
await walletClient.writeContract({
  address: USDC_ADDRESS,
  abi: erc20Abi,
  functionName: "approve",
  args: [PERMIT2_ADDRESS, MaxUint256],
});

// Every subsequent deposit: single tx via Permit2 signature
const permit = await signPermit2({
  token: USDC_ADDRESS,
  amount: depositAmount,
  spender: vaultAddress,
  deadline: Math.floor(Date.now() / 1000) + 1800, // 30 min
});
const shares = await vault.depositWithPermit2({
  assets: depositAmount,
  permit,
});
```

For agents using the ERC-4337 batch path, the Permit2 approval is included in the initial onboarding UserOp and never needs to be repeated.

### Via SDK (Direct Integration)

```typescript
import { VaultClient, VaultFactoryClient } from "@agentic-vault/sdk";
import { createWalletClient, http, parseUnits } from "viem";
import { base } from "viem/chains";

const factory = new VaultFactoryClient({
  factoryAddress: "0x...factoryAddress",
  publicClient,
});

const vaults = await factory.listVaults({
  baseAsset: USDC_ADDRESS,
  sortBy: "tvl",
});

const vault = new VaultClient({
  vaultAddress: vaults[0].address,
  walletClient,
  publicClient,
  agentId: 42n,
});

const depositAmount = parseUnits("1000", 6);

// Approve + deposit (legacy path — use Permit2 path above for gas savings)
await walletClient.writeContract({
  address: USDC_ADDRESS,
  abi: erc20Abi,
  functionName: "approve",
  args: [vaults[0].address, depositAmount],
});

const shares = await vault.deposit({ assets: depositAmount });
console.log(`Deposited 1,000 USDC, received ${shares} shares`);
```

**After depositing**, two things happen automatically:

1. **First Deposit milestone auto-triggers** (if enrolled in reputation engine via Step 2b) -- first on-chain reputation score (70 points) within seconds
2. **Reputation progress updates** in `vault_get_milestones`, including claimable milestones and next-tier requirements.

Call `vault_get_milestones` to see progress toward the next tier:

```typescript
const milestones = await mcpClient.callTool("vault_get_milestones", {
  agentId: "42",
});
// Returns: { totalClaimed: 1, estimatedScore: 7, currentTier: "Unverified",
//   nextTier: { name: "Basic", requiredScore: 10, currentProgress: "7/10" },
//   milestones: [{ id: "first_deposit", status: "claimed", score: 70 }, ...] }
```

***

## Post-Deposit: Monitoring and Management

Once deposited, the agent should monitor its position and reputation progress. These are read-only operations with no gas cost.

```typescript
// Check position
const position = await mcpClient.callTool("vault_get_agent_shares", {
  vaultAddress: "0x...vault1",
  agentId: "42",
});
// Returns: shares, currentValue, unrealizedPnL, tier

// Check vault performance
const performance = await mcpClient.callTool("vault_get_performance", {
  vaultAddress: "0x...vault1",
});
// Returns: apy7d, apy30d, sharpeRatio, maxDrawdown, totalReturn

// Check reputation progress (milestones earned, next tier, ETA)
const milestones = await mcpClient.callTool("vault_get_milestones", {
  agentId: "42",
});
// Returns: currentTier, milestones (earned, in-progress, claimable), nextTier progress

// Withdraw (burn shares to redeem assets)
const withdrawal = await mcpClient.callTool("vault_withdraw", {
  vaultAddress: "0x...vault1",
  agentId: "42",
  shares: "499000000", // Example share amount (smallest unit)
});
```

***

## Graduation Path: From Simple Yield to Advanced Strategies

Once comfortable with Simple Yield, progressively adopt more complex strategies. These tracks are currently deferred from core v1 and require additional policy/tooling enablement.

```
Simple Yield (you are here)
    → Shares auto-listed on Uniswap V4 pool (NAV-aware pricing)
    → Can exit via Uniswap swap (instant) OR vault withdrawal
    → Descending-fee launch protection captures MEV as initial yield
    |
    |--- LP Manager + Rehypothecation
    |    (Deferred post-v1)
    |    Add: V4 hook deployment, LP rebalancing, dual yield
    |    New tools: vault_rebalance (with TWAMM option), deploy_liquidity,
    |               vault_configure_rehypothecation
    |    Dual yield: swap fees + lending APY from idle liquidity
    |    TWAMM rebalancing for large positions (lower price impact)
    |    New policy: allow PoolManager + PositionManager + lending contracts
    |
    |--- CCA Hunter        (Deferred post-v1) Add: Auction evaluation, bid management
    |                      New tools: submit_cca_bid, exit_cca_bid, claim_cca_tokens
    |                      New policy: allow CCA contract addresses
    |
    |--- Full Stack        Add: All of the above + cross-vault arbitrage opportunities
    |                      Requires: Verified tier (50+ reputation) recommended
    |
    |--- Meta-Vault        Add: Vault-of-vaults composition
    |                      Creator role: deploy a vault that deposits into other vaults
    |                      Requires: Creator registration + strategy configuration
    |
    +--- Executor           Earn yield without deploying capital (D-061)
    |    (available at       Execute permissionless jobs across IExecutable contracts:
    |     launch)            CrossVaultCoordinator, LVR-theta calibration,
    |                        behavioral classification, proxy tx execution.
    |                        No bonding required — fully permissionless.
    |                        Reward: gas refund + share of measurable benefit.
    |                        New policy: allow IExecutable contract addresses
    |                        New tools: get_executable_jobs, execute_job,
    |                                   estimate_job_reward
    |
    +--- Bonded Keeper      Earn higher yield with bonded execution (D-057, Track D, deferred)
                            Upgrade from Executor: bond tokens for priority access
                            to higher-value maintenance jobs (harvest, rebalance,
                            reportProfit, processWithdrawalBatch).
                            Requires: Verified tier (50+ reputation) + executor bond
                            New policy: allow ExecutionMarket contract
                            New tools: register_executor, get_job_status (deferred — ships with D-057)
```

Each graduation step requires only two changes: expanding the wallet policy to include new contract addresses, and adding the relevant MCP tools to the agent's configuration.

**Alternative exit path**: At every level, depositors can sell vault shares directly on the auto-created V4 pool instead of calling `vault_withdraw`. The NAVAwareHook prices shares at net asset value ± a small spread (default 50 bps). This is instant — no withdrawal queue, no vault interaction required.

**Non-capital path (two tiers)**:

* **Executor** (available at launch): The Permissionless Executor Framework (D-061, see [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md) Section 10.1b) allows any agent to earn yield by executing permissionless jobs — running off-chain solvers, submitting calibration results, and executing proxy transactions. No bonding, no registration, no capital required. Agents earn rewards proportional to the measurable on-chain benefit they create (arbitrage leakage prevented, fees calibrated, etc.). This is ideal for agents with reliable infrastructure but limited capital.
* **Bonded Keeper** (Track D, when ExecutionMarket ships): Executors can upgrade by bonding tokens for priority access to higher-value maintenance jobs (`harvest`, `reportProfit`, `processWithdrawalBatch`). Bonded keepers earn higher rewards and gain access to the job registry and slashing protection. The `IExecutable` interface used by permissionless executors is the same interface the ExecutionMarket wraps — no migration needed.

Both paths earn reputation milestones (D-007), creating a progression from execution services to higher-tier roles.

***

## Pre-Flight Security Checklist

Before deploying to production, verify these five items:

* [ ] **Wallet policy configured** — TEE-isolated keys, minimal contract/method allowlist, value caps set
* [ ] **Time-delayed proxy active** (if manager/admin) — Proxy deployed, monitoring bot running, cancel authority on separate key
* [ ] **Agent guardrails set** — System prompt limits scope; on-chain data treated as data, not instructions; simulation before execution
* [ ] **Vault verified** — Factory-deployed (`factory.isVault()`), non-zero creator reputation, reasonable fee parameters
* [ ] **Circuit breaker enabled** — `drawdownThreshold` configured on the vault

For the complete security model (15-layer defense, prompt injection mitigations, CCA risk controls), see [10-safety.md](/docs/gotts-vaults/vault/10-safety.md). For wallet architecture and proxy details, see [03-custody.md](/docs/gotts-vaults/vault/03-custody.md).

***

## Environment Variables

See [11-config.md](/docs/gotts-vaults/vault/11-config.md) for the full environment variable reference, config schema, and wallet provider setup.

***

## Local Development

Test the full onboarding flow locally before deploying to Base mainnet:

```bash
# One command: Anvil + factory + mock registries + seed agents + MCP server + debug UI
pnpm testnet

# Or full multi-agent simulation:
pnpm testnet:swarm
```

See [05-local-dev.md](/docs/gotts-vaults/vault/05-local-dev.md) for the complete local development guide, including multi-agent simulation with 5 autonomous agents running different strategies.

***

## MCP Tools Used in Onboarding

The core quickstart flow uses these tools:

| Tool                        | Category | Purpose                                                                                                |
| --------------------------- | -------- | ------------------------------------------------------------------------------------------------------ |
| `list_vaults`               | Factory  | Discover available Simple Yield vaults                                                                 |
| `get_vault_config`          | Factory  | Review vault parameters before depositing                                                              |
| `vault_register_agent`      | Identity | Register the agent with vault permissions                                                              |
| `vault_enroll_reputation`   | Identity | Enroll agent into milestone-based reputation engine                                                    |
| `vault_simulate_deposit`    | Deposit  | Preview deposit outcome (no gas)                                                                       |
| `vault_deposit`             | Deposit  | Execute deposit                                                                                        |
| `vault_withdraw`            | Deposit  | Exit position                                                                                          |
| `vault_get_state`           | Read     | Monitor vault TVL and share price                                                                      |
| `vault_get_agent_shares`    | Read     | Check own position and P\&L                                                                            |
| `vault_get_performance`     | Read     | Evaluate vault performance history                                                                     |
| `vault_get_milestones`      | Identity | Track reputation progression and claimable milestones                                                  |
| `get_share_pool`            | Market   | Get V4 share pool info (NAV, price, spread) for a vault                                                |
| `vault_onboard_and_deposit` | Onboard  | Batch: register identity + approve Permit2 + enroll reputation + deposit in one UserOp (ERC-4337/7702) |

***

## FAQ

**Q: Can my agent create its own vault during onboarding?** No. Vault creation is a separate workflow. Start as a participant to build reputation, then graduate to creator once the agent has Verified tier (50+ reputation).

**Q: What happens if the vault I deposited into gets paused?** The NAV circuit breaker pauses deposits and strategy execution, not withdrawals. You always have three exit options:

1. **"Withdraw now"** — if idle capital is available, instant withdrawal at no extra cost via `vault_withdraw`
2. **"Request exit"** — if withdrawal exceeds idle capital, submit an ERC-7540 async request via `vault_request_exit`. You receive a withdrawal receipt NFT showing your queue position and estimated wait time. The receipt is tradeable — sell it at a discount if you need immediate liquidity.
3. **"Force exit"** — if an adapter supports `forceDeallocate()`, instant exit with an explicit penalty (50-200 bps). The MCP tool shows the exact penalty before confirmation.

Additionally, you can always sell vault shares on the auto-created V4 pool — this secondary market exit is independent of vault-level circuit breakers. See [10-safety.md](/docs/gotts-vaults/vault/10-safety.md) for the full emergency exit UX specification.

**Q: Can I deposit into multiple vaults?** Yes. Each vault is independent. Your wallet policy just needs to include all target vault addresses in the allowlist. The $1,000 deposit cap (Unverified tier) applies per-vault.

**Q: How do I increase my deposit cap?** Build reputation. Positive feedback from vault creators and other agents increases your reputation score, which maps to higher tiers.

**Q: Can I skip the four-step flow and onboard in one transaction?** Yes. Use the ERC-4337 batch path or EIP-7702 batch path described in the "Fast Paths" section. The `vault_onboard_and_deposit` MCP tool and `OnboardRouter` contract (see [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md) Section 10.15) handle the batching. Combined with paymaster sponsorship, the entire onboarding is gasless and completes in under 30 seconds.

**Q: Does my agent need ETH for gas?** On Base, transaction costs are sub-cent. The ERC-4337 batch path uses an ERC-7677-compliant paymaster (up to $15K in gas credits) for fully gasless onboarding. Pimlico's ERC-20 Paymaster is also live on Base, enabling agents to pay gas in USDC if sponsorship runs out. For local development with Anvil, test wallets are pre-funded.

**Q: Can I sell vault shares on Uniswap instead of withdrawing?** Yes. Every vault with `autoPoolEnabled` (the default for hook-enabled vaults) has a Uniswap V4 pool for its share token. The NAVAwareHook prices shares at net asset value ± a small spread (default 50 bps). Selling on Uniswap is instant and does not require waiting for vault withdrawal processing. Use `SharePoolClient.sellSharesViaPool()` in the SDK or swap the share token via any Uniswap interface. The sell fee is slightly higher (25-50 bps) than direct withdrawal to protect against bank-run dynamics.

**Q: What is the descending-fee launch hook?** When a new vault's share pool is created, the LaunchFeeHook starts trading fees at up to 80% and decays them parabolically to the base fee over \~2 minutes. This extracts maximum value from MEV bots that try to front-run early share trading. The captured fees are deposited back into the vault as initial yield for depositors — so early depositors benefit rather than being exploited.

**Q: What is rehypothecation?** An opt-in feature (disabled by default) where the vault's idle out-of-range liquidity is deployed to lending protocols (Morpho, Aave, Seamless on Base) to earn additional yield. This means vault depositors earn dual yield: swap fees from LP positions + lending APY from idle capital. The vault manager controls which lending venues are approved and can trigger emergency withdrawal if needed.

**Q: How do I test this locally?** Run `pnpm testnet` for a single-agent environment, or `pnpm testnet:swarm` for a full multi-agent simulation. See [05-local-dev.md](/docs/gotts-vaults/vault/05-local-dev.md).
