diff --git a/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx b/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx index f399fc0..a974415 100644 --- a/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx +++ b/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx @@ -40,7 +40,7 @@ app.use(paymentMiddleware({ })); ``` -Install `@parallel-protocol/x402` 0.8.1 or later: since 1 October 2026 the facilitator refuses a settle that does not present the token it issued at verify, and versions before 0.8.0 do not send it. Version 0.8.1 adds the URL checks below. +Install `@parallel-protocol/x402` 0.8.2 or later: since 1 October 2026 the facilitator refuses a settle that does not present the token it issued at verify, and versions before 0.8.0 do not send it. Version 0.8.1 adds the URL checks below. Keep the facilitator's URL in https, as above. Since 0.8.1, the SDK refuses a plain http URL outside `localhost`, `127.0.0.1` and `[::1]` with an `X402ConfigError` when the middleware is created. It calls that address only and never follows a redirect, which fails the call with `FACILITATOR_UNAVAILABLE`. diff --git a/src/pages/agents/x402/agent-quickstart.mdx b/src/pages/agents/x402/agent-quickstart.mdx index bf08abf..b2fbcb2 100644 --- a/src/pages/agents/x402/agent-quickstart.mdx +++ b/src/pages/agents/x402/agent-quickstart.mdx @@ -15,9 +15,9 @@ This guide makes an agent pay x402 APIs autonomously. The whole integration is o npm install @parallel-protocol/x402-fetch ``` -This page describes version 0.3.0, the one a fresh install gets. The package signs through the payment engine of the [Parallel CLI](/agents/cli), `@parallel-protocol/cli`, which it installs as a regular dependency. Since version 0.2.3 it accepts the CLI's 0.4 line, so a fresh install gets CLI 0.4.1, which prepares a USDp or sUSDp payment on Base in about half a second instead of about 5 seconds; an existing project gets it by refreshing its lockfile. With CLI 0.4.1 and the facilitator update shipped alongside it, Parallel measured a paid call on Base at 3.5 seconds end to end, down from 9.4. +This page describes version 0.3.1, the one a fresh install gets. The package signs through the payment engine of the [Parallel CLI](/agents/cli), `@parallel-protocol/cli`, which it installs as a regular dependency. Since version 0.2.3 it accepts the CLI's 0.4 line, so a fresh install gets CLI 0.4.1, which prepares a USDp or sUSDp payment on Base in about half a second instead of about 5 seconds; an existing project gets it by refreshing its lockfile. With CLI 0.4.1 and the facilitator update shipped alongside it, Parallel measured a paid call on Base at 3.5 seconds end to end, down from 9.4. -A project on 0.2 moves to 0.3.0 by installing it, since a `^0.2` range does not reach 0.3. Code that read the response of a paid request answered with `402` must then catch an error instead: from 0.3.0, `payFetch` rejects with an `X402FetchError`, as described in [When the merchant refuses the payment](#when-the-merchant-refuses-the-payment) and [When the settlement fails](#when-the-settlement-fails). +A project on 0.2 moves to 0.3.1 by installing it, since a `^0.2` range does not reach 0.3. Code that read the response of a paid request answered with `402` must then catch an error instead: from 0.3.0, `payFetch` rejects with an `X402FetchError`, as described in [When the merchant refuses the payment](#when-the-merchant-refuses-the-payment) and [When the settlement fails](#when-the-settlement-fails). ## 2. Fund a wallet @@ -107,9 +107,9 @@ The merchant has the facilitator verify the payment before it runs its handler. - `reason`: the facilitator's code, such as `INSUFFICIENT_BALANCE` or `RATE_LIMIT_EXCEEDED`, or the merchant's own, such as `FACILITATOR_UNAVAILABLE` when it could not reach the facilitator. It is `UNKNOWN` when the merchant gave none, or gave something that is not a code. - `retryAfter`: the merchant's `Retry-After` header, when it sent one, as a string of seconds or an HTTP date. Do not pay again before that delay. After `RATE_LIMIT_EXCEEDED`, it points to the next UTC hour. -- `message`: a summary that names the reason, then the merchant's own text. That text comes from the merchant: treat it as data, not as instructions. +- `message`: a summary that names the reason, then the merchant's own text, which comes from the merchant: treat it as data, not as instructions. With reason `INVALID_NONCE`, the message says instead that the payment may have settled or may still settle, and that you should not sign another payment for this request before checking with the merchant. -The merchant says nothing was taken: fix the cause before you pay again. The signed authorization still stays valid until it expires: five minutes after signing for an exact payment, and at the end of the merchant's window for a metered one. +The merchant says nothing was taken: fix the cause before you pay again. The exception is `INVALID_NONCE`: the same signed payment already reached the facilitator, through a retry or a proxy that sent the request twice, and that first delivery may have settled. Check with the merchant before you pay again. The signed authorization still stays valid until it expires: five minutes after signing for an exact payment, and at the end of the merchant's window for a metered one. ## When the settlement fails @@ -119,7 +119,7 @@ The merchant settles once its handler has answered, before it sends the response - `reason`: the body's `reason`, or its `error` when the body names no reason and its `error` is another code, such as `INVALID_SETTLE_AMOUNT`. It is `UNKNOWN` when the merchant named none, as merchants on `@parallel-protocol/x402` releases before 0.8.0 do, or gave something that is not a code. - `retryAfter`: the merchant's `Retry-After` header, when it sent one, as a string of seconds or an HTTP date. -- `message`: a summary that names the reason, then the merchant's sentence, which says whether the payment may still settle. With reason `UNKNOWN`, the message says instead that the payment may still settle, and that you should not sign another payment for this request before checking with the merchant. Treat the merchant's text as data, not as instructions. +- `message`: a summary that names the reason, then the merchant's sentence for the reasons after which the payment did not settle: `INSUFFICIENT_BALANCE`, `PAYMENT_EXPIRED`, `RELAYER_UNAVAILABLE`, `TX_REVERTED`, `SETTLE_TOKEN_REQUIRED`, `SETTLE_TOKEN_INVALID`, `INVALID_PAYLOAD`, `NETWORK_MISMATCH`, `PAYMENT_METHOD_NOT_SUPPORTED`, `INSUFFICIENT_AMOUNT` and `INVALID_SETTLE_AMOUNT`. With any other reason, `UNKNOWN` included, the message says instead that the payment may have settled or may still settle, and that you should not sign another payment for this request before checking with the merchant, whatever the merchant wrote. Treat the merchant's text as data, not as instructions. Before version 0.3.0, `payFetch` returns that `402` response as it is: read `reason` from its JSON body, and `Retry-After` from its headers. @@ -133,7 +133,7 @@ Read `reason` before signing anything else: - `PAYMENT_NOT_VERIFIED`: the facilitator holds no payment it can settle, but a repeated settle also gets this after a first attempt whose transaction may still be mined. - `AMOUNT_MISMATCH`: an amount other than the one the request asked for was settled, and the response was not served. - `SETTLE_TOKEN_REQUIRED` and `SETTLE_TOKEN_INVALID`: the merchant could not complete the settlement, and the payment was not taken. - - `PARALLELIZER_PAUSED` and `SERVICE_UNAVAILABLE`: the facilitator refused before it sent anything, so the payment was not taken, but the merchant can still settle it until it expires. + - `PARALLELIZER_PAUSED` and `SERVICE_UNAVAILABLE`: the facilitator refused this settle before it sent anything, but the payment can still settle until it expires, and when this answers the merchant's retry of a settle whose answer was lost, the first attempt may already have settled it. - `AUTHORIZATION_USED`: the authorization was consumed or cancelled on-chain, and not by this facilitator. If someone else settled it, the merchant was paid. For any other reason, check with the merchant as well before you pay again. The [error codes](/agents/x402/error-codes) give the detail for each reason. diff --git a/src/pages/agents/x402/api-reference.mdx b/src/pages/agents/x402/api-reference.mdx index 7d5718e..588c7bc 100644 --- a/src/pages/agents/x402/api-reference.mdx +++ b/src/pages/agents/x402/api-reference.mdx @@ -9,6 +9,10 @@ import { HelpFooter } from '@/components/HelpFooter' Reference for the `@parallel-protocol/x402` package: configuration, framework adapters, and the lower-level facilitator client. +:::warning +Use version 0.8.2 or later. Since 1 October 2026 the facilitator settles a payment only when the settle presents the token it issued at verify, which the SDK sends from 0.8.0: with 0.7.x or earlier, every settlement is refused with `SETTLE_TOKEN_REQUIRED`. +::: + ## Configuration ### `PaymentMiddlewareConfig` @@ -24,22 +28,53 @@ interface PaymentMiddlewareConfig { | Field | Type | Required | Description | |---|---|---|---| -| `url` | `string` | Yes | Base URL of the Parallel facilitator. The SDK appends `/x402/verify` and `/x402/settle` to this value. | +| `url` | `string` | Yes | Base URL of the Parallel facilitator, `https://agents.parallel.best`. The SDK appends `/x402/verify` and `/x402/settle` to this value. It must use https: plain http is accepted only for `localhost`, `127.0.0.1` and `[::1]`. A trailing slash is ignored. The SDK calls this address only and never follows a redirect, which fails the call with `FACILITATOR_UNAVAILABLE`. | | `apiKey` | `string` | No | Reserved for future use. Sent as an `X-API-Key` header when provided; not currently enforced. | ### `RouteConfig` | Field | Type | Required | Description | |---|---|---|---| -| `price` | `string \| bigint` | Yes | Amount required. A string like `"0.01"` is parsed at `decimals` precision. Pass a `bigint` to skip parsing. | -| `decimals` | `number` | No | Override for custom tokens only. Each accepted token's decimals are resolved automatically from Parallel's on-chain token catalog; an unknown token without `decimals` throws `X402ConfigError` at startup. | +| `price` | `string \| bigint \| (ctx) => string \| bigint \| Promise` | Yes | Amount required. A string like `"0.01"` is parsed with each accepted token's own decimals. Pass a `bigint` to skip parsing, or a function to price each request from its content. On a metered route, `price` is the cap. | +| `decimals` | `number` | No | Override for custom tokens only. Each accepted token's decimals are resolved automatically from Parallel's on-chain token catalog. An unknown token without `decimals` throws `X402ConfigError` at the first request on the route. | | `network` | `string` | Yes | Chain slug: `"ethereum"`, `"base"`, `"avalanche"`, or `"hyperevm"`. | | `payTo` | `Address` | Yes | The merchant's receiving address. | -| `acceptedTokens` | `Address[]` | No | Token addresses the route accepts. Defaults to USDp, USDC, and sUSDp for the network; required on networks without defaults. | +| `acceptedTokens` | `Address[]` | No | Token addresses the route accepts. Defaults to USDp, USDC, and sUSDp for the network, and required on networks without defaults. A metered route accepts USDp only. | | `description` | `string` | No | Human-readable description of the resource, included in the `402` body. | +| `scheme` | `"exact" \| "upto"` | No | `exact` (default) charges `price` as invoiced. `upto` invoices `price` as a cap: the handler names the amount it actually charges, and the rest is refunded on-chain. See [metered routes](#metered-routes-upto). | +| `maxTimeoutSeconds` | `number` | No | Settlement window announced to the payer, 300 by default. On a metered route it is 3,600 at most: a larger value throws `X402ConfigError` at startup. On metered routes, Express, Hono and Next.js give the handler this window minus two minutes, kept for the settlement and its retry, and 30 seconds at least. Fastify does not time handlers out. | +| `meter` | `(ctx) => string \| bigint \| undefined \| Promise` | No | Metered routes only: reads the amount to charge from the handler's response. See [metered routes](#metered-routes-upto). | Route matching is **longest-prefix-wins**: `/api/v1/users` matches a `/api/v1` config before a `/api` one. +### Metered routes (`upto`) + +On a route with `scheme: "upto"`, `price` is a cap: the handler names the amount it charges, and the facilitator settles that amount through [route U](/agents/x402/verify-vs-settle#settlement-routes), refunding the rest to the agent. Metered payments are made in USDp, on Base. + +```ts +import { SETTLE_AMOUNT_HEADER } from "@parallel-protocol/x402"; + +// routes: { "/v1/chat/completions": { scheme: "upto", price: "2", maxTimeoutSeconds: 600, network: "base", payTo } } +fastify.post("/v1/chat/completions", async (request, reply) => { + const completion = await runInference(request.body); + reply.header(SETTLE_AMOUNT_HEADER, completion.costInUsdp); // e.g. "0.0137" + return completion; +}); +``` + +The handler names the amount in the `payment-settle-amount` header, in whole token units like `price`. The middleware removes the header before the response leaves. On a `2xx` response: + +| Header | What happens | +|---|---| +| absent | The cap is charged. | +| `"0"` | The request is served for free: nothing is settled, no `payment-response`. | +| an amount up to `price` | That amount is settled, and the receipt's `amountSettled` carries it. | +| malformed, more decimals than the token, or above `price` | The response is discarded and the agent gets `402 INVALID_SETTLE_AMOUNT`. | + +Instead of the header, a `meter` function on the route can read the amount from the response: it receives `{ status, header(name), body, request }` and returns an amount, or nothing to let the header decide. An amount above the cap settles the cap, and a `meter` that throws makes the agent get `402 INVALID_SETTLE_AMOUNT`. + +A handler that finishes after the window has done the work, but the payment can no longer settle: the agent gets `402 PAYMENT_SETTLEMENT_FAILED` with reason `PAYMENT_EXPIRED`, and the merchant is not paid. Keep a margin. + ## Framework adapters | Import path | Export | Framework | @@ -60,26 +95,38 @@ import { FacilitatorClient } from "@parallel-protocol/x402"; const client = new FacilitatorClient({ url: "https://agents.parallel.best" }); -// Phase 1: verify signature + reserve nonce (no on-chain tx) -await client.verify(paymentHeader, paymentRequirements); +// Phase 1: verify signature + reserve nonce (no on-chain tx). The facilitator +// hands back the settle token this payment must be settled with. +const { settleToken } = await client.verify(paymentHeader, paymentRequirements); -// Phase 2: submit on-chain, return the settlement result -const result = await client.settle(paymentHeader, paymentRequirements); +// Phase 2: submit on-chain with the token, return the settlement result. +// On a metered route, also pass the amount to charge in the token's smallest unit: { settleToken, amount } +const result = await client.settle(paymentHeader, paymentRequirements, { settleToken }); if (result.success) { console.log(result.txHash, result.route, result.gasSponsored); + console.log(result.amountSettled); // metered routes: the amount charged + console.log(result.alreadySettled); // true when an earlier settle already did it } else { - console.error(result.error.code); + console.error(result.error.code); // e.g. "INSUFFICIENT_BALANCE" + console.error(result.error.message); // the facilitator's text + console.error(result.error.status); // its HTTP status, result.error.retryAfter when it sent one } ``` -`verify` uses a 10-second timeout; `settle` uses a 60-second timeout (it waits for on-chain inclusion). `verify` throws an [`X402RuntimeError`](/agents/x402/error-codes) on any failure; `settle` returns a result union on facilitator errors and throws only on connectivity issues. +The constructor throws `X402ConfigError` when the URL is neither https nor plain http on `localhost`, `127.0.0.1` or `[::1]`. `verify` uses a 10-second timeout and `settle` a 60-second one, since it waits for on-chain inclusion. `verify` throws an [`X402RuntimeError`](/agents/x402/error-codes) on any failure, with the facilitator's text in `.detail` and its status in `.status`, and a verify that issues no settle token is an invalid response. `settle` returns a result union on facilitator errors and throws on connectivity issues, with `SETTLE_TIMEOUT` when the 60 seconds ran out: the payment may then still settle. + +The settle token is a secret for the life of the request. Keep it in memory, never log it, never send it to the payer. ## `createPaymentGate` For frameworks not covered by an adapter, the lower-level `createPaymentGate` exposes the verify step without running your handler: ```ts -import { createPaymentGate } from "@parallel-protocol/x402"; +import { + createPaymentGate, + settleVerified, + settlementFailureResponse, +} from "@parallel-protocol/x402"; const gate = createPaymentGate(config); @@ -91,19 +138,26 @@ const result = await gate({ }); if (result.type === "pass") { - // route not configured for payment — proceed normally + // route not configured for payment, proceed normally } else if (result.type === "error") { - // send 402: result.result.status / headers / body + // send result.result.status / headers / body (a 402, or a price refusal) } else { - // result.type === "verified" — run your handler, then: + // result.type === "verified": run your handler, then const handlerStatus = await runHandler(); if (handlerStatus >= 200 && handlerStatus < 300) { - const settlement = await result.settle(); + // a metered route passes the amount to charge: settleVerified(result, { amount }) + const outcome = await settleVerified(result); + if (!outcome.settled) { + // discard the handler's response and send this 402 instead: + // settlementFailureResponse(outcome).status / headers / body + } } } ``` -Use `createPaymentMiddleware` instead if you want the full verify → run → settle flow managed for you. +The gate keeps the settle token the facilitator issued at verify and presents it at settle, so a custom integration has nothing to carry. `settleVerified` runs the same settlement as the framework adapters, with one retry when the outcome is unknown, and `settlementFailureResponse` builds the `402` that tells the agent why. On a metered route, `settleVerified(result, { amount })` takes the amount to charge in the token's smallest unit, which `resolveCharge` computes from the handler's response as the adapters do, and refuses a confirmation for another amount with `AMOUNT_MISMATCH`. + +Use `createPaymentMiddleware` instead if you want the whole flow (verify, run the handler, settle) managed for you. ## Utilities diff --git a/src/pages/agents/x402/concepts.mdx b/src/pages/agents/x402/concepts.mdx index fd96b71..6c173d4 100644 --- a/src/pages/agents/x402/concepts.mdx +++ b/src/pages/agents/x402/concepts.mdx @@ -20,7 +20,7 @@ Every paid request goes through two phases: If verification fails, your handler never runs. If your handler fails, settlement never happens — the agent is only charged for a successful response. See [verify vs settle](/agents/x402/verify-vs-settle) for the full sequence. -Each payment settles once. The facilitator claims the payment before it submits anything, so two settles of the same payment never both reach the chain, and a settle repeated after a lost answer gets the recorded outcome: the confirmation, marked `alreadySettled`, or the refusal. A settle that does not present the token issued at verify is refused with `SETTLE_TOKEN_REQUIRED`, or `SETTLE_TOKEN_INVALID` for a wrong one: the facilitator has required the token since 1 October 2026, and `@parallel-protocol/x402` sends it from version 0.8.0. +Each payment settles once. The facilitator claims the payment before it submits anything, so two settles of the same payment never both reach the chain, and a settle repeated once the first one has finished gets its recorded outcome: the confirmation, marked `alreadySettled`, or `PAYMENT_NOT_VERIFIED` when it failed. A settle that does not present the token issued at verify is refused with `SETTLE_TOKEN_REQUIRED`, or `SETTLE_TOKEN_INVALID` for a wrong one: the facilitator has required the token since 1 October 2026, and `@parallel-protocol/x402` sends it from version 0.8.0. ## Exact and metered payments diff --git a/src/pages/agents/x402/error-codes.mdx b/src/pages/agents/x402/error-codes.mdx index e33d6fc..616ca71 100644 --- a/src/pages/agents/x402/error-codes.mdx +++ b/src/pages/agents/x402/error-codes.mdx @@ -1,46 +1,114 @@ --- title: x402 error codes -description: Reference for the errors thrown by the Parallel x402 SDK and the error codes propagated from the facilitator on a rejected payment. +description: Reference for the errors thrown by the Parallel x402 SDK, the codes the facilitator returns when it refuses a payment, and the reasons a settlement can fail. --- import { HelpFooter } from '@/components/HelpFooter' # Error codes +:::warning +Since 1 October 2026 the facilitator settles a payment only when the settle presents the token it issued at verify. `@parallel-protocol/x402` sends it from version 0.8.0. A merchant on 0.7.x or earlier sees every settlement refused with `SETTLE_TOKEN_REQUIRED`: the agent gets a `402` instead of the response, and the merchant is never paid. Use 0.8.2 or later. +::: + ## Thrown by the SDK | Error class | When | |---|---| -| `X402ConfigError` | Invalid config at middleware setup — bad `payTo`, an unknown network with no `acceptedTokens`, or a malformed facilitator URL. | +| `X402ConfigError` | Invalid config, with a message that names the field at fault. At middleware setup: bad `payTo`, a facilitator URL that is malformed or not https (plain http is accepted only for `localhost`, `127.0.0.1` and `[::1]`), or a metered route with `maxTimeoutSeconds` above 3,600. At the first request on a route: an unknown network with no `acceptedTokens`, an unknown token with no `decimals`, or a price below the token's precision. | | `X402RuntimeError` | A runtime failure. The specific cause is in `.code` (below). | ### `X402RuntimeError.code` | Code | Meaning | |---|---| -| `FACILITATOR_UNAVAILABLE` | The facilitator timed out (10s) or returned a non-JSON error. | -| `FACILITATOR_INVALID_RESPONSE` | The facilitator returned an unexpected response shape. | -| `INVALID_PAYMENT` | The `payment-signature` / `X-PAYMENT` header could not be base64-decoded. | +| `FACILITATOR_UNAVAILABLE` | The facilitator gave no usable answer: it could not be reached, did not answer a verify within 10 s, answered with a redirect (the SDK never follows one), answered an error without a code, or answered a body that is not JSON. At settle, the payment may still settle. | +| `SETTLE_TIMEOUT` | The facilitator did not answer a settle within 60 s. The payment may still settle. | +| `FACILITATOR_INVALID_RESPONSE` | The facilitator returned an unexpected response, including a verify without a settle token. | +| `INVALID_PAYMENT` | The `payment-signature` / `X-PAYMENT` header could not be decoded. | -## Propagated from the facilitator +An `X402RuntimeError` also carries the facilitator's text in `.detail`, its HTTP status in `.status` (the redirect's status for a redirect), and its `Retry-After` in `.retryAfter` when it sent one. -When the facilitator rejects a payment, its error code is forwarded as the `error` field on the re-issued `402` body. Common values: +## Refused at verify -| Code | Meaning | +When the facilitator refuses a payment at verify, your handler does not run and nothing moves. The middleware re-issues a `402` with a new invoice: the facilitator's code is the `error` field, its text the `message` field, and its `Retry-After` header is copied whenever it sent one. The facilitator's own status is the `.status` of the error when you call the [`FacilitatorClient`](/agents/x402/api-reference#facilitatorclient) yourself. + +| Code | Facilitator status | Meaning | What the agent should do | +|---|---|---|---| +| `INVALID_PAYLOAD` | 400 | The payload does not have the shape of its settlement route, carries a field another route would read, or uses a method of the other scheme. | Sign a payment that matches one of the `accepts` entries. | +| `INVALID_SIGNATURE` | 400 | Signature recovery failed. | Sign again. | +| `INVALID_NONCE` | 409 | Nonce already used: the same payment reached the facilitator before, and may have settled. | Do not sign another payment before checking with the merchant. | +| `PAYMENT_EXPIRED` | 402 | The authorization's `validBefore` has passed. | Sign a new payment. | +| `INSUFFICIENT_AMOUNT` | 402 | The amount the route guarantees the merchant is below the price: the signed amount on a transfer, the guaranteed output (`amountOut` or `amountOutMin`) on a conversion. Also an authorization for zero. | Sign for the invoiced `amount`. | +| `INSUFFICIENT_BALANCE` | 402 | The payer does not hold the signed amount. Checked on metered payments, against the cap. | Fund the wallet, sign a new payment. | +| `ASSET_MISMATCH` | 400 | The route does not deliver the token the merchant requires. | Pay so that the merchant receives one of the `accepts` assets. | +| `RECIPIENT_MISMATCH` | 400 | The signed recipient is not the merchant's `payTo`. | Sign to the invoiced `payTo`. | +| `NETWORK_MISMATCH` | 400 | The facilitator does not support the payload's chain, or it is not the route's chain. | Sign on the invoiced network. | +| `WINDOW_TOO_LONG` | 400 | A metered authorization valid for more than 3,600 seconds. | Sign again with a `validBefore` within the hour. | +| `PAYMENT_METHOD_NOT_SUPPORTED` | 400 | No settlement route for this method or token on this chain, including a metered payment on a chain without the escrow. | Pay with another method or token. | +| `COLLATERAL_NOT_SUPPORTED` | 400 | The swap delivers a token that is not a collateral of the chain. | Pay for another of the `accepts` assets. | +| `RATE_LIMIT_EXCEEDED` | 429 | The payer passed 1,000 verifies in the current UTC hour. | Pay again after `Retry-After`, which points to the next hour. | +| `SERVICE_UNAVAILABLE` | 503 | The facilitator could not read the chain or its own store. | Pay again after a short wait. | + +An `error` from the facilitator that is not a code (capitals, digits and underscores) is not forwarded: the `402` carries `FACILITATOR_INVALID_RESPONSE` with the facilitator's message instead. That is the case of its per-IP rate limit (see [rate limits](#rate-limits)). + +## Settlement failures + +The settlement runs after your handler answered. When it fails, the middleware discards the handler's response and answers `402` with this JSON body, plus the facilitator's `Retry-After` header when it sent one: + +```json +{ + "error": "PAYMENT_SETTLEMENT_FAILED", + "reason": "INSUFFICIENT_BALANCE", + "message": "Payer balance is below the signed amount — the payment cannot settle" +} +``` + +`error` stays `PAYMENT_SETTLEMENT_FAILED` for the clients that already read it. `reason` says why, and tells the agent whether to sign a new payment. + +| Reason | Facilitator status | Meaning | What the agent should do | +|---|---|---|---| +| `INSUFFICIENT_BALANCE` | 402 | The payer no longer holds the signed amount. | Fund the wallet, sign a new payment. | +| `AUTHORIZATION_USED` | 409 | The authorization is already consumed or cancelled on-chain. It may have paid the merchant. | Do not sign another payment before checking with the merchant. | +| `PAYMENT_EXPIRED` | 402 | The authorization expired before settlement. On a metered route, the handler finished after the window. | Sign a new payment. | +| `PAYMENT_NOT_VERIFIED` | 402 | No verified payment for this authorization, or an earlier settle of it failed. The merchant may have been paid, or may still be. | Do not sign another payment before checking with the merchant. | +| `SETTLE_IN_PROGRESS` | 409 | Another settle of the same payment is still running. | Do not sign another payment before checking with the merchant. | +| `SETTLE_TOKEN_INVALID`, `SETTLE_TOKEN_REQUIRED` | 403 | The merchant did not present the settle token issued at verify. A merchant-side issue, typically a middleware older than 0.8.0. Nothing was settled. | Do not sign another payment before checking with the merchant. | +| `RELAYER_UNAVAILABLE` | 503 | The facilitator is temporarily unable to settle. The payment was not taken, and the facilitator will not settle it. | Retry later with a new payment, after `Retry-After` when given. | +| `PARALLELIZER_PAUSED` | 503 | The Parallelizer has paused the swap this route needs, or the facilitator could not read whether it has. This settle sent nothing, but the payment may still settle until its authorization expires, and an earlier attempt may already have settled it. | Do not sign another payment before checking with the merchant. | +| `SERVICE_UNAVAILABLE` | 503 | The facilitator could not read its own store. This settle sent nothing, but the payment may still settle until its authorization expires, and an earlier attempt may already have settled it. | Do not sign another payment before checking with the merchant. | +| `TX_REVERTED` | 500 | The transaction reverted for a reason the facilitator could not attribute. | Sign a new payment. | +| `SUBMISSION_FAILED` | 500 | The submission failed. When the message says the outcome is unknown, a transaction may have been sent, and the payment may have settled or may still settle. | Do not sign another payment before checking with the merchant. x402-fetch says so for this reason whatever the message. A client that reads the merchant's 402 itself may sign a new payment when the message says no transaction was submitted. | +| `RECEIPT_UNAVAILABLE` | 500 | The transaction was sent but its confirmation could not be read. | Do not sign another payment before checking with the merchant. | +| `INVALID_PAYLOAD`, `NETWORK_MISMATCH`, `PAYMENT_METHOD_NOT_SUPPORTED` | 400 | The settle does not match the payment that was verified, or a metered amount is missing, malformed or above the cap. Nothing was settled. | Sign a new payment. | +| `INSUFFICIENT_AMOUNT` | 402 | A metered amount of zero. Nothing was settled. | Sign a new payment. | + +The SDK adds its own reasons: + +| Reason | Meaning | What the agent should do | +|---|---|---| +| `SETTLE_TIMEOUT`, `FACILITATOR_UNAVAILABLE`, `FACILITATOR_INVALID_RESPONSE` | The facilitator's answer was lost: the settlement may still have gone through. | Do not sign another payment before checking with the merchant. | +| `AMOUNT_MISMATCH` | On a metered route, the facilitator confirmed a settlement of another amount than the one the handler asked for. Money moved, and the response was not served. | Do not sign another payment before checking with the merchant. | +| `UNKNOWN` | Anything the facilitator answered that is not a code, such as its per-IP rate limit. | Check with the merchant before paying again. | + +On a metered route, a handler that names an amount the middleware cannot settle (malformed, finer than the token, above the cap, or a `meter` that fails) has its response discarded, and the agent gets a `402` whose body is `{ error: "INVALID_SETTLE_AMOUNT", message }`, with no `reason`. Nothing was settled. It is a merchant-side bug, and the same request fails the same way until the merchant fixes its handler. + +`AMOUNT_MISMATCH` is the one reason that points at the facilitator rather than at the request: alert on it rather than treating it as a routine refusal. For `SETTLE_IN_PROGRESS`, `RECEIPT_UNAVAILABLE`, `SETTLE_TOKEN_INVALID` and `SETTLE_TOKEN_REQUIRED`, the `message` is the SDK's own, since the facilitator's text for them addresses the merchant. From version 0.8.2, it is the SDK's own too for `AUTHORIZATION_USED`, `PAYMENT_NOT_VERIFIED`, `PARALLELIZER_PAUSED` and `SERVICE_UNAVAILABLE`: the payment may have settled or may still settle, so the message tells the agent to check with the merchant before paying again, as it does for `UNKNOWN`. + +Before any of this, a settle that timed out or could not reach the facilitator is retried once by the SDK, with the same settle token. The same settle is safe to repeat: once the first attempt has finished, the facilitator answers with its recorded outcome, the confirmation marked `alreadySettled` or `PAYMENT_NOT_VERIFIED` when it failed, and any other answer to the retry tells the agent to check with the merchant. + +## Rate limits + +The facilitator counts the requests of each IP address that calls it, which is the merchant's server: 60 verifies a minute and 600 settles a minute, each on its own counter. It also counts the verifies of each payer: 1,000 per UTC hour. + +| Limit | What the agent gets | |---|---| -| `INVALID_SIGNATURE` | Signature recovery failed. | -| `INVALID_NONCE` | Nonce already used (replay detected). | -| `PAYMENT_EXPIRED` | The authorization's `validBefore` has passed. | -| `INSUFFICIENT_AMOUNT` | The signed amount is less than the required amount. | -| `NETWORK_MISMATCH` | The payload's chain does not match the route's configured chain. | -| `RATE_LIMIT_EXCEEDED` | The signer has exceeded the hourly transaction limit. | -| `PAYMENT_NOT_VERIFIED` | `/settle` was called without a prior `/verify` (or the verify context expired — 120 s). | -| `PARALLELIZER_PAUSED` | The swap is paused on-chain — nothing moved, the authorization simply expires. | -| `PAYMENT_METHOD_NOT_SUPPORTED` | The payment method does not match any settlement route. | -| `COLLATERAL_NOT_SUPPORTED` | The requested output token is not an accepted collateral on this chain. | +| Verifies per IP | A `402` with a new invoice, `error: "FACILITATOR_INVALID_RESPONSE"` and the facilitator's `Retry-After`. Nothing was verified. | +| Settles per IP | A `402` with `reason: "UNKNOWN"` and the facilitator's `Retry-After`. The response is discarded. This settle did nothing, but when the limit answers the SDK's retry of a settle that timed out, the first attempt may have settled. | +| Verifies per payer | A `402` with a new invoice, `error: "RATE_LIMIT_EXCEEDED"`, and a `Retry-After` that points to the next UTC hour. | ## Handling errors -A rejected payment is not an exception in your handler — the middleware re-issues a `402` with the `error` field set, and the agent can sign a corrected payment and retry. You only need to catch `X402RuntimeError` if you are calling the [`FacilitatorClient`](/agents/x402/api-reference#facilitatorclient) or [`createPaymentGate`](/agents/x402/api-reference) directly. +A refused payment is not an exception in your handler. On a refusal at verify, the middleware re-issues a `402` and the agent can sign a corrected payment. On a failed settlement, the `reason` decides: some ask for a new payment, others for a check with the merchant first, since the first payment may still settle. You only need to catch `X402RuntimeError` if you call the [`FacilitatorClient`](/agents/x402/api-reference#facilitatorclient) or [`createPaymentGate`](/agents/x402/api-reference#createpaymentgate) directly. diff --git a/src/pages/agents/x402/quickstart.mdx b/src/pages/agents/x402/quickstart.mdx index db5f854..99e0c29 100644 --- a/src/pages/agents/x402/quickstart.mdx +++ b/src/pages/agents/x402/quickstart.mdx @@ -17,7 +17,7 @@ npm install @parallel-protocol/x402 ``` :::warning -Use version 0.8.1 or later. Since 1 October 2026 the facilitator settles a payment only when the settle presents the token it issued at verify, and versions before 0.8.0 do not send it: their settlements are refused with `SETTLE_TOKEN_REQUIRED`, and the agent gets a `402` instead of your response. Version 0.8.1 adds the facilitator URL checks of step 2. +Use version 0.8.2 or later. Since 1 October 2026 the facilitator settles a payment only when the settle presents the token it issued at verify, and versions before 0.8.0 do not send it: their settlements are refused with `SETTLE_TOKEN_REQUIRED`, and the agent gets a `402` instead of your response. Version 0.8.1 adds the facilitator URL checks of step 2, and 0.8.2 tells the agent to check with you before paying again for the reasons listed in the error codes. ::: Install your framework separately — they are optional peer dependencies: diff --git a/src/pages/agents/x402/schemas.mdx b/src/pages/agents/x402/schemas.mdx index baa7066..7cc5339 100644 --- a/src/pages/agents/x402/schemas.mdx +++ b/src/pages/agents/x402/schemas.mdx @@ -17,18 +17,19 @@ Returned when no valid payment is present. The `payment-required` header holds a interface PaymentRequired { x402Version: 2; error?: string; // present on re-challenge, e.g. "INVALID_SIGNATURE" + message?: string; // the facilitator's text for `error`, when it sent one resource: { url: string; description?: string; mimeType: "application/json"; }; accepts: Array<{ - scheme: "exact"; + scheme: "exact" | "upto"; // "upto": `amount` is a cap, see metered payments below network: string; // EIP-155, e.g. "eip155:8453" asset: string; // token address - amount: string; // wei string (18 decimals for USDp) + amount: string; // in the token's smallest unit (18 decimals for USDp) payTo: string; - maxTimeoutSeconds: 300; + maxTimeoutSeconds: number; // the settlement window, 300 by default, 3,600 at most on "upto" extra: { decimals: number }; // the payer must scale the amount with THESE decimals }>; } @@ -61,6 +62,10 @@ const header = Buffer.from(JSON.stringify(signedPayload)).toString("base64"); Agent-side signing helpers (EIP-3009 authorizations, EIP-712 signing) live in the `@parallel-protocol/payment-core` package. +### Metered payments (`upto`) + +On a metered invoice, the agent signs a `ReceiveWithAuthorization` of the cap to Parallel's escrow contract, on the USDp domain, instead of a transfer to the merchant. The payload has `scheme: "upto"` and the method `uptoWithAuthorization`, carries the merchant in `uptoParams.payTo`, and puts the payer's random salt in `authorization.nonce`: the signed nonce is derived from the salt and the payment's terms, so the signature only holds for those exact values. `@parallel-protocol/payment-core` exports `deriveUptoNonce` for this. The escrow address comes from Parallel's chain catalog (`@parallel-protocol/chains`), never from the invoice. + ## `200` response — `payment-response` On success, the middleware sets a `payment-response` header with a base64-encoded settlement confirmation: @@ -69,13 +74,29 @@ On success, the middleware sets a `payment-response` header with a base64-encode interface PaymentConfirmation { success: true; txHash: string; - route: string; // internal settlement route id + route: string; // the settlement route, "A" to "L", or "U" for a metered payment chain: string; // "base" gasSponsored: boolean; networkId: string; // "eip155:8453" + amountSettled?: string; // metered routes: the amount charged, in the token's smallest unit + alreadySettled?: true; // answered from an earlier settle's recorded outcome, nothing broadcast this time +} +``` + +`route` is one of the [settlement routes](/agents/x402/verify-vs-settle#settlement-routes). The middleware sets `access-control-expose-headers` automatically so browser clients can read `payment-response`. + +## `402` after a failed settlement + +When the settlement fails after your handler answered, the response is discarded and replaced by a `402` with a plain JSON body. It carries no `payment-required` header, so an x402 client does not take it for a new invoice: + +```ts +interface SettlementFailureBody { + error: "PAYMENT_SETTLEMENT_FAILED"; + reason: string; // why, e.g. "INSUFFICIENT_BALANCE" or "AMOUNT_MISMATCH" (see the error codes) + message: string; // one line, cut at 300 characters } ``` -The middleware sets `access-control-expose-headers` automatically so browser clients can read `payment-response`. +The facilitator's `Retry-After` header is copied when it sent one. The reasons and what the agent should do with each are listed in [settlement failures](/agents/x402/error-codes#settlement-failures). diff --git a/src/pages/agents/x402/verify-vs-settle.mdx b/src/pages/agents/x402/verify-vs-settle.mdx index 3096739..449c34c 100644 --- a/src/pages/agents/x402/verify-vs-settle.mdx +++ b/src/pages/agents/x402/verify-vs-settle.mdx @@ -23,11 +23,12 @@ Agent Merchant (the SDK) Facilitator | | | |── GET /api/data ──────────────>| | | payment-signature: |── POST /x402/verify ───────>| - | |<─ { isValid: true } ────────| + | |<─ { isValid, settleToken } ─| | | | | | [your handler runs] | | | | | |── POST /x402/settle ───────>| + | | (+ settleToken) | | |<─ { txHash, route, ... } ───| | | | |<─ 200 + payment-response ──────| | @@ -38,9 +39,43 @@ Agent Merchant (the SDK) Facilitator - **The handler only runs after the signature is verified.** A request with a missing or invalid payment never reaches your code — it gets a `402`. - **Settlement happens after a 2xx.** The on-chain transfer is submitted only once your handler returns a success response. If your handler errors, nothing is charged. -- **A failed settlement discards the response.** If the on-chain transfer reverts or the facilitator times out, the middleware returns `402` instead of your handler's output, so the agent can retry. +- **The settle is bound to the merchant that verified.** `POST /x402/verify` hands the middleware a settle token that `POST /x402/settle` must present. The token stays in memory for the life of the request and never reaches the agent. The facilitator has required it since 1 October 2026, and `@parallel-protocol/x402` sends it from 0.8.0: a merchant on 0.7.x or earlier sees every settlement refused with `SETTLE_TOKEN_REQUIRED`, and is never paid. +- **The SDK talks to the facilitator only.** From 0.8.1 it calls the facilitator at its configured https address and never follows a redirect, so the payment, the settle token and the API key never reach another address. +- **One payment, one settlement.** The facilitator claims the payment before it submits anything, so two settles of the same payment never both reach the chain. A settle repeated once the first one has finished gets its recorded outcome: the confirmation, marked `alreadySettled`, or `PAYMENT_NOT_VERIFIED` when it failed. +- **Concurrent payments do not collide.** On each chain, the facilitator sends its settlement transactions one at a time, so payments settled together each get their own transaction. +- **A failed settlement discards the response and says why.** The middleware returns `402` instead of your handler's output, with a `reason` that tells the agent whether to sign a new payment or to check with you first. See [settlement failures](/agents/x402/error-codes#settlement-failures). - **CORS preflight passes through.** `OPTIONS` requests are never challenged. +## Settlement routes + +The facilitator settles each payment through one of 13 routes, chosen from the signed payload. The settlement receipt names it in `route`. + +| Route | Method signed | Agent pays | Merchant receives | Gas (approx.) | How it settles | +|---|---|---|---|---|---| +| **A** | `transferWithAuthorization` | USDp | USDp | 65K | Direct USDp transfer. | +| **B** | `swapExactOutputWithAuthorization` | USDp | USDC (exact) | 120K | The Parallelizer swaps the agent's USDp for the exact USDC amount. | +| **C** | `depositWithAuthorization` | USDp | sUSDp | 110K | The agent's USDp is deposited into the savings vault, and the merchant receives the sUSDp shares. | +| **D** | `swapExactOutputWithAuthorization` | USDp | Another backing collateral (exact) | 120K | Same as B, for the other collaterals of the Parallelizer. | +| **E** | `swapExactInputWithAuthorization` | USDC or a collateral (exact) | USDp (minimum) | 120K | The agent pays an exact amount, and the Parallelizer delivers at least the minimum USDp. | +| **F** | `transferWithAuthorization` | USDC or a collateral | The same token | 65K | Direct transfer of the token. | +| **G** | `swapExactInputWithAuthorization` | USDC or a collateral (exact) | sUSDp | 200K | The token is swapped to USDp, which is deposited as sUSDp for the merchant, in one transaction. | +| **H** | `redeemWithAuthorization` | sUSDp | USDp | 130K | The agent redeems sUSDp shares, and the merchant receives the USDp. | +| **I** | `redeemWithAuthorization` and `swapExactOutputWithAuthorization` | sUSDp | USDC (exact) | 180K | sUSDp is redeemed to USDp, then swapped for the exact USDC amount, in one transaction. | +| **J** | `transferWithAuthorization` | sUSDp | sUSDp | 65K | Direct transfer of sUSDp shares. | +| **K** | `redeemWithAuthorization` and `swapExactOutputWithAuthorization` | sUSDp | Another backing collateral (exact) | 180K | Same as I, for the other collaterals of the Parallelizer. | +| **L** | `partialRedeemWithAuthorization` | sUSDp and USDp | USDp or a backing collateral | 180K | A partial sUSDp redemption combined with the agent's USDp, in one transaction. | +| **U** | `uptoWithAuthorization` | USDp (the cap) | USDp (the amount charged) | 130K | A [metered payment](/agents/x402/api-reference#metered-routes-upto): Parallel's escrow contract pulls the signed cap, pays the merchant the amount the handler charged, and refunds the rest to the agent, in one transaction. | + +What each route needs on the chain: + +- Routes B, D, E, G, I, K and L need the Parallelizer, deployed on Ethereum, Base, Avalanche and HyperEVM. +- Routes B and I swap to USDC, so they need USDC among the chain's collaterals, which is the case on Base and Avalanche. +- Routes C, G, H, I, J, K and L need sUSDp on the chain. +- Routes E, F and G take as payment the chain's USDC or one of its collaterals, and the token must support EIP-3009. +- Route U needs the escrow contract, deployed on Base. On route U, verify also checks that the payer holds the cap. A metered payment on another chain is refused at verify with `PAYMENT_METHOD_NOT_SUPPORTED`. + +The facilitator's `GET /capabilities?chain=` lists the routes available on a chain right now, with their gas estimates and fees, and the settlement receipt says in `gasSponsored` whether the facilitator paid the gas. + ## Headers involved | Phase | Header | Direction |