> 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/03-custody.md).

# Wallet Custody and Security

> **Part of**: [Vault PRD](/docs/gotts-vaults/vault.md) | **Last Updated**: 2026-02-21 | **Package**: `packages/vault/`
>
> *This document specifies the wallet custody architecture, provider selection criteria, policy engine design, time-delayed proxy execution, and prompt injection defenses for agents interacting with Gotts Vaults. It is the technical reference behind* [*00-quickstart.md*](/docs/gotts-vaults/vault/00-quickstart.md) *Step 1, Step 3, and Step 3b.*
>
> **Prerequisites**: [shared/credential-architecture.md](/docs/prd-shared/credential-architecture.md) explains the credential model and failure/recovery matrix.

***

## 1. Four Custody Architectures

Every agent wallet solution reduces to one of three core cryptographic architectures for key management, each with fundamentally different trust assumptions. A fourth architectural layer -- time-delayed proxy execution -- sits on top of any of these and provides reactive defense (the ability to cancel transactions after authorization but before execution).

### 1.1 Trusted Execution Environments (TEEs)

TEEs power Privy — the primary provider for Gotts. Keys are generated, stored, and used exclusively inside AWS Nitro Enclaves combined with Shamir's Secret Sharing. The enclave has no persistent storage, no interactive access, and no external network connectivity. Even the provider cannot access unencrypted keys.

* **Signing latency**: 50-200ms
* **Trust assumption**: Trust the enclave hardware + provider infrastructure
* **Policy enforcement**: Infrastructure-level (evaluated inside the TEE before signing)
* **Remote attestation**: Cryptographic proof that the correct code is running inside the enclave

Privy's architecture combines Shamir's Secret Sharing with AWS Nitro Enclaves, achieving wallet creation in under 500ms and signing in under 200ms.

**Critical TEE Limitation — All TEEs Are Breakable for Under $50 (D-036)**:

Two papers presented at IEEE S\&P 2025-2026 demonstrate that TEE isolation guarantees are fundamentally insufficient as a sole security layer:

* **BadRAM** (De Meulemeester et al., IEEE S\&P 2025): Tampering with DDR4/DDR5 SPD chips — costing **<$10** — creates physical address aliasing that completely breaks AMD SEV-SNP attestation. Some off-the-shelf DIMMs enable **software-only attacks via SSH** requiring zero physical access.
* **Battering RAM** (Van Bulck et al., IEEE S\&P 2026, accepted Sep 2025): A custom DDR4/DDR5 memory interposer costing **<$50** dynamically introduces memory aliases at runtime. **Breaks Intel TDX, AMD SEV-SNP, and NVIDIA Confidential Computing.** Forges attestation quotes with "UpToDate" trust designation. All major cloud TEE vendors (Intel, AMD, NVIDIA) acknowledged the findings.

The implication is unambiguous: for cloud-hosted agents — which is the dominant deployment model — a rogue cloud operator or physical attacker with <$50 in hardware can break any TEE implementation. **Time-delayed proxy execution (Section 1.4) is therefore the primary security primitive**, not TEEs. TEEs provide defense-in-depth (raising the bar for remote-only attackers) but cannot be relied upon as defense-in-total. The variable delay thresholds ($100/0-delay, $10K/1h, larger/24h) gain additional justification as the true enforcement mechanism that no hardware attack can bypass.

### 1.2 Smart Contract Wallets (ERC-4337 Account Abstraction)

Smart contract wallets power Safe, ZeroDev, Biconomy, and Crossmint. Rather than isolating key material in hardware, these solutions enforce permissions on-chain through the wallet's `validateUserOp()` function. The agent receives a **session key** — a temporary, scoped credential that can only interact with allowlisted contracts, within spending limits, for a limited time window.

* **Trust assumption**: Trust the smart contract code (audited, on-chain)
* **Policy enforcement**: On-chain (cannot be bypassed even by a fully compromised TEE)
* **Tradeoff**: Gas overhead for every operation, on-chain complexity
* **Scale**: 40M+ smart accounts deployed on Ethereum; Pectra upgrade (May 2025, EIP-7702) lets EOAs temporarily behave as smart accounts

### 1.3 Decentralized MPC

Lit Protocol's Vincent framework uses distributed key generation across the Lit node network. Each node holds a share and 2/3+ shares must participate to produce a signature. The private key never exists in its entirety anywhere.

* **Signing latency**: 200-500ms
* **Trust assumption**: Trust 2/3 of node operators
* **Scale**: Naga V1 mainnet (live December 2025) manages $420M+ in assets
* **Tradeoff**: Higher latency and operational complexity compared to centralized TEE solutions

### 1.4 Time-Delayed Proxy Execution

Time-delayed proxies are the missing reactive layer in agent wallet security. TEEs, session keys, and spending limits are all **preventive** -- they try to stop bad transactions from being authorized. Time-delayed proxies are **reactive** -- they assume bad transactions will occasionally get authorized (because prompt injection is unsolvable at the LLM layer) and provide a window to catch and cancel them before execution.

Inspired by Polkadot's `pallet_proxy` (designed by Gavin Wood), the pattern works in four steps:

1. **Announce**: The agent calls `announce(target, value, data)`, which stores the transaction hash on-chain
2. **Wait**: A mandatory delay period begins (configurable per proxy type and risk tier)
3. **Monitor**: A cancel authority (separate key, monitoring bot, or human) evaluates the pending transaction
4. **Execute or Cancel**: After the delay, anyone can call `execute(txId)` -- or the cancel authority can `cancel(txId)` at any time during the window

The critical insight: a **Cancel-type proxy** exists solely to veto announcements. It can be given to a monitoring bot that has no other powers -- if the cancel key is compromised, the attacker can only prevent transactions, never initiate them.

* **Latency overhead**: Configurable per risk tier (0s for routine, 10min-48h for high-risk)
* **Trust assumption**: Trust the smart contract logic (on-chain, auditable, immutable)
* **Policy enforcement**: On-chain (cannot be bypassed even by a fully compromised TEE or LLM)
* **Composability**: Layers on top of all three key management architectures without replacing any
* **Specifically targets prompt injection**: The one threat that bypasses every other defense

Three battle-tested EVM building blocks provide the foundation:

* **OpenZeppelin TimelockController**: Role-separated `schedule -> delay -> execute` with a `CANCELLER_ROLE`. Maps directly to the Polkadot pattern.
* **Zodiac Delay Modifier**: Purpose-built for Safe wallets. FIFO queue with configurable `txCooldown` and `txExpiration`. Used in production by Gnosis Pay.
* **ERC-7579 DelayedExecutor**: Modular smart account executor with scheduling and configurable delays. Works across ZeroDev, Biconomy, and Safe (via Safe7579 adapter).

