# Architecture

FervusAI is built in layers. The on-chain program on Solana is the authoritative source of truth and enforcement. Everything above it - the API, SDK, and dashboard - is an interface to that program.

***

## System overview

```
┌────────────────────────────────────────────────────────┐
│                    FervusAI Platform                    │
│                                                         │
│  ┌────────────┐  ┌────────────┐  ┌───────────────────┐ │
│  │  REST API  │  │  SDK       │  │  Dashboard (Web)  │ │
│  │  (HTTPS)   │  │  TS / Py   │  │  Operator Console │ │
│  └─────┬──────┘  └─────┬──────┘  └─────────┬─────────┘ │
│        └───────────────┴──────────────────── │           │
│                        │                               │
│              ┌──────────▼──────────┐                   │
│              │    Policy Engine    │                   │
│              │  (validation layer) │                   │
│              └──────────┬──────────┘                   │
│                         │                              │
│              ┌──────────▼──────────┐                   │
│              │  Transaction Builder│                   │
│              │  (Solana tx assembly│                   │
│              └──────────┬──────────┘                   │
└────────────────────────────────────────────────────────┘
                          │
           ┌──────────────▼───────────────────┐
           │         Solana Mainnet            │
           │                                   │
           │  ┌────────────────────────────┐   │
           │  │  FervusAI On-Chain Program  │   │
           │  │  (Rust / Anchor)            │   │
           │  │                             │   │
           │  │  - Wallet PDAs              │   │
           │  │  - Policy enforcement       │   │
           │  │  - Escrow vaults            │   │
           │  │  - Event emission           │   │
           │  └────────────────────────────┘   │
           │                                   │
           │  USDC SPL Token Program            │
           └───────────────────────────────────┘
                          │
           ┌──────────────▼───────────────────┐
           │  Indexing & Events (Helius)        │
           │  - Webhook delivery               │
           │  - Real-time tx monitoring        │
           │  - Balance subscriptions          │
           └───────────────────────────────────┘
```

***

## Core stack

| Layer                | Technology                                 | Rationale                                                                            |
| -------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------ |
| **Blockchain**       | Solana Mainnet                             | 400ms finality, \~$0.001 tx cost, native USDC, institutional validation              |
| **Settlement token** | USDC (SPL)                                 | Stable, Circle-backed, deep liquidity, widely accepted                               |
| **On-chain program** | Rust + Anchor                              | Type-safe Solana program development, PDA account model, auditable                   |
| **Wallet model**     | PDAs (Program Derived Addresses)           | No private key exposure, program-controlled, deterministic derivation                |
| **Indexing**         | Helius                                     | Solana-native, sub-100ms webhooks, DAS API, full transaction history                 |
| **API**              | TypeScript / Node.js                       | Fast iteration, strong Solana SDK ecosystem (`@solana/web3.js`, `@solana/spl-token`) |
| **SDK**              | TypeScript + Python                        | Covers the dominant agent developer stacks                                           |
| **Dashboard**        | Next.js                                    | SSR, edge-deployable, React component model                                          |
| **Micropayments**    | x402 compatible                            | Interop with the emerging agent payment standard                                     |
| **Custody model**    | Non-custodial (PDA) + optional MPC co-sign | Operator retains control; FervusAI cannot unilaterally move funds                    |

***

## The on-chain program

The FervusAI on-chain program is a Rust/Anchor program deployed to Solana Mainnet. Source is in `contracts/programs/fervus/`. It is the authoritative enforcement layer for all wallet operations — no application-layer code can bypass it.

### Account types

**`Organisation`** — Seeds: `["organisation", authority]`. One per operator. Holds the operator authority, total deposited USDC, total allocated across wallets, policy and wallet counts, and a webhook URL for event delivery.

**`Policy`** — Seeds: `["policy", organisation, policy_id]`. One per spending policy. Stores all limit parameters (`max_per_tx`, `max_per_day`, `max_per_month`, `velocity_cap`), rolling counters for each time window, recipient allowlist (up to 16 addresses), blocked category codes (up to 8), the co-sign threshold, and policy expiry. Rolling counters are updated on every successful `execute_payment` call within the same transaction.

**`AgentWallet`** — Seeds: `["wallet", organisation, agent_id]`. One per agent. Stores the bound policy, USDC balance, escrow lock amount, lifetime spend, transaction count, and status (`Active`, `Frozen`, `PolicyViolation`, `Deactivated`). The wallet PDA is the SPL token account authority — it signs transfers via CPI using its seeds.

**`Escrow`** — Seeds: `["escrow", requesting_wallet, nonce]`. One per A2A escrow position. Holds the locked USDC in an associated vault PDA, the task description hash, completion proof hash, dispute reason hash, TTL expiry, and status (`Open`, `Released`, `Refunded`, `Disputed`, `Adjudicated`).

**`SessionToken`** — Seeds: `["session", wallet, session_id]`. Short-lived authority token scoped to a single wallet. Stores the ephemeral `session_authority` public key and `expires_at` timestamp. Prevents the organisation keypair from being exposed at runtime.

### Instructions

