# x402

## x402  — Pay-Per-Intelligence

{% hint style="warning" %}
**Partial Rollout** — Conversation write overage payments are now supported. Premium model-tier upgrades and full SDK abstractions are still in progress. APIs and interfaces may evolve as rollout continues. [Join our Discord](https://discord.com/invite/join-milo) for updates.
{% endhint %}

### What is this?

Milo will use the [x402 protocol](https://www.x402.org/) to let you pay for smarter AI models on-the-fly. Instead of fixed subscription tiers, you pay per request — upgrade the brain behind any API call by attaching a stablecoin micropayment.

No signup. No billing portal. Just an HTTP header.

### x402 in 30 seconds (for new users)

If this is your first time seeing `402 Payment Required`, the flow is:

1. You send your normal API request.
2. If free quota is exhausted, Milo returns `402` with exact payment requirements (recipient + accepted options).
3. You submit the payment transfer on Solana.
4. You retry the same API request with `X-PAYMENT` that includes:
   * `recipient` (from server response)
   * `asset` + `amount` (from server response)
   * unique one-time `paymentId`
   * confirmed `txSignature` for that payment transfer
5. Milo verifies on-chain and processes the request.

Think of `X-PAYMENT` as a payment receipt attached to the retry request.

### Live Today: Conversation Overage Payments

Conversation write endpoints currently include a free tier and paid overage:

* Free tier: `2` writes per `60s` per API key (shared across conversations)
* Overage response: `402 Payment Required`
* Payment header: `X-PAYMENT`
* Recipient wallet: `TREASURY_WALLET`
* Accepted prices per extra write:
  * `0.25 USDC`
  * `0.01 SOL`
* Anti-replay: include a unique one-time `paymentId` per paid request.
* On-chain verification: include `txSignature` for a confirmed Solana transfer to `TREASURY_WALLET` with matching asset+amount.

When over free quota, Milo returns payment requirements in both headers and JSON `error.details`:

* `X-Payment-Required: true`
* `X-Payment-Header: X-PAYMENT`
* `X-Payment-Recipient: <TREASURY_WALLET>`
* `X-Payment-Options: USDC:0.25,SOL:0.01`
* `X-Payment-Id-Field: paymentId`
* `X-Payment-Tx-Field: txSignature`

When a paid overage retry is accepted (`2xx`), Milo returns:

* `PAYMENT-RESPONSE: <base64-json-settlement>` (x402-style acceptance payload)
* `X-PAYMENT-RESPONSE: <same-value>` (legacy mirror)
* `X-Billing-Mode: payg`

**Paid retry example:**

```bash
curl -X POST https://partners.andmilo.com/api/v1/users/{userId}/conversations/{conversationId}/messages \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -H "X-PAYMENT: {\"recipient\":\"<TREASURY_WALLET>\",\"asset\":\"USDC\",\"amount\":0.25,\"paymentId\":\"pay_001_unique\",\"txSignature\":\"<confirmed-solana-tx-signature>\"}" \
  -d '{ "message": "Continue the analysis." }'
```

### Security Rules (Important)

* Never share a private key or seed phrase with Milo, CLI flags, logs, or support channels.
* Milo only needs proof of payment (`txSignature`) — not wallet secrets.
* Always use the current `402` response to determine recipient and accepted options.
* Do not hardcode payment recipient/amount in autonomous agents without validating server response.
* Use a new one-time `paymentId` for every paid retry (replays are rejected).
* A paid proof is single-use: one overage request only.
* Wait for transaction confirmation before retrying with `txSignature`.
* Treat `X-PAYMENT` values as sensitive operational data; avoid logging full headers in production.

### How it will work

Every Milo API endpoint that involves AI reasoning (conversations, position analysis, auto-trade decisions) will accept an optional x402 payment. When you pay, Milo routes your request to a more capable model with deeper analysis, more tool calls, and longer context.

```
┌──────────┐                    ┌──────────┐                  ┌──────────┐
│  Client  │ ── request ──────► │   Milo   │ ── settle ─────► │  x402    │
│          │                    │   API    │                  │Facilitator│
│          │ ◄── 402 + price ── │          │                  │          │
│          │                    │          │                  │          │
│          │ ── request ──────► │          │ ◄── verified ─── │          │
│          │    + payment       │          │                  │          │
│          │ ◄── 200 + result ─ │          │                  │          │
└──────────┘                    └──────────┘                  └──────────┘
```

1. You call a Milo endpoint as usual
2. If you want the premium model, include the `X-PAYMENT` header with your x402 payment payload
3. Milo verifies the payment via the x402 facilitator on Solana
4. Your request is routed to the upgraded model
5. If you don't pay, you still get the standard model — nothing breaks

### Model Tiers (Planned)

| Tier         | Cost per request    | What you get                                                                             |
| ------------ | ------------------- | ---------------------------------------------------------------------------------------- |
| **Standard** | Free (with API key) | Default model. Fast responses, good for routine tasks                                    |
| **Pro**      | \~$0.01 USDC        | Smarter model. Deeper analysis, more tool calls, better trade reasoning                  |
| **Ultra**    | \~$0.05 USDC        | Best available model. Maximum context, multi-step research, institutional-grade analysis |

Pricing is per-request and settled instantly on Solana in USDC. Final pricing will be announced closer to launch.

### Which endpoints will support it?

| Endpoint                             | Standard (free) | Pro | Ultra |
| ------------------------------------ | :-------------: | :-: | :---: |
| Create conversation (market-analyst) |       yes       | yes |  yes  |
| Create conversation (auto-trader)    |       yes       | yes |  yes  |
| Send message                         |       yes       | yes |  yes  |
| List positions (with PnL analysis)   |       yes       | yes |   —   |
| Auto-trade rebalance decisions       |    automatic    |  —  |   —   |

The auto-trader agent will benefit the most from upgrades — Pro and Ultra models evaluate more signals, consider longer price history, and produce more detailed theses before entering or exiting positions.

### Quick Example (Planned)

Once live, upgrading a request will look like this:

**Standard request (free):**

```bash
curl -X POST https://partners.andmilo.com/api/v1/users/{userId}/conversations \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Analyze JUP for me",
    "agentType": "market-analyst"
  }'
```

**Pro request (with x402 payment):**

```bash
curl -X POST https://partners.andmilo.com/api/v1/users/{userId}/conversations \
  -H "X-API-Key: $API_KEY" \
  -H "X-PAYMENT: <x402-payment-payload>" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Analyze JUP for me",
    "agentType": "market-analyst"
  }'
```

Same endpoint. Same request body. The only difference is the `X-PAYMENT` header. Premium tier routing is not live yet — we will announce rollout timing.

### SDK Integration (Coming Soon)

We're building SDK wrappers that handle payment construction automatically. You'll set a budget and the SDK handles the rest.

#### JavaScript / TypeScript

```typescript
import { MiloClient } from '@milo/sdk';

const milo = new MiloClient({
  apiKey: 'mk_live_...',
  wallet: yourSolanaKeypair,     // signs x402 payments
  modelTier: 'pro',              // default tier for all requests
  maxSpendPerRequest: 0.05,      // safety cap in USDC
});

// Automatically attaches x402 payment at the "pro" tier
const conversation = await milo.conversations.create({
  userId: 'uuid',
  message: 'Deep dive on RENDER — fundamentals, technicals, and risk',
  agentType: 'market-analyst',
});

// Override tier for a single request
const analysis = await milo.conversations.create({
  userId: 'uuid',
  message: 'Full portfolio risk assessment with correlation analysis',
  agentType: 'auto-trader',
}, { tier: 'ultra' });

// Poll for response (same as before)
const messages = await milo.conversations.getMessages({
  userId: 'uuid',
  conversationId: conversation.conversationId,
});
```

> **Status:** Coming soon. The SDK will wrap `@x402/svm` for Solana payment construction and handle retry logic when the facilitator returns settlement confirmation.

#### Python

```python
from milo import MiloClient

milo = MiloClient(
    api_key="mk_live_...",
    wallet=solana_keypair,
    model_tier="pro",
    max_spend_per_request=0.05,
)

conversation = milo.conversations.create(
    user_id="uuid",
    message="What's the best DePIN play right now?",
    agent_type="market-analyst",
)

# Override tier for this call
conversation = milo.conversations.create(
    user_id="uuid",
    message="Rebalance my portfolio for a risk-off environment",
    agent_type="auto-trader",
    tier="ultra",
)
```

> **Status:** Coming soon.

#### Raw HTTP (via x402 libraries)

Once Milo endpoints support x402, you'll also be able to use any x402 client library (`@x402/fetch`, `@x402/axios`) directly without the Milo SDK:

```typescript
import { paymentRequiredFetch } from '@x402/fetch';

const response = await paymentRequiredFetch(
  'https://partners.andmilo.com/api/v1/users/{userId}/conversations',
  {
    method: 'POST',
    headers: {
      'X-API-Key': apiKey,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      message: 'Analyze JUP for me',
      agentType: 'market-analyst',
    }),
  },
  { wallet: yourSolanaKeypair }
);
```

The x402 fetch wrapper handles the 402 → payment → retry flow automatically.

> **Status:** Coming soon for premium tier upgrades. Conversation overage payments are already supported.

### Spending Controls (Coming Soon)

The SDK will include safety rails so autonomous agents don't overspend:

| Setting              | Description                                             |
| -------------------- | ------------------------------------------------------- |
| `maxSpendPerRequest` | Max USDC per single API call                            |
| `maxSpendPerHour`    | Hourly budget cap                                       |
| `maxSpendPerDay`     | Daily budget cap                                        |
| `modelTier`          | Default tier (`standard`, `pro`, `ultra`)               |
| `autoUpgrade`        | Auto-upgrade to Pro if Standard response quality is low |

### Why x402?

* **No subscriptions** — Pay only for what you use
* **Instant settlement** — Payments settle on Solana in \~400ms
* **Agent-native** — Your trading bot can decide when to pay for better analysis
* **Transparent pricing** — Cost is per-request, visible before you pay
* **Backward compatible** — Standard tier always works without payment

### Roadmap

| Feature                                                       | Status      |
| ------------------------------------------------------------- | ----------- |
| Conversation write overage payments (`2/min` free, then paid) | Live        |
| x402 payment verification on API                              | Coming soon |
| Pro tier (conversations, analysis)                            | Coming soon |
| Ultra tier (deep research, portfolio review)                  | Coming soon |
| TypeScript SDK (`@milo/sdk`)                                  | Coming soon |
| Python SDK                                                    | Coming soon |
| Spending controls & budget caps                               | Coming soon |
| Auto-upgrade (smart tier selection)                           | Coming soon |
| Pay-per-trade execution priority                              | Planned     |

### Get Notified

Want early access? [Join our Discord](https://discord.gg/andmilo) and ask about the x402 beta.
