# x402 Payment Integration Guide

{% hint style="info" %}
x402 is an HTTP-native payment protocol. Payment happens inline with the API call — no pre-registration, no API keys, no subscriptions needed.
{% endhint %}

***

### How It Works

The x402 protocol uses three HTTP headers to negotiate payment:

| Header              | Direction                       | Content                             |
| ------------------- | ------------------------------- | ----------------------------------- |
| `payment-required`  | Server → Client (402 response)  | Base64-encoded payment requirements |
| `payment-signature` | Client → Server (retry request) | Base64-encoded signed payment       |
| `payment-response`  | Server → Client (200 response)  | Base64-encoded settlement receipt   |

#### Flow Diagram

````
Client                                Server                         AIBTC Facilitator
  │                                      │                                 │
  │─── POST /api/tools/:slug/run ──────>│                                 │
  │                                      │                                 │
  │<── 402 + payment-required header ───│                                 │
  │                                      │                                 │
  │  (client signs tx in wallet)         │                                 │
  │                                      │                                 │
  │─── POST /run + payment-signature ──>│                                 │
  │                                      │─── POST /verify ──────────────>│
  │                                      │<── { isValid: true } ─────────│
  │                                      │                                 │
  │                                      │  (executes tool)               │
  │                                      │                                 │
  │                                      │─── POST /settle ──────────────>│
  │                                      │<── { success, txid } ─────────│
  │                                      │                                 │
  │<── 200 + payment-response header ───│                                 │
```<div data-gb-custom-block data-tag="hint" data-style='success'>**Key safety feature**: Settlement only happens AFTER successful tool execution. If the tool fails, payment is never settled — your wallet is not charged.</div>---

## Step-by-Step

### 1. Call the Tool

```bash
curl -X POST https://nova.zeroauthoritydao.com/api/tools/token-analytics/run \
  -H "Content-Type: application/json" \
  -d '{"input": {"token": "WELSH"}}'
````

#### 2. Receive 402 Response

```http
HTTP/1.1 402 Payment Required
payment-required: eyJ4NDAyVmVyc2lvbiI6Mi4uLn0=
Content-Type: application/json

{
  "error": "PAYMENT_REQUIRED",
  "tool": {
    "slug": "token-analytics",
    "name": "Deep Token Analytics",
    "price_sats": 500
  },
  "accepts": [
    {
      "scheme": "exact",
      "network": "stacks:mainnet",
      "asset": "STX",
      "amount": "5000",
      "payTo": "SP...",
      "maxTimeoutSeconds": 300,
      "display": "~0.0050 STX"
    },
    {
      "scheme": "exact",
      "network": "stacks:mainnet",
      "asset": "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token",
      "amount": "500",
      "payTo": "SP...",
      "maxTimeoutSeconds": 300,
      "display": "500 sats"
    },
    {
      "scheme": "exact",
      "network": "stacks:mainnet",
      "asset": "SP120SBRBQJ00MCWS7TM5R8WJNTTKD5K0HFRC2CNE.usdcx",
      "amount": "250",
      "payTo": "SP...",
      "maxTimeoutSeconds": 300,
      "display": "~$2.50"
    }
  ]
}
```

#### 3. Sign Payment

Build a Stacks transaction for the chosen token. The transaction must be:

* **Sponsored** (`sponsored: true`) — the AIBTC relay pays gas fees
* **Zero fee** (`fee: 0n`) — sponsor covers it

```typescript
import { makeSTXTokenTransfer } from '@stacks/transactions'

const tx = await makeSTXTokenTransfer({
  recipient: accept.payTo,
  amount: BigInt(accept.amount),
  senderKey: privateKey,
  network: 'mainnet',
  sponsored: true,
  fee: 0n,
})

const paymentPayload = {
  txid: tx.txid(),
  asset: 'STX',
  amount: accept.amount,
  from: senderAddress,
  to: accept.payTo,
  network: 'stacks:mainnet',
}

const paymentSignature = btoa(JSON.stringify(paymentPayload))
```

#### 4. Retry with Payment

```bash
curl -X POST https://nova.zeroauthoritydao.com/api/tools/token-analytics/run \
  -H "Content-Type: application/json" \
  -H "payment-signature: eyJ0eGlkIjoiMHguLi4ifQ==" \
  -d '{"input": {"token": "WELSH"}}'
```

#### 5. Receive Results

```http
HTTP/1.1 200 OK
payment-response: eyJzdWNjZXNzIjp0cnVlLC4uLn0=
Content-Type: application/json

{
  "runId": "uuid",
  "status": "completed",
  "output": {
    "fetch_token_data": { ... },
    "fetch_market_tokens": { ... }
  }
}
```

***

### Supported Payment Tokens

All payments are on **Stacks mainnet**.

| Token | Contract                                               | Unit                              |
| ----- | ------------------------------------------------------ | --------------------------------- |
| STX   | Native                                                 | microSTX (1 STX = 1,000,000 uSTX) |
| sBTC  | `SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token` | satoshis                          |
| USDCx | `SP120SBRBQJ00MCWS7TM5R8WJNTTKD5K0HFRC2CNE.usdcx`      | base units                        |

***

### Error Handling

| HTTP Status | Error Code          | Meaning                                               |
| ----------- | ------------------- | ----------------------------------------------------- |
| 402         | `PAYMENT_REQUIRED`  | Payment needed — see `accepts[]` for options          |
| 400         | `PAYMENT_INVALID`   | Payment signature invalid or verification failed      |
| 400         | `VALIDATION_ERROR`  | Tool input validation failed                          |
| 401         | `IDENTITY_REQUIRED` | Must provide JWT or `X-STACKS-ADDRESS` for free tools |
| 429         | `RATE_LIMITED`      | Too many requests — wait and retry                    |

***

### AIBTC Facilitator

Nova uses the [AIBTC x402 Sponsor Relay](https://x402-relay.aibtc.com) for payment verification and settlement. The facilitator:

* Verifies payment signatures match requirements
* Sponsors transaction gas fees (gasless for the payer)
* Broadcasts transactions to Stacks mainnet
* Returns settlement receipts with txid

The facilitator is **non-custodial** — it can only execute transactions the client has already signed.

***

### Premium Users

Nova Premium subscribers bypass x402 entirely. Authenticate with a JWT token and all tools are free with no per-call payment.

{% hint style="info" %}
Get [Nova Premium](https://nova.zeroauthoritydao.com/premium) for unlimited access to all tools.
{% endhint %}