| Instruction            | Module         | Description                                                         |
| ---------------------- | -------------- | ------------------------------------------------------------------- |
| `init_organisation`    | `organisation` | Initialise a new operator organisation account and USDC reserve ATA |
| `update_organisation`  | `organisation` | Update label and webhook URL                                        |
| `create_policy`        | `policy`       | Create a spending policy with full parameter set                    |
| `update_policy`        | `policy`       | Update policy parameters — takes effect within one slot             |
| `deactivate_policy`    | `policy`       | Permanently deactivate a policy                                     |
| `provision_wallet`     | `wallet`       | Derive and initialise a new agent wallet PDA                        |
| `fund_wallet`          | `wallet`       | Transfer USDC from organisation reserve to agent wallet             |
| `withdraw_from_wallet` | `wallet`       | Return USDC from wallet to organisation reserve                     |
| `rebind_wallet_policy` | `wallet`       | Bind wallet to a different policy                                   |
| `freeze_wallet`        | `wallet`       | Immediately freeze all outbound transactions                        |
| `unfreeze_wallet`      | `wallet`       | Restore wallet to `Active` status                                   |
| `execute_payment`      | `payment`      | Enforce policy on-chain, execute USDC SPL CPI transfer              |
| `open_escrow`          | `escrow`       | Lock USDC in vault PDA for A2A task payment                         |
| `release_escrow`       | `escrow`       | Verify completion proof, release vault to receiving agent           |
| `refund_escrow`        | `escrow`       | Return vault to requesting agent (cancellation or TTL expiry)       |
| `dispute_escrow`       | `escrow`       | Raise a dispute, pause release                                      |
| `adjudicate_escrow`    | `escrow`       | Split vault between parties (organisation authority only)           |
| `issue_session_token`  | `session`      | Issue a short-lived signing authority for a wallet                  |
| `revoke_session_token` | `session`      | Revoke a session before TTL expires                                 |

### Policy enforcement

`execute_payment` performs all policy checks **atomically** within the same transaction as the USDC SPL token transfer. If any check fails, the entire transaction is rejected — there is no partial execution, no retry, no application-layer fallback.

The check sequence (all evaluated on-chain before the transfer CPI fires):

1. Wallet status is `Active`
2. Policy is active
3. Policy has not expired (`expiry` timestamp)
4. Time windows rolled over if elapsed (hour, day, month)
5. `max_per_tx` — per-transaction ceiling
6. `max_per_day` — rolling 24-hour accumulator
7. `max_per_month` — rolling monthly accumulator
8. `velocity_cap` — maximum transactions per hour
9. `allowed_recipients` — if non-empty, recipient must be listed
10. `blocked_categories` — payment category must not be blocked
11. `require_co_sign_above` — co-sign authority must be present if threshold is met
12. Available balance ≥ payment amount

***

## Wallet derivation

Every FervusAI account address is deterministic and computable client-side before the provisioning instruction is submitted.

```
# Organisation
PDA(seeds: [b"organisation", authority_pubkey], program_id)

# Policy
PDA(seeds: [b"policy", organisation_pubkey, policy_id_16_bytes], program_id)

# Agent wallet
PDA(seeds: [b"wallet", organisation_pubkey, agent_id_32_bytes], program_id)

# A2A escrow
PDA(seeds: [b"escrow", requesting_wallet_pubkey, nonce_u64_le], program_id)

# Session token
PDA(seeds: [b"session", wallet_pubkey, session_id_16_bytes], program_id)
```

This means wallet addresses can be pre-computed and referenced in other systems before they are provisioned on-chain. The `provision_wallet` instruction creates the account; it does not determine the address.

***

## Indexing pipeline

The Helius webhook pipeline:

1. The FervusAI on-chain program emits Solana events (program logs / account change notifications) on every instruction execution.
2. Helius monitors FervusAI program accounts via a persistent subscription and delivers structured webhook payloads within \~100ms of slot confirmation.
3. FervusAI's indexing service receives Helius webhooks, parses the event data, writes to the transaction database, and re-emits as FervusAI-formatted webhook events to operator endpoints.
4. The dashboard WebSocket connection subscribes to the indexing service for live updates.

***

## Session authority model

Session tokens are **on-chain accounts** (`SessionToken` PDA), not JWTs. This is a deliberate security decision: the session authority and its expiry are enforced by the program, not by an application-layer token that could be forged or replayed.

1. The organisation authority calls `issue_session_token`, providing an ephemeral keypair public key and TTL (60 s – 24 h). The `SessionToken` PDA is written on-chain.
2. The agent uses the corresponding ephemeral private key to sign payment transactions.
3. The API layer verifies the `SessionToken` PDA — active, not revoked, not expired — before constructing each transaction.
4. The organisation authority can call `revoke_session_token` at any time to invalidate the session immediately.

Session tokens are scoped to a single wallet. An agent with a valid session for `wallet_A` cannot sign transactions for `wallet_B`.

***

## MPC co-signing

For high-value transactions requiring operator co-sign:

1. The API constructs the Solana transaction and serialises it.
2. The serialised transaction is returned to both the agent and the operator as a `co_sign_payload`.
3. The operator signs the payload using their operator key.
4. Both signatures are combined client-side (2-of-2 threshold signature scheme).
5. The combined signature is submitted with the transaction.

FervusAI's MPC implementation uses a threshold signature scheme rather than multisig at the Solana program level - this keeps transaction size and cost equivalent to a standard single-signature transaction while maintaining the 2-of-2 security property.

In beta, operators can use either the dashboard approval flow or a programmatic signing endpoint. Support for hardware signing keys (Ledger, YubiKey) is on the post-beta roadmap.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.fervusai.com/resources/architecture.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
