# x402 agent payments

Price HTTP API operations for AI assistants using x402 v1 HTTP 402 challenges, X-PAYMENT verification, atomic replay ledgers, and machine-readable /pricing.md discovery.

Subscription portals and credit-card checkout forms work for human buyers, not for an autonomous assistant making a one-off paid API call. Ferrite supports **x402 version 1** directly across `agent-ready` and `payments`: you attach a micro-dollar price to any `Surface` operation, and Ferrite advertises the price in OpenAPI and `/pricing.md`, returns standard HTTP `402` payment challenges, verifies incoming `X-PAYMENT` payloads, prevents nonce replay atomically in your store, and returns an `X-PAYMENT-RESPONSE` receipt.

## Price an operation in `Surface`

Install `agent-ready` and `payments`:

```bash
ferrite add agent-ready
ferrite add payments
```

Set `price_micros` on any `Operation` in your `Surface` (`1_000_000` equals `$1.00` USD, matching 6-decimal USDC atomic units on Base):

```rust filename="src/surface.rs"
use crate::agent_ready::surface::Operation;
use ferrite_app::serde_json::json;

let premium_quote = Operation {
    name: "get_premium_quote".into(),
    method: "GET".into(),
    path: "/api/quotes/premium".into(),
    description: "Return an annotated market quote. Priced at $0.01 via x402.".into(),
    input_schema: Some(json!({
        "type": "object",
        "properties": { "symbol": { "type": "string" } },
        "required": ["symbol"],
        "additionalProperties": false
    })),
    output_schema: None,
    read_only: true,
    idempotent: true,
    price_micros: 10_000,
};
```

From that single declaration, `agent-ready` automatically emits:

- `x-price-usd-micros: 10000` and a `402` Payment Required response schema in `/.well-known/api-catalog` and `/openapi.json`.
- A human- and agent-readable price table at `GET /pricing.md`.

## Enforce payment before serving

Gate the route handler with `payments::x402_gate::require_payment`. The gate runs three steps in strict order:

1. **Challenge unpaid requests.** If `X-PAYMENT` is absent or malformed, respond with HTTP `402` and the JSON `challenge_body` listing `x402Version: 1`, `scheme: "exact"`, `network: "base"`, `asset` (Base USDC `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`), `maxAmountRequired`, `payTo`, and `resource`.
2. **Verify before touching the ledger.** Decode `X-PAYMENT` and validate the EIP-3009 authorization fields, payee binding, amount, and validity window against `ctx.now_ms() / 1000` via your `Facilitator` implementation (`LocalVerifier` checks an HMAC-SHA-256 settlement tag keyed by `ctx.secret("x402-facilitator-key")`; a custom `Facilitator` submits `x402::facilitator_verify_body` and `x402::facilitator_settle_body` to an external facilitator over a declared egress handle).
3. **Claim the nonce atomically before serving.** Record the verified payment nonce in the store-backed `ReplayLedger` using compare-and-set (`put_if_version(expected = None)`). Exactly one concurrent presentation of a nonce succeeds; duplicates fail with `402`. Only after the nonce commits does your handler produce the response and attach the base64 JSON `X-PAYMENT-RESPONSE` header.

Forward `x-payment` in `ferrite.json` so the gateway delivers the payment header to your application:

```json filename="ferrite.json (excerpt)"
{
  "prefix": "/api/",
  "binding": "requests",
  "kind": "api",
  "forward_headers": ["accept", "x-payment"]
}
```

## Security boundaries and settlement scope

- **Fail-closed defaults.** If the store replay ledger cannot answer, or if the facilitator secret is missing, every paid request is rejected with `402`. Never serve paid data on a ledger error.
- **Verify before recording nonces.** `require_payment` validates the payment before inserting its nonce into the store so unauthenticated callers cannot fill your replay ledger with attacker-chosen nonces.
- **On-chain broadcast belongs to your facilitator.** Constrained Ferrite applications do not hold blockchain RPC keys or broadcast transactions directly. Wire an external x402 facilitator URL as an explicit HTTPS egress destination in `ferrite.json`, store the facilitator credential as a write-only secret, and call `x402::facilitator_settle_body` through `Facilitator::settle`.

## Verify locally

Start your application with `ferrite dev` and confirm both price discovery and the `402` challenge:

```bash
curl -s http://127.0.0.1:8787/pricing.md
curl -i "http://127.0.0.1:8787/api/quotes/premium?symbol=FERR"
```

Confirm that the unpaid request answers `HTTP/1.1 402 Payment Required` with `x402Version: 1` and an `accepts` array naming your `payTo` address and `maxAmountRequired`.

## Next steps

- Inspect the complete OpenAPI schema generation in [OpenAPI and structured errors](/developers/openapi/).
- Check your `402` challenge automatically with `agent-score` and `agent-conformance` in [Verify agent readiness](/developers/agent-readiness-verification/).
- See all declaration options on `Surface` in [Agent-ready apps](/developers/agent-native-apps/).
