> For the complete documentation index, see [llms.txt](https://docs.grandprotocol.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.grandprotocol.org/platform/architecture.md).

# Architecture & API Reference

This page describes how Grand Protocol is built and how a payment flows through the platform from your agent to the target service and back.

***

## Overview

Grand Protocol is built in three layers: a **gateway** that handles protocol detection and policy enforcement, a **protocol layer** that implements x402 and MPP payment handshakes, and a **Robinhood Chain settlement layer** that records every transaction on-chain.

***

## Technology stack

| Layer            | Technology           | Rationale                                                              |
| ---------------- | -------------------- | ---------------------------------------------------------------------- |
| Gateway API      | Go                   | Low latency, high concurrency, minimal memory overhead                 |
| x402 handler     | Go                   | EIP-712 typed-data signing (secp256k1) via standard Ethereum libraries |
| MPP handler      | Go                   | Session management and multi-rail support                              |
| Smart contracts  | Solidity + Foundry   | On-chain wallet registry and transaction ledger on Robinhood Chain     |
| Settlement token | USDC (ERC-20)        | Most widely adopted stablecoin on EVM networks                         |
| Session store    | Redis                | Sub-millisecond MPP session cache                                      |
| State store      | PostgreSQL           | Agent registry, policy store, account state                            |
| Dashboard        | Next.js + TypeScript |                                                                        |

***

## Payment flow

Every `POST /v1/pay` request follows this path:

```
Agent sends POST /v1/pay
        │
        ▼
Grand Protocol Gateway
  - API key authentication
  - TLS termination
  - Rate limiting (per account)
        │
        ▼
Policy Engine
  - Checks domain allowlist / blocklist
  - Checks per-call spend limit
  - Checks daily budget remaining
  - Checks rate limit window
  - Rejects here if any check fails (no funds spent)
        │
        ▼
Protocol Detector
  - Sends original request to target endpoint
  - Receives 402 response
  - Reads response to determine x402 or MPP
        │
        ├── x402 ───────────────────────────────────────────────────────┐
        │                                                               │
        │   x402 Handler                                                │
        │   - Parses PaymentRequired object                             │
        │   - Constructs PaymentPayload                                 │
        │   - Signs with agent key (EIP-712, secp256k1)                 │
        │   - Retransmits original request with X-PAYMENT header        │
        │   - Receives 200 response from resource server                │
        │                                                               │
        └── mpp ──────────────────────────────────────────────────────┐ │
                                                                      │ │
            MPP Handler                                               │ │
            - Checks session cache for existing session               │ │
            - If no session: negotiates new session via Tempo rail    │ │
            - Authorizes payment with session credential              │ │
            - Receives 200 response from resource server              │ │
                                                                      │ │
        ◄─────────────────────────────────────────────────────────────┘ │
        ◄───────────────────────────────────────────────────────────────┘
        │
        ▼
Robinhood Chain Settlement Bridge
  - Constructs ERC-20 USDC transfer from the agent's contract wallet
  - Signs with agent key
  - Submits to Robinhood Chain mainnet (chain ID 4663)
  - Waits for block confirmation (100ms block time)
  - Writes on-chain ledger record to the GrandProtocol.sol ledger contract
        │
        ▼
Response returned to agent
  - PaymentResult with status, data, txHash, amountPaid, protocol
```

***

## Smart contracts: GrandProtocol.sol

The Grand Protocol contracts on Robinhood Chain handle:

**Wallet registry** Each agent wallet is a smart contract wallet deployed by the Grand Protocol factory contract using `CREATE2`, with the agent ID as the salt. The address is deterministic and the wallet holds USDC directly as an ERC-20 balance.

**Transaction ledger** Every payment writes a ledger entry containing:

* Agent wallet address
* Payee address
* USDC amount (uint256, 6 decimal places)
* Protocol (x402 or MPP, stored as enum)
* Endpoint hash (SHA256 of the endpoint URL)
* Timestamp (Unix epoch, uint64)
* Parent transaction hash (for multi-agent chains, or zero)
* Policy check result

**Payment function** The payment function:

1. Verifies the transaction is signed by the agent's key
2. Transfers USDC from the agent's wallet to the payee via an ERC-20 transfer
3. Writes the ledger entry
4. Emits a `PaymentRecorded` event for the dashboard indexer

***

## Spend policy enforcement

Policies are enforced in two places:

**Gateway layer (primary):** Before any request is sent to the target endpoint. Fast rejection with no network cost and no on-chain fee.

**On-chain layer (high-value transactions):** For transactions above a configurable threshold, the policy is also encoded into the transaction calldata and verified by the on-chain contract. This ensures that even if the gateway were bypassed, the contract would reject the transfer.

The default high-value threshold is 10 USDC per transaction. Enterprise accounts can configure this.

***

## MPP session store

MPP sessions are cached in Redis with a TTL matching the session's expiry. The key is `{agentId}:{serviceDomain}`. On cache miss, the MPP handler negotiates a new session with the service, stores it, and proceeds.

Sessions are not stored on-chain. Only the final payment settlement is on-chain.

***

## Dashboard indexer

A lightweight indexer subscribes to contract events over a Robinhood Chain WebSocket JSON-RPC log subscription and writes denormalized records to the dashboard read database. The indexer runs with a one-second lag target. If the indexer falls behind, the dashboard shows a staleness indicator and instructs users to check the Robinhood Chain explorer directly.

***

## Data residency

By default, Grand Protocol stores off-chain state (agent registry, policy store, MPP sessions) in the United States. On-chain data (wallet balances, transaction ledger) is global, replicated by every Robinhood Chain node, and posted to Ethereum.

Enterprise plans can request off-chain data residency in:

* European Union (Frankfurt)
* United Kingdom (London)
* Asia Pacific (Singapore)

Contact support to configure data residency for your account.

***

## Key management

Agent wallet signing keys are stored encrypted in Grand Protocol's key management service (KMS). The KMS uses envelope encryption: each key is encrypted with a per-account key, which is itself encrypted with a root KMS key.

The private key is decrypted in memory only at the point of signing a Robinhood Chain transaction. It is never written to disk unencrypted and never transmitted outside the signing process.

Enterprise accounts can bring their own KMS key (BYOK). See [Security](/platform/security.md) for details.

***

## REST API reference

All endpoints are under `https://api.grandprotocol.org/v1`. Every request requires `Authorization: Bearer <key>`.

### Wallets

| Method | Path                             | Description                                                 |
| ------ | -------------------------------- | ----------------------------------------------------------- |
| `POST` | `/v1/wallets`                    | Create an agent wallet                                      |
| `GET`  | `/v1/wallets/{agentId}`          | Get wallet balance and address                              |
| `POST` | `/v1/wallets/{agentId}/fund`     | Fund a wallet from your account's configured funding source |
| `POST` | `/v1/wallets/{agentId}/withdraw` | Withdraw USDC to an external Robinhood Chain address        |
| `POST` | `/v1/wallets/import`             | Import an existing secp256k1 private key                    |

### Payments

| Method | Path                | Description                                    |
| ------ | ------------------- | ---------------------------------------------- |
| `POST` | `/v1/pay`           | Make a payment — protocol auto-detected        |
| `POST` | `/v1/agents/invoke` | Invoke a sub-agent with an optional budget cap |

### Policies

| Method | Path                     | Description                                   |
| ------ | ------------------------ | --------------------------------------------- |
| `PUT`  | `/v1/policies/{agentId}` | Set or replace spend policies                 |
| `GET`  | `/v1/policies/{agentId}` | Get current spend policies and usage counters |

### Transactions

| Method | Path                              | Description                                                                     |
| ------ | --------------------------------- | ------------------------------------------------------------------------------- |
| `GET`  | `/v1/transactions`                | List transactions; filter by `agentId`, `protocol`, `domain`, `since`, `status` |
| `GET`  | `/v1/transactions/{txHash}`       | Get a single transaction                                                        |
| `GET`  | `/v1/transactions/{txHash}/chain` | List all transactions in a multi-agent chain                                    |
| `GET`  | `/v1/transactions/{txHash}/tree`  | Get the full payment tree with cost rollup                                      |

### Sessions

| Method   | Path           | Description                                      |
| -------- | -------------- | ------------------------------------------------ |
| `GET`    | `/v1/sessions` | List active MPP sessions for an agent            |
| `DELETE` | `/v1/sessions` | Clear sessions; filter by `agentId` and `domain` |

### Metrics

| Method | Path                           | Description                                                                        |
| ------ | ------------------------------ | ---------------------------------------------------------------------------------- |
| `GET`  | `/v1/agents/{agentId}/metrics` | Aggregated spend, tx count, and protocol split; supports `window` and `resolution` |

### Keys and alerts

| Method   | Path               | Description                                            |
| -------- | ------------------ | ------------------------------------------------------ |
| `POST`   | `/v1/keys`         | Create a per-agent API key                             |
| `DELETE` | `/v1/keys/{keyId}` | Revoke an API key                                      |
| `POST`   | `/v1/alerts`       | Create a budget, spend-rate, or policy-violation alert |

***

## Error responses

All API errors return JSON with a machine-readable `error` field:

```json
{
  "error": "policy_violation",
  "reason": "per_call_limit_exceeded",
  "detail": "Requested 2.50 USDC, limit is 1.00 USDC"
}
```

| HTTP status | Meaning                                           |
| ----------- | ------------------------------------------------- |
| `401`       | API key missing or invalid                        |
| `402`       | Payment rejected by policy (see `error` body)     |
| `403`       | Per-agent key used for an account-level operation |
| `429`       | Account-level rate limit exceeded                 |
| `500`       | Internal error                                    |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.grandprotocol.org/platform/architecture.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
