> For the complete documentation index, see [llms.txt](https://docs.zeroauthority.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.zeroauthority.xyz/nova-bot/tools/x402-payment-integration-guide.md).

# x402 Payment Integration Guide

This guide explains how the x402 payment protocol works for Nova Tools — whether you're building an agent, integrating from a dashboard, or calling the API directly.

{% 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 ───│                                 │
```

{% hint 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.
{% endhint %}

***

### Step-by-Step

#### 1. Call the Tool

```bash
curl -X POST https://nova.zeroauthoritydao.com/api/tools/stacks-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": "stacks-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/stacks-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 %}


---

# 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.zeroauthority.xyz/nova-bot/tools/x402-payment-integration-guide.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.