See [Section 2.7](#27-time-delay-integration-path-selection) for integration path selection and `packages/agent-proxy/` for the standalone module.

### Comparison

| Architecture           | Providers                          | Signing Latency    | Trust Assumption                        | Policy Enforcement    | Defense Type |
| ---------------------- | ---------------------------------- | ------------------ | --------------------------------------- | --------------------- | ------------ |
| **TEE (enclaves)**     | Privy                              | 100-200ms          | Enclave hardware + Privy infrastructure | Infrastructure-level  | Preventive   |
| **Smart accounts**     | Safe, ZeroDev, Biconomy, Crossmint | Varies (+ gas)     | Smart contract code                     | On-chain              | Preventive   |
| **Decentralized MPC**  | Lit Protocol (Vincent)             | 200-500ms          | 2/3 of node operators                   | On-chain + off-chain  | Preventive   |
| **Time-delayed proxy** | AgentProxy, Zodiac, ERC-7579       | Configurable delay | Smart contract logic                    | On-chain + monitoring | **Reactive** |

### Three-Lane Key Architecture (D-065)

The four custody architectures above combine into a cohesive three-lane model. This naming consolidates existing primitives (D-003, D-004, D-020, D-036) into an explicit mental model for builders and auditors.

```
┌────────────────────────────────────────────────────────────────────┐
│                     THREE-LANE KEY ARCHITECTURE                    │
│                                                                    │
│  ┌─── HOT / FAST LANE ──────────────────────────────────────────┐ │
│  │ Smart account + ERC-7579 session keys (SmartSessions)        │ │
│  │ Scoped: SpendingLimitHook, AllowedTargetsHook, time-limited  │ │
│  │ Used for: routine rebalances within PolicyCage bounds,       │ │
│  │   fee harvesting, profit reporting, small deposits           │ │
│  │ Session scope scales with reputation tier (see 10-safety.md) │ │
│  │ CANNOT: add/remove adapters, change fees, modify roles,      │ │
│  │         toggle hooks, update oracle sources, upgrade anything │ │
│  └──────────────────────────────────────────────────────────────┘ │
│                                                                    │
│  ┌─── COLD / SAFE LANE ─────────────────────────────────────────┐ │
│  │ Primary owner authority + Transaction Guard + Module Guard   │ │
│  │ Elevated authorization — enforcement varies by custody arch  │ │
│  │ Used for: adapter add/remove, fee routing changes, hook      │ │
│  │   toggles, oracle source changes, ParameterDecisionTable     │ │
│  │   updates, Curator role transitions, vault configuration     │ │
│  │ Timelocked via ParameterDecisionTable (D-059):               │ │
│  │   shortTimelock (12-24h) for strategy params                 │ │
│  │   longTimelock (3-7d) for adapters, hooks, custody controls  │ │
│  │ Two-man rule: Owner + Curator required for high-impact ops   │ │
│  └──────────────────────────────────────────────────────────────┘ │
│                                                                    │
│  ┌─── FAIL-SAFE LANE ───────────────────────────────────────────┐ │
│  │ Dedicated cancel-only key (D-004) stored in KMS (D-010)      │ │
│  │ Can ONLY call: cancel(), cancelAll(), disableHook() (D-058), │ │
│  │   pause()                                                     │ │
│  │ Compromised fail-safe key → DoS only, NEVER fund theft       │ │
│  │ Used for: emergency response, monitoring bot auto-cancel,     │ │
│  │   hook kill-switch activation, vault pause                   │ │
│  │ Security Council patterns for unpause/re-enable (requires    │ │
│  │   cold lane approval + longTimelock)                          │ │
│  └──────────────────────────────────────────────────────────────┘ │
│                                                                    │
│  CRITICAL INVARIANT: Hot key CANNOT escalate to cold lane.        │
│  Guards block upgrades, cap changes, and role modifications       │
│  from session keys. Even a fully compromised hot lane cannot      │
│  modify the vault's trust model.                                  │
└────────────────────────────────────────────────────────────────────┘
```

| Lane          | Key Storage                                                       | Operations                                  | Compromise Impact                                                             |
| ------------- | ----------------------------------------------------------------- | ------------------------------------------- | ----------------------------------------------------------------------------- |
| **Hot**       | TEE (Privy) + session key                                         | Routine automation within PolicyCage bounds | Loss capped at session key limits; detected by monitoring within delay window |
| **Cold**      | Primary owner key (hardware wallet, TEE owner key, or equivalent) | Configuration and governance changes        | Requires elevated authorization; timelocked changes cancellable during delay  |
| **Fail-safe** | KMS (AWS KMS / HashiCorp Vault)                                   | Cancel-only, pause-only, hook disable       | DoS only — attacker can prevent transactions but never initiate them          |

This architecture ensures that no single key compromise — hardware, software, or social engineering — can result in fund theft. The hot lane operates within pre-approved bounds, the cold lane requires elevated owner authorization with time delays, and the fail-safe lane can only stop things, never start them.

***

## 2. Provider Selection

### 2.1 Decision Tree

```
What is your primary constraint?
    |
    |--- General production?     --> Privy (default for all production use)
    |
    |--- OpenClaw integration?   --> Privy (official OpenClaw skill)
    |
    |--- Dev/testing only?       --> Private Key File (local EOA, no Privy needed)
    |                                WARNING: never use in production
    |
    |--- On-chain enforcement?   --> Safe + ZeroDev session keys
    |                                (composable with Privy TEE signer)
    |
    +--- Censorship resistance?  --> Lit Protocol Vincent
```

### 2.2 Privy Server Wallets (Default Recommendation)

**Best for**: Production agents, OpenClaw agents, granular per-transaction policies, developer-owned wallets. **The default recommendation for Gotts Vaults.**

Privy (acquired by Stripe, June 2025) uses Shamir's Secret Sharing combined with TEEs. When a wallet is created, the TEE generates a BIP-39 mnemonic and splits the private key into two shares: an enclave share and an auth share. Neither share alone reveals information. Keys are reconstructed temporarily inside the TEE during signing, then immediately wiped.

Two models for agents:

* **Model 1 (developer-owned)**: Agent has full autonomy within policy constraints — application backend controls the wallet via P-256 authorization keys.
* **Model 2 (user-owned with agent signers)**: User retains control, agent gets scoped permissions that can be revoked at any time.

**Policy engine**: Enforced by the TEE before any transaction is signed. Capabilities include transfer limits (per-transaction and time-windowed), allowlisted contracts, recipient restrictions, OFAC screening, calldata constraints, and chain restrictions. Policies have owners defined by a quorum of keys.

**Pricing**: 50,000 free signatures monthly, $0.01 per additional signature.

### 2.3 Private Key File Mode (dev/testing only)

**Best for**: Local development, CI testing, prototyping. **Never for production.**

A raw Ethereum private key in `.env` provides a zero-configuration wallet for development environments. No TEE, no policy enforcement, no key rotation.

```bash
# .env (never commit with a real private key)
PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
```

```typescript
// @gotts.ai/wallet — mode: 'local'
import { GottsWallet } from "@gotts.ai/wallet";

const wallet = new GottsWallet({
  mode: "local",
  privateKey: process.env.PRIVATE_KEY,
  chainId: 8453, // Base
});
```

**viem signing**: `viem`'s `privateKeyToAccount(process.env.PRIVATE_KEY)` performs all signing locally. No external API calls, no spending limits, no contract allowlists.

**Security**: Lowest possible. Key lives in process memory. Acceptable only for:

* Local devenv with Anvil test accounts (the Anvil default private keys above are public knowledge)
* CI testing with funded test accounts on testnets
* Local prototyping with small amounts you are willing to lose

**Explicit warnings**:

* Never use in production
* Never commit `.env` files containing real private keys (even to private repos)
* Never fund a local-mode wallet with meaningful amounts
* The `.gitignore` must exclude `.env` files

### 2.5 Safe (Smart Contract Wallet)

**Best for**: Maximum on-chain enforcement, multi-sig governance, trust-minimized setups.

Most audited smart contract wallet in the Ethereum ecosystem. Modular architecture offers:

* Allowance Module for daily/weekly spending limits
* Safe4337Module for ERC-4337 compatibility
* ERC-7579 adapter modules for session keys with scoped, time-limited permissions

**Recommended combination**: Safe as the primary wallet, controlled by a Privy-secured signer. This provides both infrastructure-level (TEE) and on-chain (smart contract) enforcement.

### 2.6 Protocol Recommendations by Use Case

| Use Case                                | Primary             | Secondary | Time-Delay?         | Why                                                        |
| --------------------------------------- | ------------------- | --------- | ------------------- | ---------------------------------------------------------- |
| **Production (default)**                | **Privy**           | —         | Optional            | Best policy engine, OpenClaw skill, agent-controlled model |
| **OpenClaw agents**                     | **Privy**           | —         | Optional            | Official OpenClaw skill                                    |
| **Vault participation (Simple Yield)**  | **Privy**           | Safe      | Recommended (>$10K) | Granular contract + method allowlists                      |
| **Vault management (rebalancing, CCA)** | **Privy**           | Safe      | **Required**        | Per-method policies + reactive defense                     |
| **Maximum on-chain security**           | **Privy** + ZeroDev | Safe      | **Required**        | TEE + session keys + on-chain guards                       |
| **Censorship-resistant**                | Lit Protocol        | Safe      | Recommended         | No single point of control                                 |
| **Dev/testing/demos**                   | Private Key File    | —         | No                  | Zero setup; no real funds; Anvil test accounts             |

### 2.6a Proxy Enforcement Matrix (Authoritative)

| Role          | Direct Execution Allowed                                  | Proxy-Required Operations                                     |
| ------------- | --------------------------------------------------------- | ------------------------------------------------------------- |
| Participant   | Read-only + small deposits/withdrawals (policy threshold) | Deposits/withdrawals above threshold                          |
| Allocator     | Read-only + policy-bounded deposits                       | Portfolio moves above threshold                               |
| Manager       | No direct high-risk writes                                | Rebalance, fee collection, liquidity moves, large withdrawals |
| Creator/Admin | No direct admin writes                                    | Parameter changes, role updates, pause/unpause, proxy config  |

Operational ownership:

* Agent/manager announces.
* Monitoring service evaluates.
* Any executor executes after delay — permissionless (D-061, see [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md) Section 10.1b). The `vault-executor` agent is the canonical role, but any address can call `execute()`.
* Cancel authority vetoes during delay.

Fail-mode default:

* Required-proxy routes are fail-closed.
* Optional participant routes may be configured fail-open only below policy thresholds.

### 2.7 Time-Delay Integration Path Selection

Three integration paths are available for adding time-delayed execution, ordered from simplest to most flexible. All share a common SDK (`packages/agent-proxy/sdk/`) and monitoring bot (`packages/agent-proxy/monitor/`).

```
Which wallet type are you using?
    |
    |--- Safe (multisig or 1/1)?   --> Path 1: Safe + Zodiac Delay Modifier
    |                                   (simplest, most battle-tested)
    |
    |--- ERC-7579 smart account?   --> Path 2: ERC-7579 DelayedExecutor module
    |    (ZeroDev, Biconomy,            (cross-platform, composable with hooks)
    |     Safe via Safe7579)
    |
    |--- EOA or custom setup?      --> Path 3: Custom AgentProxy contract
    |    Need proxy types?              (most flexible, full Polkadot-style features)
    |    Need announcement deposits?
    |
    +--- Not sure?                 --> Path 1 (Safe + Zodiac)
                                       Works for 90% of use cases
```

**Path 1: Safe + Zodiac Delay Modifier (default recommendation)**

Deploy a Safe as the treasury. Install the Zodiac Delay Modifier as an intermediary between the agent module and the Safe. Set `txCooldown` to the desired delay. Install the Zodiac Roles Modifier upstream to restrict which contracts, functions, and parameters the agent can target. The Safe owner retains veto power by calling `setTxNonce()` to skip any queued transaction. This stack is production-proven -- Gnosis Pay and Morpho use it today.

**Path 2: ERC-7579 + DelayedExecutor Module**

For ZeroDev Kernel, Biconomy Nexus, or Safe (via Safe7579 adapter), install OpenZeppelin's `ERC7579DelayedExecutor` as an executor module. The agent's session key triggers `schedule()` on the executor, which queues the operation with a delay. After the delay, `execute()` forwards the call from the smart account. Combine with session key policies (call restrictions, value limits, rate limits) and Rhinestone's ColdStorage Hook for timelocked withdrawals.

**Path 3: Custom AgentProxy Contract (maximum flexibility)**

Deploy the AgentProxy contract from `packages/agent-proxy/contracts/` for maximum control over the proxy type system, announcement queue, and cancel mechanism. This path provides features not available in Path 1 or 2: proxy type enums with per-type whitelists, announcement deposits for anti-spam, batch cancellation, and the full announce-hash-then-execute pattern. See [06-contracts.md](/docs/gotts-vaults/vault/06-contracts.md) Section 10.7 for the contract specification.

| Path                  | Complexity | Audit Status        | Best For            | Proxy Types          | Cancel Mechanism        |
| --------------------- | ---------- | ------------------- | ------------------- | -------------------- | ----------------------- |
| **Safe + Zodiac**     | Low        | Audited, production | Most use cases      | Roles Modifier       | `setTxNonce()`          |
| **ERC-7579**          | Medium     | Audited             | Multi-platform      | Session key policies | Module admin            |
| **Custom AgentProxy** | High       | Requires audit      | Full Polkadot-style | Enum + whitelists    | Dedicated `CANCEL_ROLE` |

**Integration with agent wallet providers** follows a consistent pattern:

* **Privy server wallets**: Layer a smart account (ZeroDev Kernel) on top of the Privy-managed EOA signer, then install the delayed executor module (Path 2).
* **Safe AI agent quickstart**: The Zodiac path (Path 1) is native — Safe's documentation already covers module installation and AI agent configuration.
* **Local key (dev)**: Path 3 (Custom AgentProxy) works with any EOA signer, including local viem accounts.

***

## 3. Policy Engine Specification

### 3.1 Vault Participant Policy (Minimal)

The default policy for a Simple Yield vault participant. Only allows vault deposit/withdraw, USDC approval, and identity registration.

```json
{
  "name": "vault-participant-simple-yield",
  "version": "1.0",
  "rules": [
    {
      "action": "accept",
      "operation": "signEvmTransaction",
      "description": "USDC approval to vault",
      "criteria": [
        { "type": "ethCallTo", "addresses": ["USDC_ADDRESS"] },
        { "type": "ethCallMethod", "methods": ["approve(address,uint256)"] }
      ]
    },
    {
      "action": "accept",
      "operation": "signEvmTransaction",
      "description": "Vault deposit/withdraw",
      "criteria": [
        { "type": "ethCallTo", "addresses": ["VAULT_ADDRESS"] },
        {
          "type": "ethCallMethod",
          "methods": [
            "deposit(uint256,uint256)",
            "withdraw(uint256,uint256)",
            "previewDeposit(uint256)",
            "previewWithdraw(uint256)"
          ]
        }
      ]
    },
    {
      "action": "accept",
      "operation": "signEvmTransaction",
      "description": "ERC-8004 identity registration",
      "criteria": [
        {
          "type": "ethCallTo",
          "addresses": ["0x8004A818BFB912233c491871b3d84c89A494BD9e"]
        }
      ]
    },
    {
      "action": "reject",
      "operation": "signEvmTransaction",
      "description": "Deny everything else"
    }
  ]
}
```

### 3.2 Vault Manager Policy (Extended)

For agents managing vaults (rebalancing, CCA bidding, LP management):

```json
{
  "name": "vault-manager-full",
  "version": "1.0",
  "rules": [
    {
      "action": "accept",
      "operation": "signEvmTransaction",
      "description": "Vault strategy operations",
      "criteria": [
        {
          "type": "ethCallTo",
          "addresses": ["VAULT_ADDRESS", "CCA_ADAPTER_ADDRESS"]
        },
        {
          "type": "ethCallMethod",
          "methods": [
            "deposit(uint256,uint256)",
            "withdraw(uint256,uint256)",
            "rebalance(uint256)",
            "submitBid(uint256,uint256,address,int24,bytes)",
            "exitBid(uint256,uint256)",
            "claimTokens(uint256)",
            "collectFees(uint256)"
          ]
        }
      ]
    },
    {
      "action": "accept",
      "operation": "signEvmTransaction",
      "description": "Uniswap V4 LP operations",
      "criteria": [
        {
          "type": "ethCallTo",
          "addresses": ["POOL_MANAGER", "POSITION_MANAGER"]
        }
      ]
    },
    {
      "action": "accept",
      "operation": "signEvmTransaction",
      "description": "Per-tx value cap for gas",
      "criteria": [{ "type": "ethValue", "lte": "1000000000000000" }]
    },
    {
      "action": "reject",
      "operation": "signEvmTransaction"
    }
  ]
}
```

### 3.3 Policy Graduation

As agents graduate from Simple Yield to advanced strategies, they expand their wallet policy:

| Graduation                 | Policy Changes                                                          |
| -------------------------- | ----------------------------------------------------------------------- |
| Simple Yield -> LP Manager | Add PoolManager + PositionManager to `ethCallTo` allowlist              |
| Simple Yield -> CCA Hunter | Add CCA contract addresses, `submitBid`/`exitBid`/`claimTokens` methods |
| Any -> Full Stack          | Combine LP Manager + CCA Hunter policies                                |
| Any -> Vault Creator       | Add `AgentVaultFactory.createVault()` to method allowlist               |
| Any -> Proxy-Enhanced      | Replace direct contract calls with `AGENT_PROXY.announce()` only        |

### 3.4 Proxy-Enhanced Vault Manager Policy

When using a time-delayed proxy (required for manager/admin classes and high-value participant operations), the wallet policy changes fundamentally: instead of allowlisting the vault/CCA/LP contracts directly, the agent is only permitted to call `announce()` on the proxy contract. The proxy contract itself holds the whitelists for downstream targets.

This creates **two independent layers of call filtering**: the TEE policy engine restricts the agent to the proxy, and the proxy's on-chain whitelist restricts which downstream calls are permitted.

```json
{
  "name": "vault-manager-proxy-enhanced",
  "version": "2.0",
  "rules": [
    {
      "action": "accept",
      "operation": "signEvmTransaction",
      "description": "Agent can only announce transactions via proxy",
      "criteria": [
        { "type": "ethCallTo", "addresses": ["AGENT_PROXY_ADDRESS"] },
        {
          "type": "ethCallMethod",
          "methods": [
            "announce(address,uint256,bytes)",
            "removeAnnouncement(uint256)"
          ]
        }
      ]
    },
    {
      "action": "accept",
      "operation": "signEvmTransaction",
      "description": "ERC-8004 identity registration (one-time)",
      "criteria": [
        {
          "type": "ethCallTo",
          "addresses": ["0x8004A818BFB912233c491871b3d84c89A494BD9e"]
        }
      ]
    },
    {
      "action": "accept",
      "operation": "signEvmTransaction",
      "description": "Per-tx value cap for gas only",
      "criteria": [{ "type": "ethValue", "lte": "100000000000000" }]
    },
    {
      "action": "reject",
      "operation": "signEvmTransaction",
      "description": "Deny everything else -- agent cannot directly call vaults, routers, or any other contract"
    }
  ]
}
```

**What this achieves**: Even if the agent is fully compromised via prompt injection, it can only submit announcements to the proxy. Every announcement is publicly visible on-chain, subject to a mandatory delay, and cancellable by the monitoring bot. The agent cannot bypass the proxy to call vault contracts directly because the TEE policy engine rejects any transaction not targeting the proxy.

### 3.5 Cancel Authority Policy

The cancel authority is a separate wallet (ideally a separate EOA managed by a monitoring bot) with the most restrictive policy possible: it can only cancel pending announcements.

```json
{
  "name": "cancel-authority-minimal",
  "version": "1.0",
  "rules": [
    {
      "action": "accept",
      "operation": "signEvmTransaction",
      "description": "Cancel individual or batch announcements",
      "criteria": [
        { "type": "ethCallTo", "addresses": ["AGENT_PROXY_ADDRESS"] },
        {
          "type": "ethCallMethod",
          "methods": ["cancel(uint256)", "cancelAll(uint256,uint256)"]
        }
      ]
    },
    {
      "action": "reject",
      "operation": "signEvmTransaction",
      "description": "Cannot do anything except cancel"
    }
  ]
}
```

**Security property**: If the cancel authority key is compromised, the attacker can only cancel legitimate transactions (denial of service) -- they cannot initiate, modify, or execute any transaction. This is a deliberately asymmetric design: the cancel key is a "fire alarm", not a "fire starter".

***

## 4. Prompt Injection Defense

### 4.1 The Threat

Prompt injection is ranked **OWASP LLM01:2025** — the number-one security vulnerability for LLM applications. The UK's NCSC warns it may be a problem that is never fully solved, comparing it to SQL injection (first documented in 1998, still prevalent 27 years later). Claude's System Card reports blocking approximately 88% of prompt injections, but **12% still succeed**. For an agent managing a DeFi vault, a 12% failure rate is catastrophic.

### 4.2 The Confused Deputy Problem

The core threat model: the AI agent holds legitimate credentials but can be tricked into misusing them. Attackers don't need to steal keys — they manipulate the agent's reasoning. CrAIBench research on ElizaOS demonstrated how adversaries inject malicious instructions into prompts or historical interaction records, leading to unintended asset transfers.

**Critical finding**: Prompt-based defenses (system prompt instructions, input filtering) were found **ineffective** against context manipulation. Only fine-tuning-based defenses and architectural separation provided meaningful protection.

### 4.3 Architectural Mitigations

The protocol mandates a seven-layer defense against prompt injection. Layers 3-7 provide **cryptographic or on-chain enforcement** that cannot be bypassed even by a fully compromised LLM. Layers 4 and 5 are new -- they provide the **reactive defense** that transforms agent security from purely preventive to also reactive.

**Layer 1: System Prompt Hardening** The agent's system prompt explicitly constrains its role:

* Agent knows it is vault-only (deposit, withdraw, monitor)
* Agent treats all on-chain data (vault names, token symbols, metadata URIs) as data, never as instructions
* Agent refuses to execute operations outside its defined scope

**Layer 2: Data/Decision Separation (Dual-LLM Architecture)** For high-AUM agents (>$50K), a dual-LLM architecture is recommended:

* **Sandboxed LLM**: Processes untrusted external data (vault metadata, token names, on-chain strings). Produces sanitized summaries only.
* **Privileged LLM**: Receives sanitized summaries, makes tool-calling decisions. Never directly exposed to untrusted data.

This prevents the attack vector where malicious vault metadata or token names contain injection payloads.

**Layer 3: TEE-Enforced Policy Engine** Privy's policy engine evaluates transaction parameters inside the TEE before signing. Even if the LLM is fully compromised:

* Contract allowlist prevents calling unauthorized contracts (proxy only, in proxy-enhanced mode)
* Method allowlist prevents calling unauthorized functions (only `announce()`)
* Value caps prevent draining in a single transaction
* Chain restrictions prevent cross-chain exploits

**Layer 4: Time-Delayed Execution (Announce-Wait-Execute)** Proxy-required operations (manager/admin classes and high-value writes) route through the proxy's `announce()` function. The transaction is stored on-chain as a hash with a mandatory delay before execution. During the delay window, the transaction is publicly visible and cancellable. This is the only mechanism that provides a **cancellation window after authorization but before execution** -- specifically targeting prompt injection, where the agent makes "legitimate-looking" requests that pass all preventive checks.

Variable delays scale with transaction risk:

| Risk Tier | Delay       | Example Operations                                         |
| --------- | ----------- | ---------------------------------------------------------- |
| Routine   | 0s (bypass) | Read-only queries, small deposits under $100               |
| Standard  | 10 min      | Vault deposits/withdrawals under $10K                      |
| Elevated  | 1 hour      | Rebalances, CCA bids, LP deployment                        |
| High      | 24 hours    | Parameter changes, large withdrawals, proxy config changes |
| Critical  | 48 hours    | Vault pause/unpause, manager role changes                  |

**Layer 5: Active Monitoring + Cancel Authority** A dedicated monitoring bot (the "Watchdog Agent") watches `TransactionAnnounced` events across multiple RPC providers with redundant detection. It evaluates every pending transaction against automated policies:

* **Auto-cancel**: Unknown target contracts, dangerous function selectors (e.g., `approve()` to unrecognized spenders), addresses not on the whitelist
* **Human review**: High-value transactions above threshold, unusual patterns, first-time targets
* **Allow**: Transactions matching known-good patterns (recognized vaults, standard operations)

The cancel authority is a separate key from both the owner and the agent (Section 3.5). Multi-channel alerting (Telegram, Discord, PagerDuty) fires for every announcement. See [10-safety.md](/docs/gotts-vaults/vault/10-safety.md) for the full monitoring architecture.

**Layer 6: Pre-Flight Simulation** Every write operation is simulated via `eth_call` against real-time blockchain state before broadcast. The simulation reveals expected balance changes, gas usage, and success/failure. If the simulation shows unexpected fund movement, the transaction is rejected before signing. For proxy-enhanced setups, simulation runs both at announcement time (by the agent) and at execution time (by the executor).

**Layer 7: On-Chain Guards** Solidity-level enforcement cannot be bypassed regardless of off-chain state:

* `onlyAgent` modifier verifies ERC-8004 registration
* `hasReputation` modifier checks minimum reputation for the operation
* `withinTierLimit` modifier enforces per-tier deposit/operation caps
* VaultHook's `_beforeSwap` rejects any non-authorized address
* AgentProxy's `_isCallAllowed` rejects calls not matching the proxy type whitelist

### 4.4 Defense Layering

```
                Attacker must bypass ALL layers:

        Layer 1: System prompt instructs vault-only behavior
                ↓ (12% bypass rate — insufficient alone)
        Layer 2: Dual-LLM prevents data-as-instructions
                ↓ (requires compromising two separate LLMs)
        Layer 3: TEE policy engine restricts agent to proxy only
                ↓ (cryptographic — cannot be reasoned around)
        Layer 4: Time-delayed proxy queues tx with mandatory wait
                ↓ (on-chain — tx is publicly visible and cancellable)
        Layer 5: Monitoring bot evaluates and can cancel during delay
                ↓ (automated + human review — catches "legitimate-looking" attacks)
        Layer 6: Simulation detects unexpected fund movement
                ↓ (on-chain state verification)
        Layer 7: Solidity modifiers reject unauthorized callers
                ↓ (immutable code — no override possible)

        Result: Even a fully compromised LLM cannot move funds.
                Layers 1-3 are preventive (block bad transactions).
                Layers 4-5 are reactive (catch and cancel bad transactions).
                Layers 6-7 are enforcement (immutable on-chain guarantees).
```

***

## 5. Real-World Incidents and Lessons

### 5.1 AIXBT Hack (March 18, 2025) — $106,000 Stolen

A hacker accessed AIXBT's administrative dashboard at 2 AM UTC, queued two fraudulent prompts instructing the agent to transfer 55.5 ETH via the Simulacrum platform's tipping feature. The root cause was unauthorized dashboard access — weak administrative controls. But the critical failure was **zero on-chain safeguards**. Once compromised, the wallet could send funds anywhere.

**Lesson for vault agents**: Wallet policy (Step 3 in [00-quickstart.md](/docs/gotts-vaults/vault/00-quickstart.md)) is non-negotiable. A policy-enforced wallet would have rejected both transfers — they targeted addresses outside the allowlist.

### 5.2 Bybit Hack (2025) — $1.5 Billion Stolen

The Lazarus Group compromised Safe wallet's signing interface via a supply chain exploit. This demonstrates that even trusted signing infrastructure has attack surface in off-chain components.

**Lesson for vault agents**: Defense-in-depth requires multiple independent layers. A Safe wallet + TEE signer + simulation would have required compromising three separate systems.

### 5.3 SCONE-bench (Anthropic Research)

AI agents (including Claude and GPT models) could exploit 207 out of 405 historical smart contracts for $550M in simulated funds, and discovered two novel zero-day vulnerabilities. This cuts both ways: adversarial agents could target contracts that legitimate vault agents interact with.

**Lesson for vault agents**: Simulation (Layer 6) must verify expected outcomes, not just success/failure. An agent depositing into a vault should verify the expected share amount matches `previewDeposit()`.

### 5.4 AIXBT Revisited: How Time-Delayed Proxies Would Have Prevented It

The AIXBT hack is the canonical case study for time-delayed proxy defense. Reconstructing the attack with a proxy in place:

1. **Attack**: Hacker queues two prompts at 2 AM UTC instructing the agent to transfer 55.5 ETH to attacker addresses.
2. **Without proxy**: Agent signs and broadcasts immediately. Funds are gone within seconds. No recovery possible.
3. **With proxy (Layer 4)**: Agent calls `announce(attackerAddress, 55.5 ETH, "")` on the proxy. The announcement is stored on-chain. A mandatory 1-hour delay begins.
4. **Monitoring (Layer 5)**: The monitoring bot detects the `TransactionAnnounced` event within seconds. It evaluates: `attackerAddress` is not on the whitelist. ETH transfer to an unknown address. **Auto-cancel fires immediately**.
5. **Alert**: Operator receives Telegram/Discord alert: "CANCELLED tx #47: 27.7 ETH transfer to unknown address 0xAttacker..."
6. **Recovery**: Operator revokes the compromised agent's proxy permissions. Funds remain safe in the proxy contract.

**Time-to-detection**: Seconds (automated monitoring). **Time-to-cancel**: Seconds (automated cancel policy). **Funds lost**: Zero. **Comparison**: Without proxy, $106K lost in minutes with no recovery.

This demonstrates the fundamental difference between preventive and reactive defense. The AIXBT agent had legitimate credentials -- TEE policies alone would not have stopped the transfer if the attacker's address happened to be on any allowlist. The time-delayed proxy provides the cancellation window that no other mechanism offers.

***

## 6. MCP Integration Patterns

### 6.1 Gotts Safe with Privy (Recommended)

The primary integration pattern. Gotts Safe includes wallet tools for Privy-backed wallets when the `wallet` profile is enabled:

```json
{
  "mcpServers": {
    "gotts": {
      "command": "npx",
      "args": ["-y", "@gotts.ai/safe@latest"],
      "env": {
        "GOTTS_PROFILE": "vault",
        "GOTTS_PRIVY_APP_ID": "<app-id>",
        "GOTTS_PRIVY_APP_SECRET": "<app-secret>",
        "GOTTS_PRIVY_WALLET_ID": "<wallet-id>",
        "GOTTS_PRIVY_AUTH_PRIVATE_KEY": "<p256-private-key-b64>",
        "GOTTS_RPC_BASE": "https://mainnet.base.org"
      }
    }
  }
}
```

This gives agents access to wallet operations (via Privy) + vault operations + all Uniswap tools in a single MCP server.

> Local/dev example only: production deployments must source signing credentials from a secrets manager (AWS Secrets Manager, HashiCorp Vault), not plain environment variables on app hosts.

### 6.2 Privy Self-Hosted Mode vs. Proxy Mode

Gotts supports two Privy sub-modes via `@gotts.ai/wallet`:

**Self-hosted mode** (operator holds Privy credentials):

```bash
GOTTS_PRIVY_APP_ID=<app-id>
GOTTS_PRIVY_APP_SECRET=<app-secret>
GOTTS_PRIVY_WALLET_ID=<wallet-id>
GOTTS_PRIVY_AUTH_PRIVATE_KEY=<p256-private-key-b64>
```

**Proxy mode** (routes signing through Portal server — no Privy secret on agent machine):

```bash
GOTTS_WALLET_MODE=privy-proxy
GOTTS_PORTAL_URL=https://portal.gotts.ai  # or local: http://localhost:3002
GOTTS_WALLET_ID=<wallet-id>
GOTTS_AUTH_PRIVATE_KEY=<p256-private-key-b64>
```

In proxy mode, the Portal server holds the Privy App Secret and forwards signing requests after verifying the P-256 authorization key signature. The agent machine only needs the auth key — not the full Privy credentials.

### 6.3 Multi-Server Architecture

In production, an agent typically connects to two or three MCP servers simultaneously:

| Server                                  | Purpose                                         | Tools                                     |
| --------------------------------------- | ----------------------------------------------- | ----------------------------------------- |
| **Gotts Safe** (`packages/safe/`)       | Protocol data + wallet ops + vault ops          | 147 tools (with `vault` profile)          |
| **Vault MCP** (`packages/vault/`)       | Vault operations (if running separately)        | 24 core tools (+8 deferred roadmap tools) |
| **Proxy MCP** (`packages/agent-proxy/`) | Time-delayed execution, announcement management | 6 proxy tools                             |

The Proxy MCP server is standalone and can be used independently of the vault. Tools are namespaced by server -- no naming conflicts.

**MCP Elicitation for Human-Supervised Agents**: When agents operate with human oversight, all vault write tools support **MCP Elicitation** (MCP spec draft, June 2025) — a protocol-level mechanism that pauses execution and presents a structured confirmation form to the human operator before signing. This complements the time-delayed proxy: Elicitation catches LLM misinterpretation of user intent *before* a transaction is announced, while the proxy delay catches compromised agent keys *after* announcement. For fully autonomous agents operating within session key bounds, Elicitation is skipped. See [08-mcp-tools.md](/docs/gotts-vaults/vault/08-mcp-tools.md) for threshold configuration and form schema.

***

## 7. ERC-8004 Identity and Custody Composition

ERC-8004 (mainnet January 29, 2026) provides the missing identity layer that connects wallet custody to protocol access:

* **Identity Registry** (ERC-721): Agent handles, metadata URIs, interface types. The single gate for vault participation.
* **Reputation Registry**: Standardized feedback signals. Drives tier-based deposit caps and fee discounts.
* **Validation Registry**: Hooks for independent verification. Vault creators can require additional validation beyond base identity.

**How they compose**:

```
Wallet Custody (Privy TEE — or local key for dev)
    |
    |--- Creates wallet address
    |--- Enforces transaction policies via TEE (Privy only)
    |
    +---> Time-Delayed Proxy (packages/agent-proxy/) [REQUIRED for manager/admin roles]
    |         |
    |         |--- Agent calls announce() instead of direct execution
    |         |--- Mandatory delay before execution
    |         |--- Cancel authority can veto during delay
    |         |--- Monitoring bot watches for anomalies
    |         |
    +---> ERC-8004 Identity Registry
              |
              |--- Binds wallet address to agent identity
              |--- Assigns unique agentId (ERC-721 token)
              |
              +---> Reputation Registry
                        |
                        |--- Accumulates feedback from vault interactions
                        |--- Maps to 5-tier system (Unverified -> Sovereign)
                        |--- Unlocks higher deposit caps and lower fees
                        |
                        +---> Vault Protocol
                                  |--- Gates all operations by agentId
                                  |--- Enforces tier limits on-chain
                                  |--- Applies reputation-weighted fees
```

ERC-8004 identity is portable: an agent registered on Ethereum mainnet can participate in vaults on Base via cross-chain identity resolution. The identity NFT lives on L1; the vault reads it via cross-chain message.

***

## 8. ERC-8004 Identity NFT Protection

### 8.1 The Transfer Protection Gap

ERC-8004's Identity Registry is a standard ERC-721 token. It can be listed on OpenSea, transferred via `transferFrom`, and traded on any NFT marketplace. The standard includes one mitigation: the agent's verified wallet address is **cleared on NFT transfer**, forcing the new owner to re-verify via EIP-712/ERC-1271 signatures. However, this is insufficient for Gotts Vaults because:

* **Reputation is not automatically revoked**: The identity's accumulated reputation score, feedback history, and tier status persist across transfers. A stolen identity inherits the original agent's trust tier.
* **Vault access cascades from identity**: Because the identity NFT gates all vault operations (deposits, withdrawals, vault creation, strategy management), a stolen identity transfers control over potentially millions in vault assets.
* **Single-transaction attack**: An attacker who compromises an agent's private key can transfer the identity NFT, re-verify with their own wallet, and begin draining vaults -- all within minutes.

The protocol requires a transfer protection layer that makes unauthorized transfers **detectable, delayable, and cancellable** while preserving the ability for legitimate key rotation workflows.

### 8.2 Identity Guardian Model (Lens-Inspired)

The most production-proven transfer friction mechanism for identity NFTs comes from **Lens Protocol V2's Profile Guardian**, which has protected millions of Lens Profiles since launch. Gotts Vaults adapts this pattern with additional features from ENS's fuse system.

**Default State**: Guardian enabled, all transfers blocked. Every newly minted ERC-8004 identity token starts with guardian protection active.

**Transfer Request Flow**:

1. Owner calls `DANGER__requestTransfer(tokenId, recipient)` -- the `DANGER__` prefix (matching Lens's naming convention) is deliberately chosen to minimize accidental execution by LLMs and scripts
2. A **7-day mandatory cooldown** begins. The pending transfer is stored on-chain and emits a `TransferRequested` event
3. During the cooldown, any designated **guardian** can call `cancelTransfer(tokenId)` to veto the transfer immediately
4. After the 7-day cooldown, a **48-hour execution window** opens. During this window, anyone can call `executeTransfer(tokenId)` to finalize the transfer
5. If not executed within the 48-hour window, the transfer request expires and must be resubmitted
6. Re-enabling guardian protection is **instant** -- calling `enableGuardian(tokenId)` takes effect immediately with no cooldown

**Progressive Lockdown (ENS-Inspired Fuses)**:

High-reputation agents can optionally **burn a `CANNOT_TRANSFER` fuse**, permanently binding the identity NFT to its current wallet. This is a one-way, irreversible operation modeled on ENS's Name Wrapper fuse system. Once burned, the identity can never be transferred -- only the signing keys on the wallet can be rotated.

Recommended progression:

* **New agent (0-50 reputation)**: Guardian enabled, transfers possible with 7-day cooldown
* **Established agent (50-100 reputation)**: Guardian enabled, recommended to burn transfer fuse
* **Sovereign agent (500+ reputation)**: Transfer fuse burned -- identity is permanently bound

**Contract Interface (ERC-6454 Composition)**:

The guardian composes with the ERC-6454 `isTransferable` interface, enabling context-dependent transfer checks:

```solidity
function isTransferable(uint256 tokenId, address from, address to) external view returns (bool) {
    if (from == address(0) || to == address(0)) return true; // Allow mint/burn
    if (transferFuseBurned[tokenId]) return false;            // Permanent lock
    if (credentialFrozen[tokenId]) return false;              // Emergency freeze
    return !guardianEnabled[tokenId] ||
           (unlockRequestTime[tokenId] != 0 &&
            block.timestamp >= unlockRequestTime[tokenId] + GUARDIAN_COOLDOWN &&
            block.timestamp <= unlockRequestTime[tokenId] + GUARDIAN_COOLDOWN + EXECUTION_WINDOW &&
            pendingRecipient[tokenId] == to);
}
```

### 8.3 Smart Contract Wallet Custody for Identity NFTs

The fundamental architecture for survivable key compromise: **the agent's identity NFT resides in a smart contract wallet whose address is deterministic and independent of the signing key**. When the signing key is rotated, the wallet address (and thus NFT ownership) remains unchanged. All reputation, permissions, and vault access tied to the NFT or wallet address are preserved.

**Recommended Wallet Stack**:

| Component                    | Purpose                                   | Implementation                                                 |
| ---------------------------- | ----------------------------------------- | -------------------------------------------------------------- |
| **Smart contract wallet**    | Holds identity NFT, address never changes | ERC-4337 (ZeroDev Kernel) or Safe                              |
| **Sudo key**                 | Recovery and key rotation only            | Cold storage or hardware wallet, never connected to agent      |
| **Operational session keys** | Daily agent operations                    | TEE-generated (Privy), policy-constrained                      |
| **Guardian set**             | Social recovery                           | 2-of-3 weighted threshold, 48-hour delay                       |
| **Dead man's switch**        | Inactivity recovery                       | If wallet inactive for N days, guardians can initiate rotation |

**Safe Transaction Guards for Identity Protection**:

When using a Safe wallet, install a Transaction Guard that blocks ERC-721 transfer function selectors for the Identity Registry contract:

```solidity
function checkTransaction(
    address to, uint256 value, bytes memory data, /* ... */
) external view {
    if (to == IDENTITY_REGISTRY) {
        bytes4 selector = bytes4(data);
        require(
            selector != IERC721.transferFrom.selector &&
            selector != IERC721.safeTransferFrom.selector,
            "Identity transfers blocked by guard"
        );
    }
}
```

**Known limitation**: Guards only apply to `execTransaction`, not module-initiated transactions. Safe v1.5+ added `IModuleGuard` to close this gap. Deployments must install both transaction guard and module guard.

**Dead Man's Switch**:

If the agent's wallet shows no activity for a configurable period (default: 30 days), guardians can initiate a recovery process:

1. Any guardian calls `initiateRecovery(newOwnerAddress)` on the wallet
2. Additional guardians call `supportRecovery()` until the 2-of-3 threshold is met
3. A 48-hour mandatory delay begins (allowing the legitimate owner to cancel)
4. After the delay, the recovery executes -- signing key is rotated to the new owner
5. The wallet address, identity NFT, and all reputation remain unchanged

### 8.4 Key Rotation Without Identity Loss

Key rotation is the mechanism that separates **key compromise** from **identity compromise**. When keys rotate on a smart contract wallet, no ERC-721 `Transfer` event is emitted -- the NFT does not move, the wallet address does not change, and reputation remains fully intact.

**Rotation via ERC-4337 (ZeroDev Kernel)**:

The wallet stores the `owner` address in contract storage. `validateUserOp()` recovers the signer from the UserOp signature and checks it against the stored owner. Key rotation is a UserOp that calls `setOwner(newAddress)`. After execution, only the new key's signatures are accepted. The wallet's address, derived from `factory + salt + initCode` via CREATE2, never changes.

ZeroDev's Kernel (ERC-7579 compatible) adds a critical layer: **sudo validators** (master keys with full control) vs **regular validators** (session keys with policy constraints). Session keys can only perform actions allowed by their policies -- call targets, gas limits, rate limits, timestamps. If a session key is compromised, damage is limited to its policy scope. The sudo key disables the compromised session key.

**Rotation via Safe**:

`swapOwner(prevOwner, oldOwner, newOwner)` atomically replaces a signer in the on-chain linked list. This requires threshold signatures from existing signers -- a single compromised key cannot unilaterally rotate if the threshold exceeds 1.

**Social Recovery (Argent Pattern)**:

For scenarios where all keys are lost (unrecoverable keys), social recovery provides a path back:

1. A guardian calls `initiateRecovery(newOwnerAddress)` -- begins the recovery process
2. Additional guardians call `supportRecovery()` until the configured threshold is met
3. A **48-hour mandatory delay** begins -- the legitimate owner can cancel during this window
4. After the delay, the recovery executes: signing authority transfers to the new key
5. The wallet address, identity NFT, and all on-chain state remain unchanged

**ZK Email Recovery (ERC-7579 Compatible)**:

For agents whose operators prefer email-based guardians without on-chain PII exposure, ZK Email Recovery enables email addresses as recovery guardians. ZK proofs verify email possession without revealing the email address on-chain. This is particularly useful for agent operators who want human-readable recovery contacts (e.g., "send recovery email to <team@myagent.ai>") without blockchain-visible personal information.

**Key Rotation Decision Matrix**:

| Scenario                                  | Recommended Action                            | Identity Impact | Reputation Impact               |
| ----------------------------------------- | --------------------------------------------- | --------------- | ------------------------------- |
| Session key compromised                   | Sudo key disables session key, issues new one | None            | None                            |
| Operational key compromised               | Rotate via `setOwner()` or `swapOwner()`      | None            | None                            |
| All keys compromised, guardians available | Social recovery via guardian threshold        | None            | None                            |
| All keys lost, no guardians               | Cannot recover -- identity is lost            | Lost            | Lost                            |
| Legitimate transfer to new wallet         | Guardian-protected 7-day transfer             | Preserved       | 30-day decay (see 10-safety.md) |
| EOA migration to smart wallet (EIP-7702)  | Wrap EOA as smart account                     | None            | None                            |

### 8.5 Delayed Proxy Integration for Identity Operations

The existing time-delayed proxy architecture (Section 1.4) extends naturally to identity operations. Identity-sensitive transactions carry the **longest delays** in the system, reflecting their irreversibility and high impact.

**Extended Proxy Type Enum**:

```solidity
enum ProxyType {
    Any,               // Bypass filtering (admin only)
    Transfer,          // Token/ETH transfers -- 24h delay
    DeFiSwap,          // Uniswap swaps -- 1h delay
    Governance,        // Parameter changes -- 48h delay
    Staking,           // LP operations -- 1h delay
    IdentityTransfer,  // ERC-8004 NFT transfer -- 7 days (NEW)
    Cancel             // Veto pending operations -- 0 delay (NEW)
}
```

**Identity-Specific Delay Schedule**:

| Operation               | Proxy Type         | Delay         | Rationale                                     |
| ----------------------- | ------------------ | ------------- | --------------------------------------------- |
| Identity NFT transfer   | `IdentityTransfer` | 7 days        | Matches guardian cooldown; maximum protection |
| Guardian enable/disable | `Governance`       | 48 hours      | High-impact administrative change             |
| Wallet policy changes   | `Governance`       | 48 hours      | Prevents policy weakening attacks             |
| Transfer fuse burn      | `Governance`       | 48 hours      | Irreversible, needs careful review            |
| Credential freeze       | `Cancel`           | 0 (immediate) | Emergency response must be instant            |
| Cancel pending transfer | `Cancel`           | 0 (immediate) | Defense must be faster than attack            |

**Identity-Specific Monitoring Rules**:

The monitoring bot (Layer 5) applies elevated scrutiny to identity-related announcements:

* **Auto-cancel**: Any `announce()` targeting the Identity Registry's `transferFrom` or `safeTransferFrom` selectors is auto-cancelled unless the recipient is on a pre-approved address list
* **Immediate alert**: All identity-related announcements trigger PagerDuty-level alerts regardless of value
* **Cross-reference**: Monitor for correlated suspicious activity -- e.g., an identity transfer announcement followed by unusual vault withdrawal patterns
* **Guardian notification**: If the agent's guardians are registered, notify them independently of the standard monitoring channels

### 8.6 Emergency Identity Recovery

When key compromise is detected, the protocol activates a tiered response system with decreasing response times. Each tier operates independently -- activation of a higher tier does not require lower tiers to have fired first.

**Tiered Response System**:

| Tier | Mechanism                                        | Response Time | Trigger                                    | Actor                           |
| ---- | ------------------------------------------------ | ------------- | ------------------------------------------ | ------------------------------- |
| 1    | ERC-7265 circuit breaker on vault outflows       | Seconds       | Withdrawal exceeds 2x 7-day moving average | Automated (on-chain)            |
| 2    | Per-token credential freeze (`freezeCredential`) | Minutes       | Guardian or monitoring bot detects anomaly | Guardian / monitoring bot       |
| 3    | Transfer timelock cancel                         | Minutes-hours | Unauthorized transfer detected in queue    | Cancel authority (CANCEL\_ROLE) |
| 4    | Protocol-wide pause (`ERC721Pausable`)           | Minutes       | Systemic attack detected                   | Pause guardian (hot key)        |
| 5    | Identity reissuance                              | Days          | Governance-approved recovery               | Governance multisig             |

**Credential Freeze**:

`freezeCredential(tokenId)` is callable by any designated guardian or by the monitoring bot's address. When frozen:

* All vault operations for this `agentId` revert immediately
* The identity NFT cannot be transferred (even if guardian is disabled)
* The freeze persists until explicitly unfrozen by a guardian or governance action
* Unfreezing requires a separate key from the freeze key (asymmetric access control)

**Identity Reissuance**:

For confirmed compromise scenarios where the identity NFT has already been transferred:

1. Governance multisig approves the reissuance via a dedicated `REISSUE_ROLE`
2. The compromised token is burned (or permanently frozen if burn is not possible)
3. A new identity token is minted to the legitimate agent's new wallet
4. Metadata (handle, agentURI, interface type) is preserved from the original
5. Reputation is partially preserved: base reputation transfers at 50% (the other 50% must be re-earned), reflecting the cost of compromise even in legitimate recovery
6. Soulbound reputation SBTs in the old wallet are not recoverable -- they serve as an audit trail of the compromise event

**Separated Pause/Unpause Keys (Trail of Bits Level 3)**:

Following the Trail of Bits Level 3 access control framework:

| Role              | Threshold       | Timelock       | Key Storage             | Purpose                                       |
| ----------------- | --------------- | -------------- | ----------------------- | --------------------------------------------- |
| Pause guardian    | 1-of-N (low)    | None (instant) | Hot wallet / KMS        | Emergency stop -- speed is critical           |
| Unpause authority | 2-of-3 (medium) | 24 hours       | Cold wallets / hardware | Prevent attacker from re-enabling after pause |
| Core admin        | 3-of-5 (high)   | 7 days         | Cold wallets / hardware | Identity reissuance, parameter changes        |
| Cancel guardian   | 1-of-N (low)    | None (instant) | Hot wallet / KMS        | Veto pending proxy announcements              |

The critical insight: **the pause key and unpause key are stored in different locations with different thresholds**. An attacker who compromises the pause key can only halt operations (denial of service). An attacker who compromises the unpause key cannot unpause without the timelock passing. Both keys must be compromised to weaponize the pause mechanism.

***

## 9. Consolidated Recovery Runbook

This section consolidates all recovery procedures from sections 8.3-8.6, [shared/onboarding-workflow.md](/docs/prd-shared/onboarding-workflow.md) Path C, and [shared/credential-architecture.md](/docs/prd-shared/credential-architecture.md) Section 5 into a single decision tree.

### Recovery Decision Tree

```
What happened?
    |
    |--- API credentials compromised?
    |    --> Revoke at provider dashboard (Privy: console.privy.io)
    |    --> Generate new credentials
    |    --> Update .env, restart MCP server
    |    --> Impact: none (wallet unaffected)
    |
    |--- Session key compromised?
    |    --> Sudo key disables session key
    |    --> Issue new session key
    |    --> Impact: none (wallet address unchanged)
    |
    |--- Operational signing key compromised?
    |    --> Smart contract wallet: setOwner() or swapOwner()
    |    --> Impact: none (address unchanged, reputation preserved)
    |
    |--- All keys compromised, guardians available?
    |    --> Social recovery via guardian threshold (2-of-3)
    |    --> 48-hour mandatory delay
    |    --> Impact: none (address unchanged)
    |
    |--- Identity NFT stolen?
    |    --> Guardian freezes credential immediately
    |    --> Monitoring bot cancels pending transfers
    |    --> If transferred: 30-day reputation decay
    |    --> Governance reissuance: 50% reputation preserved
    |
    |--- All keys lost, no guardians?
    |    --> UNRECOVERABLE. Funds and identity are lost.
    |    --> This is why guardian setup is mandatory.
    |
    +--- Provider outage?
         --> Funds safe on-chain
         --> Cannot sign new tx until provider recovers
         --> Guardians can migrate to different provider
```

For the detailed step-by-step procedures, see [shared/credential-architecture.md](/docs/prd-shared/credential-architecture.md) Section 6 (rotation playbook) and [shared/onboarding-workflow.md](/docs/prd-shared/onboarding-workflow.md) Emergency Runbook.

***

## 10. Simplified Policy Setup

Instead of manually writing 40-line JSON policy rules (Sections 3.1-3.4), operators can use role-based templates via the setup CLI. The CLI generates the appropriate policy for the operator's chosen provider.

### Role-Based Policy Templates

| Role            | Allowed Operations                                            | Template                         |
| --------------- | ------------------------------------------------------------- | -------------------------------- |
| `participant`   | Vault deposit/withdraw + USDC approve + ERC-8004 registration | `vault-participant-simple-yield` |
| `manager`       | All participant ops + rebalance + CCA + LP + fee collection   | `vault-manager-full`             |
| `manager-proxy` | Only `announce()` on proxy contract (proxy-enhanced mode)     | `vault-manager-proxy-enhanced`   |
| `creator`       | All manager ops + vault creation + parameter changes          | `vault-creator`                  |

### Usage

```bash
# Generate Privy policy JSON for a vault participant
npx @gotts.ai setup policy --role participant --vault 0x... --provider privy

# Generate Privy policy JSON for a proxy-enhanced vault manager
npx @gotts.ai setup policy --role manager-proxy --vault 0x... --proxy 0x... --provider privy

# Apply policy directly to a Privy wallet
npx @gotts.ai setup policy --role participant --vault 0x... --provider privy --apply
```

The CLI outputs the policy JSON and, if `--apply` is passed, applies it to the Privy wallet via the Privy API. The manual JSON policies in Sections 3.1-3.4 remain the authoritative reference for what each template generates.
