# x402 payment rail — pay-per-request RPC in XNO or NANUSD

The Nanswap Nodes RPC proxy accepts anonymous, per-request payment in XNO or
NANUSD (the USD Nano stablecoin) as an alternative to an API key, using an
[x402](https://www.x402.org/)-style HTTP 402 flow. It is designed for AI agents
and machine clients: no signup, no card, no KYC — a funded Nano account is the
credential. Feeless sub-second on-chain settlement makes a $0.00003 API call
economically possible.

Base URL: `https://nodes.nanswap.com`. This document is served at
`GET /x402/docs`.

## How it works

```
client                              proxy                           nano node
  |  POST /XNO {action:...}          |                                  |
  |--------------------------------->|                                  |
  |  402 + quote (accepts[])         |                                  |
  |<---------------------------------|                                  |
  |  sign state send block to payTo  |                                  |
  |  POST /XNO + X-PAYMENT: {block}  |                                  |
  |--------------------------------->|  process + confirm (<1s)         |
  |                                  |--------------------------------->|
  |  200 result                      |  amount -> prepaid credits       |
  |  + X-PAYMENT-RESPONSE: {token}   |                                  |
  |<---------------------------------|                                  |
  |  POST /XNO + X-PAYMENT-TOKEN     |  (cheap: no on-chain wait)        |
  |--------------------------------->|                                  |
```

One on-chain payment buys `amount / basePriceRaw` **credits** held behind an
opaque bearer **token**, so the confirmation wait happens once per top-up, not
once per call. When the token runs out the client gets a fresh 402 quote.

## Pricing

Credits are priced in **USD**: currently $0.00003 per credit (`extra.priceUsdPerCredit`). The
quote has one `accepts[]` entry per payment asset, each with its own `payTo`
and `basePriceRaw` (raw units of that asset per credit):

| asset    | network          | payTo     | basePriceRaw                                                       |
|----------|------------------|-----------|--------------------------------------------------------------------|
| `XNO`    | `nano-mainnet`   | `nano_…`  | USD price converted with the live XNO/USD rate (`data.nanswap.com/nano-price`, refreshed every minute) |
| `NANUSD` | `nanusd-mainnet` | `usd_…`   | 1 NANUSD = $1, 6 decimals → $0.00003 = 30 raw                       |

Both `payTo` addresses are the same key under a different prefix. Credits and
tokens are asset-agnostic: credits bought in NANUSD pay for calls on any
network. A payment is credited at the lowest XNO price quoted during the last
`extra.quoteValiditySeconds` (currently 300s), so a price tick between quote and payment
never short-changes the client. If the XNO price feed is down for longer than
15 minutes, XNO is dropped from the quote and only
NANUSD is accepted.

| action                  | credits |
|-------------------------|---------|
| any read RPC            | 1       |
| `process`               | 5       |
| `work_generate`         | 25      |

The live values are always in the quote (`extra.actionCredits`).

At $0.00003 per credit a read costs 30 raw NANUSD, or ~0.00009 XNO at
$0.33/XNO. Failed requests (HTTP ≥ 400 after the charge) are refunded automatically.
Credits expire after `extra.creditsTtlDays` (currently 90 days).

## Protocol reference

### 402 response

```json
{
  "x402Version": 1,
  "error": "no API key and no payment; pay per request with XNO or NANUSD via x402",
  "accepts": [{
    "scheme": "exact",
    "network": "nano-mainnet",
    "asset": "XNO",
    "payTo": "nano_...",
    "maxAmountRequired": "...",
    "maxTimeoutSeconds": 10,
    "extra": {
      "priceUsdPerCredit": "0.00003",
      "assetUsdPrice": "0.3305",
      "basePriceRaw": "90771558245083207261724660",
      "actionCredits": { "default": 1, "process": 5, "work_generate": 25 },
      "minPaymentRaw": "...",
      "minPaymentRawWithOwnWork": "...",
      "suggestedPaymentRaw": "...",
      "quoteValiditySeconds": 300,
      "workProvided": true,
      "frontierEndpoint": "/x402/frontier/:account",
      "balanceEndpoint": "/x402/balance"
    }
  }, {
    "scheme": "exact",
    "network": "nanusd-mainnet",
    "asset": "NANUSD",
    "payTo": "usd_...",
    "maxAmountRequired": "...",
    "extra": { "priceUsdPerCredit": "0.00003", "assetUsdPrice": "1", "basePriceRaw": "30", "...": "..." }
  }]
}
```

Pick the `accepts[]` entry of the asset you hold. `maxAmountRequired` is the
smallest payment that settles without work for the attempted action (see
minimums below); any larger amount becomes credits for later calls.

### Paying — `X-PAYMENT` header

Base64-encoded JSON (raw JSON is also accepted):

```json
{ "x402Version": 1, "scheme": "exact", "network": "nano-mainnet",
  "payload": { "block": {
    "account": "nano_payer...", "previous": "FRONTIER...",
    "representative": "nano_rep...", "balance": "<balance after send, raw>",
    "link": "<payTo public key>", "signature": "...", "work": ""
} } }
```

* Set `network` to the chosen offer's network (`nano-mainnet` or
  `nanusd-mainnet`); when it is missing the asset is inferred from the payer
  address prefix (`nano_`/`xrb_` → XNO, `usd_` → NANUSD).
