> ## Documentation Index
> Fetch the complete documentation index at: https://docs.arouter.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# x402 Agent Payments

> Let AI agents with crypto wallets automatically top up credits and authenticate — no registration, no dashboard, fully autonomous.

ARouter supports the [x402 payment protocol](https://x402.org), the open standard for HTTP-native payments.
AI agents with crypto wallets can authenticate, pay for credits, and make LLM requests —
all without registering an account or logging into a dashboard.

## Three Entry Points

ARouter provides three ways for agents to get started. API key users and wallet users now follow separate long-term paths:

| Entry Point               | Auth Method                          | Use Case                                                                          |
| ------------------------- | ------------------------------------ | --------------------------------------------------------------------------------- |
| **Standard x402 Payment** | `PAYMENT-SIGNATURE` header only      | Any x402 client — first wallet payment registers account and returns a wallet JWT |
| **SIWx Authentication**   | `SIGN-IN-WITH-X` header              | Prove wallet ownership → get wallet JWT (no payment)                              |
| **API Key**               | `Authorization: Bearer lr_live_xxxx` | Existing API key users — insufficient balance returns `403`, no x402 auto-topup   |

<Info>
  Standard x402 mode works with **any x402-compatible tool** — `@x402/fetch`, `awal`, MCP wallets, Chrome extensions.
  No ARouter SDK required.
</Info>

***

## How It Works

### Standard x402 (Any x402 Client)

The simplest entry point. Any wallet with USDC can make LLM requests immediately:

```mermaid theme={null}
sequenceDiagram
    participant Wallet as Any Wallet
    participant Client as x402 Client (@x402/fetch)
    participant GW as ARouter Gateway
    participant Chain as Base / Solana

    Client->>GW: POST /v1/chat/completions (no auth)
    GW-->>Client: 402 + PAYMENT-REQUIRED
    Client->>Wallet: Sign USDC payment (gasless EIP-3009)
    Wallet-->>Client: Signed payment
    Client->>GW: Retry + PAYMENT-SIGNATURE
    GW->>Chain: Verify & settle
    GW-->>Client: 200 OK + PAYMENT-RESPONSE(jwt)
    Note over Client: Save wallet JWT for future requests
```

1. Send a request with **no API key** — the gateway returns **HTTP 402** with payment options.
2. The x402 client signs a USDC payment (gasless via EIP-3009).
3. Retry the request with the `PAYMENT-SIGNATURE` header.
4. The gateway verifies, settles, creates your account, and returns the response.
5. The `PAYMENT-RESPONSE` header contains a `jwt` extension for future wallet-authenticated requests.

### SIWx Authentication (Wallet Sign-In)

Prove wallet ownership to get a wallet JWT without paying first:

```mermaid theme={null}
sequenceDiagram
    participant Wallet as Any Wallet
    participant Client as Client
    participant Auth as POST /v1/x402/auth

    Client->>Wallet: Sign CAIP-122 message
    Wallet-->>Client: Signature
    Client->>Auth: SIGN-IN-WITH-X header
    Auth-->>Client: {"jwt": "eyJ..."}
    Note over Client: Use Bearer JWT for wallet requests
```

SIWx follows the [CAIP-122 standard](https://chainagnostic.org/CAIPs/caip-122) — the same protocol used by QuickNode and other x402-enabled services.

### API Key Users

Existing API key users continue to use the standard ARouter API key flow:

```mermaid theme={null}
sequenceDiagram
    participant Agent as AI Agent + Wallet
    participant GW as ARouter Gateway
    participant Chain as Base / Solana

    Agent->>GW: POST /v1/chat/completions (Bearer token)
    GW-->>Agent: 403 insufficient_credits
    Note over Agent: Top up through Dashboard / Stripe / traditional billing
```

***

## Supported Networks

| Network                | CAIP-2 Identifier                         | Token |
| ---------------------- | ----------------------------------------- | ----- |
| Base Mainnet           | `eip155:8453`                             | USDC  |
| Base Sepolia (testnet) | `eip155:84532`                            | USDC  |
| Solana Mainnet         | `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp` | USDC  |
| Solana Devnet          | `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` | USDC  |

## Wallet Compatibility

All wallets work — **no private key export required**:

| Wallet                | Payment (EIP-3009) | Auth (SIWx) | Needs Private Key? |
| --------------------- | ------------------ | ----------- | ------------------ |
| MetaMask              | ✓                  | ✓           | No                 |
| Coinbase Wallet       | ✓                  | ✓           | No                 |
| Coinbase Agent Wallet | ✓                  | ✓           | No (CDP API)       |
| Phantom (Solana)      | ✓                  | ✓           | No                 |
| Local private key     | ✓                  | ✓           | Yes                |

***

## SDK Usage

### Standard x402 (No ARouter SDK Needed)

Use Coinbase's official `@x402/fetch` directly:

```typescript theme={null}
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client } from "@x402/core/client";
import { ExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";

const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const client = new x402Client();
client.register("eip155:*", new ExactEvmScheme(signer));

const paidFetch = wrapFetchWithPayment(fetch, client);

const resp = await paidFetch("https://api.arouter.ai/v1/chat/completions", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "openai/gpt-5.4",
    messages: [{ role: "user", content: "Hello" }],
  }),
});
```

### SIWx Authentication (Get Wallet JWT)

#### Node.js SDK

```typescript theme={null}
import { ARouter, authenticateWithSIWx } from "@arouter/sdk";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);

const { jwt } = await authenticateWithSIWx(
  "https://api.arouter.ai",
  { address: account.address, signMessage: (msg) => account.signMessage({ message: msg }) },
);

const client = new ARouter({ baseURL: "https://api.arouter.ai", apiKey: jwt });
```

#### Go SDK

```go theme={null}
import arouter "github.com/arouter-ai/arouter-go"

signer := arouter.NewEvmWalletSigner(privateKey)
result, err := arouter.AuthenticateWithSIWx(ctx, "https://api.arouter.ai", signer, nil)

client := arouter.NewClient("https://api.arouter.ai", result.JWT)
```

### ARouter SDK + Auto Payment (Recommended for High-Frequency)

#### Go SDK — EVM (Base)

```go theme={null}
import (
    "github.com/ethereum/go-ethereum/crypto"
    arouter "github.com/arouter-ai/arouter-go"
)

key, _ := crypto.HexToECDSA("your-private-key-hex")

client := arouter.NewClient(
    "https://api.arouter.ai",
    "",  // no API key needed
    arouter.WithX402CoinbasePayment(key),
)
```

`WithX402CoinbasePayment` sets up wallet x402 payment with JWT caching:

* first successful payment returns a wallet JWT inside `PAYMENT-RESPONSE`
* subsequent requests use `Bearer <jwt>`
* `401` triggers SIWx re-authentication
* `402` triggers x402 payment

#### Go SDK — Solana

```go theme={null}
solanaKey := ed25519.PrivateKey(yourKeyBytes)
client := arouter.NewClient("https://api.arouter.ai", "",
    arouter.WithX402SolanaPayment(solanaKey),
)
```

#### Node.js SDK — EVM (Base)

```typescript theme={null}
import { ARouter, withX402EvmPayment } from "@arouter/sdk";
import { privateKeyToAccount } from "viem/accounts";

const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const client = withX402EvmPayment(
  new ARouter({ baseURL: "https://api.arouter.ai", apiKey: "" }),
  signer,
);
```

#### Node.js SDK — Dual-Chain (EVM + Solana)

```typescript theme={null}
import { ARouter, withX402Payment } from "@arouter/sdk";

const client = withX402Payment(
  new ARouter({ baseURL: "https://api.arouter.ai", apiKey: "" }),
  {
    evm: { signer: evmAccount },
    solana: { signer: solanaSigner },
  },
);
```

### GET Endpoint for CLI Tools

For x402 CLI tools like `awal` that cannot send POST bodies:

```
GET /v1/x402/chat?model=openai/gpt-5.4&message=Hello&system=Be+brief&max_tokens=100
```

| Parameter     | Required | Description                       |
| ------------- | -------- | --------------------------------- |
| `model`       | Yes      | Model name, e.g. `openai/gpt-5.4` |
| `message`     | Yes      | User message text                 |
| `system`      | No       | System prompt                     |
| `max_tokens`  | No       | Maximum output tokens             |
| `temperature` | No       | Temperature parameter             |
| `stream`      | No       | Set to `true` for streaming       |

***

## Payment Headers

| Header              | Direction       | Description                                                                    |
| ------------------- | --------------- | ------------------------------------------------------------------------------ |
| `PAYMENT-REQUIRED`  | Server → Client | Base64-encoded payment options (amount, wallet, network).                      |
| `PAYMENT-SIGNATURE` | Client → Server | Base64-encoded signed payment payload.                                         |
| `SIGN-IN-WITH-X`    | Client → Server | Base64-encoded SIWx authentication proof.                                      |
| `PAYMENT-RESPONSE`  | Server → Client | Base64-encoded settlement result. ARouter adds a `jwt` field for wallet users. |

## How Credits Work

* x402 payments are deposited as **credits** into your tenant balance — the same pool used by Stripe and Helio payments.
* All x402 transactions appear in the **Billing** page under transaction history with the `x402_topup` reference type.
* The gateway deducts credits per-request as usual after the balance is topped up.
* Wallet users are billed by tenant, authenticated by wallet JWT, and can re-authenticate via SIWx without exposing raw API keys.

## Security

* **Standard x402 protocol**: Uses Coinbase's official x402 SDK for verification and settlement.
* **Facilitator verification**: Payments are cryptographically verified via the [x402 Facilitator](https://x402.org) before credits are granted.
* **Gasless payments**: EIP-3009 (TransferWithAuthorization) — users sign, the Facilitator submits on-chain.
* **Amount cap**: Single payments are capped to prevent unexpectedly large charges.
* **Idempotency**: Each payment payload has a unique nonce — the same signature cannot be replayed.
* **SIWx standard**: Authentication follows [CAIP-122](https://chainagnostic.org/CAIPs/caip-122) with EIP-4361 (EVM) and SIWS (Solana) message formats.
* **Audit trail**: All x402 top-ups are recorded in transaction history alongside Stripe/Helio payments.
* **Non-custodial**: USDC goes directly to the receiving wallet. The Facilitator never holds funds.