* The block must be a **state send** to `payTo` from an **opened** account,
  and its `previous` must be the account's **current frontier** (read it from
  `GET /x402/frontier/:account` right before signing). Anything else is
  rejected before any work or broadcast.
* `work` may be empty: the proxy generates it server-side (`workProvided`). A
  payment without work must be worth at least **25 credits**
  (`extra.minPaymentRaw`), the cost of the work it needs. A block carrying its
  own valid work only needs 1 credit (`extra.minPaymentRawWithOwnWork`).
* Generated work is shared and rate-limited. On `503` retry a few seconds later,
  or include your own work.
* A block you already broadcast yourself is accepted too: the proxy then only
  waits for its confirmation.
* The proxy verifies the signature locally, broadcasts the block, waits for
  confirmation, then credits **the confirmed on-chain amount** (never client
  claims). Send more than one credit's worth to prepay future calls
  (`suggestedPaymentRaw` ≈ 200 credits).
* A successful settle answers the request **and** returns
  `X-PAYMENT-RESPONSE: base64({ success, transaction, token, credits, remaining })`.
  **Store the token immediately** — it is shown exactly once; the block hash
  alone can never be exchanged for a token again (replay protection).

### Spending — token

Either header works on every subsequent request:

```
X-PAYMENT-TOKEN: x402_...
X-PAYMENT: base64({ "payload": { "token": "x402_..." } })
```

Responses carry `X-402-Credits-Remaining`. When credits are insufficient the
proxy answers 402 with the current quote.

### Helper endpoints (no payment needed, IP rate-limited)

| endpoint                     | purpose                                            |
|------------------------------|----------------------------------------------------|
| `GET /x402/docs`             | this document (markdown)                           |
| `GET /x402/quote[?action=x]` | current quote without burning a request            |
| `GET /x402/balance`          | credits left (token via `X-PAYMENT-TOKEN` header)  |
| `GET /x402/frontier/:acct`   | frontier/balance/representative of the payer account, so a fresh client can build its first send block. Network from the prefix (`nano_`, `usd_`) or `?asset=XNO\|NANUSD` |

### Minimal client (node)

```js
const { block } = require('multi-nano-web')
const quote = (await (await fetch(`${BASE}/x402/quote`)).json())
  .accepts.find(o => o.asset === 'NANUSD') // or 'XNO'
const me = 'usd_...'; const key = 'PRIVATE_KEY_HEX' // nano_... when paying XNO
const fr = await (await fetch(`${BASE}/x402/frontier/${me}`)).json()
const b = block.send({ walletBalanceRaw: fr.balance, fromAddress: me,
  toAddress: quote.payTo, representativeAddress: fr.representative,
  frontier: fr.frontier, amountRaw: (BigInt(quote.extra.basePriceRaw) * 200n).toString() }, key)
delete b.work
const xPayment = Buffer.from(JSON.stringify({ x402Version: 1, scheme: 'exact',
  network: quote.network, payload: { block: b } })).toString('base64')
const res = await fetch(`${BASE}/XNO`, { method: 'POST',
  headers: { 'content-type': 'application/json', 'x-payment': xPayment },
  body: JSON.stringify({ action: 'account_info', account: me }) })
const receipt = JSON.parse(Buffer.from(res.headers.get('x-payment-response'), 'base64'))
// persist receipt.token, reuse via X-PAYMENT-TOKEN
```

Community x402 clients that sign Nano sends locally (e.g. feeless402) follow
the same shape: read the quote from `accepts[]`, sign locally, retry with
`X-PAYMENT`.

## Guarantees

* **Only the chain counts**: the payment signature is verified, and the amount
  and destination credited are read from the confirmed block on the node, never
  from client claims.
* **Replay-safe**: each payment block is redeemable once, forever. Tokens are
  bearer secrets that never touch the chain, so ledger observers cannot spend
  someone else's credits — keep yours private.
* **Refunds**: a request that fails after being charged (HTTP ≥ 400) gets its
  credits back automatically.
