From 737b7c0e2ef4fc75d325e261d51fc2a648e2374d Mon Sep 17 00:00:00 2001 From: Noah Boisserie <51783223+JeanBrasse@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:24:21 +0400 Subject: [PATCH 1/8] docs(x402): the settle token, one settlement per payment, metered payments, x402-fetch 0.2.3 and CLI 0.4.1 - quickstart, migration recipe: @parallel-protocol/x402 0.8.0 or later; the facilitator has required the settle token since 1 October 2026, and older versions' settlements are refused with SETTLE_TOKEN_REQUIRED. What happens behind the scenes: the token from verify to settle, a failed settlement's 402 with its reason, the one retry of a settle whose outcome is unknown. - concepts: what verify checks (BAC-375), the token, one settlement per payment and alreadySettled (BAC-376), and exact and metered (upto) payments: USDp only, a window of 3,600 s at most, the two minutes the SDK keeps for the settlement and its retry, AMOUNT_MISMATCH. - agent quickstart: x402-fetch 0.2.3 on CLI ^0.4.0 and the faster signing of 0.4.1; the dailyBudget, timeoutMs and allowInsecure options and the chain default; UNKNOWN_CHAIN, BUDGET_EXCEEDED, UNSUPPORTED_SCHEME and ENGINE_NOT_FOUND; metered invoices; what the agent gets when a settlement fails; one payment at a time, no automatic retry. - CLI: MIT; pay prepare's --scheme upto and --valid-for, and the signing domain read from DOMAIN_SEPARATOR() since 0.4.1. - FAQ, x402 overview, risks: the settle retry, the token, one settlement per payment, verify's checks, MIT for the CLI; the "120-second verify window" is gone, since a settle after it is rebuilt from the verified payment. Co-Authored-By: Claude Opus 5.5 --- src/pages/agents/cli/commands.mdx | 6 +++- src/pages/agents/cli/index.mdx | 2 +- src/pages/agents/faq.mdx | 2 +- .../recipes/migrate-from-coinbase-x402.mdx | 2 ++ src/pages/agents/x402/agent-quickstart.mdx | 29 +++++++++++++++++-- src/pages/agents/x402/concepts.mdx | 15 ++++++++-- src/pages/agents/x402/index.mdx | 2 +- src/pages/agents/x402/quickstart.mdx | 9 ++++-- src/pages/security/risks.mdx | 13 +++++---- 9 files changed, 63 insertions(+), 17 deletions(-) diff --git a/src/pages/agents/cli/commands.mdx b/src/pages/agents/cli/commands.mdx index 1d2718c..8fd6dca 100644 --- a/src/pages/agents/cli/commands.mdx +++ b/src/pages/agents/cli/commands.mdx @@ -116,6 +116,10 @@ parallel pay prepare --amount --recipient
[--chain ] [--wal `pay prepare` builds an x402 payment payload: `--token` sets what the merchant receives (`usdp` by default, `usdc`, `susdp`, a collateral symbol or a token address), `--pay-with` forces the paying token (`usdp`, `usdc` or `susdp`). With `--wallet` it auto-selects the route from your balances and signs the payload. This is the engine behind [agent payments](/agents/x402/agent-quickstart) — agents rarely call it directly. +`--scheme upto` signs `--amount` as a cap for a [metered payment](/agents/x402/concepts#exact-and-metered-payments), in USDp only, and `--valid-for ` sets the window the merchant announced, 3,600 at most. The default scheme is `exact`. + +Since 0.4.1, `pay prepare` reads the signing domain from the token's `DOMAIN_SEPARATOR()` instead of calling `version()`, which USDp and sUSDp do not have: on Base, a USDp or sUSDp payment is prepared in about half a second instead of about 5. A token whose domain matches no known version is refused with `ROUTE_UNAVAILABLE` before anything is signed. + `pay verify` reports `confirmed: true` only for payments the facilitator actually settled — a merely mined transaction returns `confirmed: false` with `txMined: true`, and an unknown hash returns everything `false`. ## Utilities @@ -143,7 +147,7 @@ Failures exit 1 and print `Error [CODE]: message`. In JSON mode the envelope `{ | `COLLATERAL_NOT_SUPPORTED` | Collateral (or bridge token) not accepted on this chain | | `EXCEEDS_CAP` | Mint or redeem beyond the collateral's deposited capacity — the message carries the remaining capacity | | `EXCEEDS_BRIDGE_LIMIT` | Daily or global bridge limit reached — the message carries the reset time | -| `ROUTE_UNAVAILABLE` | The bridge route does not exist (same chain, or no bridgeable token on the destination) | +| `ROUTE_UNAVAILABLE` | The bridge route does not exist (same chain, or no bridgeable token on the destination), or `pay prepare` cannot sign for the token: its signing domain matches no known version | | `PARTIAL_READ` | Some chain reads failed and the aggregate would be wrong — retry shortly | | `INSUFFICIENT_BALANCE` | Wallet balance too low for the requested amount | | `WALLET_REQUIRED` | Signing requested but no wallet available | diff --git a/src/pages/agents/cli/index.mdx b/src/pages/agents/cli/index.mdx index 5f41259..b93ee62 100644 --- a/src/pages/agents/cli/index.mdx +++ b/src/pages/agents/cli/index.mdx @@ -20,7 +20,7 @@ npm install -g @parallel-protocol/cli npx @parallel-protocol/cli protocol overview ``` -Requires Node.js ≥ 22. +Requires Node.js ≥ 22. The package is MIT-licensed. ## 2. Read the protocol — no wallet, no config diff --git a/src/pages/agents/faq.mdx b/src/pages/agents/faq.mdx index 0e713e2..5cf3843 100644 --- a/src/pages/agents/faq.mdx +++ b/src/pages/agents/faq.mdx @@ -35,7 +35,7 @@ import { HelpFooter } from '@/components/HelpFooter' }, { question: "What happens if the facilitator goes down?", - answer: "Payments fail safe: if the facilitator is unreachable, nothing settles — signed authorizations simply expire and no funds move. A public status page for the hosted instance is being set up." + answer: "Payments fail safe: if the facilitator is unreachable, nothing settles — signed authorizations simply expire and no funds move. If only a settle's answer is lost, the SDK retries the settle once, which is safe since the facilitator answers a repeated settle with its recorded outcome; if that fails too, the agent gets a 402 saying the payment may still settle, and should check with the merchant before paying again. A public status page for the hosted instance is being set up." }, { question: "How do I get notified when an agent pays?", diff --git a/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx b/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx index 5547bd2..c2c9315 100644 --- a/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx +++ b/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx @@ -40,6 +40,8 @@ app.use(paymentMiddleware({ })); ``` +Install `@parallel-protocol/x402` 0.8.0 or later: since 1 October 2026 the facilitator refuses a settle that does not present the token it issued at verify, and earlier versions do not send it. + The shape changes — `payTo` moves into the route, and prices drop the `$` prefix — but every concept maps one-to-one. Agents paying in USDC keep paying in USDC. Agents holding USDp can now pay you natively, with the facilitator handling conversion at no extra fee. ## What you gain diff --git a/src/pages/agents/x402/agent-quickstart.mdx b/src/pages/agents/x402/agent-quickstart.mdx index e8031c7..719730e 100644 --- a/src/pages/agents/x402/agent-quickstart.mdx +++ b/src/pages/agents/x402/agent-quickstart.mdx @@ -15,6 +15,8 @@ This guide makes an agent pay x402 APIs autonomously. The whole integration is o npm install @parallel-protocol/x402-fetch ``` +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. 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 this release 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. + ## 2. Fund a wallet The agent needs a wallet holding a small amount of **USDp, USDC, or sUSDp** on the target chain. **No ETH required** — settlement is relayed and gas is sponsored. Use a dedicated wallet holding only what you intend to spend. @@ -57,9 +59,12 @@ The URL in the example is real: it is Parallel's **live demo API**, where every | Option | Default | Purpose | |---|---|---| | `privateKey` | — | The agent's signing key. Pass it explicitly (recommended, any env var name you like) — or omit it and the package falls back to the `PARALLEL_PRIVATE_KEY` environment variable. It never leaves the machine; only signatures go over the network. | -| `chain` | — | Chain to pay on: `"base"`, `"avalanche"`, `"hyperevm"`, or `"ethereum"`. Invoices for any other chain are refused. | +| `chain` | `"base"` | Chain to pay on: `"base"`, `"avalanche"`, `"hyperevm"`, or `"ethereum"`. Invoices for any other chain are refused. | | `payWith` | *(auto)* | Force a payment token (`"usdp"`, `"usdc"`, `"susdp"`). Omitted, the agent picks from its balances. | | `maxAmount` | `"1"` | Hard spend cap per request, in token units. Invoices above it are refused before signing. | +| `dailyBudget` | *(none)* | Cumulative spend ceiling per UTC day, across every payment the wrapper signs. Without it, nothing limits how many capped payments a day can sign. | +| `timeoutMs` | `60000` | Time budget of the payment engine, in milliseconds. | +| `allowInsecure` | `false` | Pay merchants served over plain `http://`. Localhost is always allowed. | ## Refusals cost nothing @@ -67,19 +72,37 @@ Every guard fires **before** the agent signs — a refused invoice never spends | Code | Cause | |---|---| -| `NO_SIGNING_KEY` | No private key provided (option or env). | +| `NO_SIGNING_KEY` | No private key provided (option or env), or a malformed one. Thrown when you wrap `fetch`. | +| `UNKNOWN_CHAIN` | The configured `chain` is not a known chain. Thrown when you wrap `fetch`. | | `AMOUNT_EXCEEDS_MAX` | The invoice asks more than `maxAmount`. | +| `BUDGET_EXCEEDED` | The invoice would take the day's spend past `dailyBudget`. | | `CHAIN_MISMATCH` | The invoice targets a different chain than configured. | +| `UNSUPPORTED_SCHEME` | The invoice offers only schemes this client cannot pay on the configured chain. It pays `exact` invoices, and `upto` invoices in USDp. | | `INVALID_INVOICE` | The `402` response is malformed. | | `INSECURE_URL` | The merchant URL is plain `http://` (localhost excepted). | -| `ENGINE_FAILED` | Payment preparation failed — the message carries the cause (usually balance, or a transient RPC error). | +| `ENGINE_NOT_FOUND` | The payment engine, `@parallel-protocol/cli`, could not be found. | +| `ENGINE_FAILED` | Payment preparation failed — the message carries the cause (usually balance, or a transient RPC error), and `engineCode` the engine's code, such as `INSUFFICIENT_BALANCE`. | | `ENGINE_TIMEOUT` | Payment preparation exceeded its time budget. | +## Metered invoices + +A merchant can invoice a route with the `upto` scheme: a cap rather than a price, for a resource whose cost is only known once it is served. The agent signs the cap for the window the merchant announced (`maxTimeoutSeconds`, 3,600 seconds at most), the merchant charges its actual cost, and the escrow refunds the rest on-chain in the same settlement. The receipt's `amountSettled` is what was really paid. + +Metered payments are made in USDp. The cap counts in full against `maxAmount` and `dailyBudget`, and the refund is never credited back to the day's budget. + +## When the settlement fails + +The merchant settles after it has answered. If that settlement fails, the agent gets a `402` instead of the response, with a JSON body: `error` is `PAYMENT_SETTLEMENT_FAILED`, `reason` says why in a code, and `message` in a sentence. `payFetch` hands that response back as it is: it does not pay again. + +Read `reason` before signing anything else. `INSUFFICIENT_BALANCE` (fund the wallet first), `PAYMENT_EXPIRED` and `AUTHORIZATION_USED` ask for a new payment, and `RELAYER_UNAVAILABLE` for a new one later. `SETTLE_TIMEOUT`, `FACILITATOR_UNAVAILABLE`, `SETTLE_IN_PROGRESS` and `RECEIPT_UNAVAILABLE` mean the first payment may still settle: check with the merchant before you pay again. See also the [error codes](/agents/x402/error-codes). + ## The safety model - **Nothing moves without a signature**, and the signature authorizes exactly one transfer, to one recipient, within a time window. - **`maxAmount` is enforced client-side** against a verified token catalog — a merchant cannot re-scale amounts or trick the agent into overpaying. - **You only pay for success.** The merchant settles the payment only when it serves a successful response; an API error means nothing is charged, and unsettled authorizations simply expire. +- **One payment settles once.** The facilitator claims a payment before it submits it, so the same authorization never settles twice. +- **One payment at a time.** A wrapper signs one payment at a time, so concurrent invoices never spend the same balance twice, and it never retries a payment on its own. A payment can still settle when the paid retry fails on the network: treat non-idempotent paid requests accordingly. ## Next steps diff --git a/src/pages/agents/x402/concepts.mdx b/src/pages/agents/x402/concepts.mdx index 353acd7..16530e0 100644 --- a/src/pages/agents/x402/concepts.mdx +++ b/src/pages/agents/x402/concepts.mdx @@ -15,11 +15,22 @@ You declare paid routes in your middleware; the facilitator handles the rest. Every paid request goes through two phases: -1. **Verify** — the facilitator checks the agent's signed payment off-chain. Instant, no transaction. If it's valid, your handler runs. -2. **Settle** — once your handler returns a success response, the facilitator submits the transfer on-chain and returns a settlement proof. +1. **Verify** — the facilitator checks the agent's signed payment off-chain: its shape, signature, nonce and expiry, and that it delivers the required token, for at least the price, to your `payTo` on the route's network. Instant, no transaction. If it's valid, your handler runs, and the facilitator hands the middleware a settle token for this payment. +2. **Settle** — once your handler returns a success response, the middleware presents that token, and the facilitator submits the transfer on-chain and returns a settlement proof. 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, marked `alreadySettled`. 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 + +A route is priced in one of two schemes: + +- **`exact`**, the default: the agent signs the price, and you receive it. +- **`upto`**, for a resource whose cost is only known once it is served, such as an LLM completion: the agent signs the price as a cap, valid for the route's `maxTimeoutSeconds` (3,600 at most). Your handler names the amount it actually charges, and the escrow refunds the rest on-chain in the same settlement. Metered routes are paid in USDp only. + +On a metered route the SDK keeps the last two minutes of that window for the settlement and its retry: on Express, Hono and Next.js the handler gets `maxTimeoutSeconds` minus 120 seconds. A settlement the facilitator confirms for another amount than the one your handler asked for is refused with `AMOUNT_MISMATCH` and the response is discarded. Alert on it: money moved, and the agent was not served. The configuration, with the `payment-settle-amount` header and the `meter` function, is in the [package README](https://www.npmjs.com/package/@parallel-protocol/x402). + ## Supported stablecoins By default a route accepts **USDp**, **USDC**, and **sUSDp**. The agent pays with whichever of these it holds; you receive the token you configured — including sUSDp, Parallel's yield-bearing savings token, so your revenue can start earning the moment it settles. You can narrow or widen the accepted set per route with the [`acceptedTokens`](/agents/x402/api-reference#routeconfig) option. diff --git a/src/pages/agents/x402/index.mdx b/src/pages/agents/x402/index.mdx index a74070d..87f1e0a 100644 --- a/src/pages/agents/x402/index.mdx +++ b/src/pages/agents/x402/index.mdx @@ -23,7 +23,7 @@ Parallel runs an **x402 facilitator** and ships drop-in middleware so any API ca - **Zero platform fee** — Parallel takes no cut of your revenue. - **Gas sponsored** on Base, HyperEVM, and Avalanche. - **Settles directly to your wallet** — non-custodial, no Parallel account. -- **MIT-licensed SDKs** — the middleware and the agent package are published on npm. +- **MIT-licensed SDKs** — the middleware, the agent package and the CLI that signs its payments are published on npm. ## Start here diff --git a/src/pages/agents/x402/quickstart.mdx b/src/pages/agents/x402/quickstart.mdx index 8e8936d..72b7a3b 100644 --- a/src/pages/agents/x402/quickstart.mdx +++ b/src/pages/agents/x402/quickstart.mdx @@ -16,6 +16,10 @@ This guide adds stablecoin payment support to an API. The same pattern works for npm install @parallel-protocol/x402 ``` +:::warning +Use version 0.8.0 or later. Since 1 October 2026 the facilitator settles a payment only when the settle presents the token it issued at verify, and earlier versions do not send it: their settlements are refused with `SETTLE_TOKEN_REQUIRED`, and the agent gets a `402` instead of your response. +::: + Install your framework separately — they are optional peer dependencies: ```bash @@ -127,10 +131,11 @@ That's it. Your API now charges $0.01 per request to `/api/data`. Agents pay in When an agent calls your endpoint with a signed payment header: -1. The middleware sends the payload to the facilitator's `/x402/verify` endpoint — an instant, off-chain signature check. +1. The middleware sends the payload to the facilitator's `/x402/verify` endpoint — an instant, off-chain check of the signature, the amount, the token and the recipient. A valid payment comes back with a settle token, which the middleware keeps in memory. 2. If valid, **your handler runs** and produces the response. -3. If your handler returns a 2xx, the middleware calls `/x402/settle` — the on-chain transfer happens. +3. If your handler returns a 2xx, the middleware calls `/x402/settle` with that token — the on-chain transfer happens, once per payment. 4. If your handler fails, **no settlement happens** — the agent is not charged. +5. If the settlement fails, the agent gets a `402` with `PAYMENT_SETTLEMENT_FAILED` and a `reason` instead of your response. A settle that timed out or could not reach the facilitator is retried once first: repeating it is safe, since the facilitator answers with the recorded outcome. See the [error codes](/agents/x402/error-codes). Read more: [The verify / settle flow](/agents/x402/verify-vs-settle). diff --git a/src/pages/security/risks.mdx b/src/pages/security/risks.mdx index c95feda..ba73a28 100644 --- a/src/pages/security/risks.mdx +++ b/src/pages/security/risks.mdx @@ -29,7 +29,7 @@ Nothing on this page is financial, legal or tax advice. USDp is backed by other | Governance and key holders | Everyone | 5 of 8 multisigs, Snapshot votes, role timelocks, scoped guardian powers | [DAO Multisigs](/governance/dao-multisigs), [Emergency Guardians](/security/parallel-emergency-guardians) | | PRL price, staking penalties, LP exposure | PRL and sPRL holders | Cooldown instead of penalty if you wait the full 28 days, warnings in MCP transactions | [Staking Mechanisms](/governance/parallel-governance-token-prl/tokenomics/staking-mechanisms) | | Chain and infrastructure outage | Everyone on that chain | Independent deployments per chain, isolation mode available on the bridge, Sonic wind-down | [Implementation](/products/parallel-v3/stablecoins-and-savings/usdp-and-susdp/implementation) | -| x402 facilitator outage or failure | Agents paying with x402, merchants accepting it | Off-chain verify then on-chain settle, nothing charged on failure, non-custodial settlement, nonce and expiry on every authorization | [How the facilitator works](/agents/x402/concepts), [Verify vs settle](/agents/x402/verify-vs-settle) | +| x402 facilitator outage or failure | Agents paying with x402, merchants accepting it | Off-chain verify then on-chain settle, nothing charged on failure, one settlement per payment, bound to the merchant that verified, non-custodial settlement, nonce and expiry on every authorization | [How the facilitator works](/agents/x402/concepts), [Verify vs settle](/agents/x402/verify-vs-settle) | | Signing a bad transaction from an AI tool | MCP and CLI users | The MCP server never signs; it returns unsigned, simulated transactions with warnings for you to review | [How MCP transactions work](/agents/mcp/transactions) | ## 1. Collateral and backing risk @@ -212,8 +212,8 @@ Off-chain services (the app, the MCP server, subgraphs, the proof-of-solvency da Parallel runs an **x402 facilitator**: an off-chain service that verifies an agent's signed payment, then settles it on-chain, so any API can charge AI agents per request. Two facts matter before you depend on it: -- **The facilitator is not audited and not open source.** The audits on the [audits page](/security/audits) (Bail Security, Cyfrin, Certora) cover the protocol smart contracts the settlement goes through, not the hosted service itself. The middleware and agent SDKs are MIT-licensed on npm; the facilitator is a closed service operated by Parallel. -- **It is a single dependency.** If it is down, slow (the SDK times out after 10 seconds on `verify`, 60 on `settle`) or misbehaving, agents cannot pay and merchants cannot get paid until it recovers. +- **The facilitator is not audited and not open source.** The audits on the [audits page](/security/audits) (Bail Security, Cyfrin, Certora) cover the protocol smart contracts the settlement goes through, not the hosted service itself. The middleware, the agent SDK and the CLI are MIT-licensed on npm; the facilitator is a closed service operated by Parallel. +- **It is a single dependency.** If it is down, slow (the SDK times out after 10 seconds on `verify` and 60 on `settle`, and retries a settle once when it timed out or could not reach the facilitator) or misbehaving, agents cannot pay and merchants cannot get paid until it recovers. An agent can pay in USDp, USDC or sUSDp only, with gas sponsored on Base, HyperEVM and Avalanche (1,000 transactions per agent per month); on Ethereum it pays its own gas. A leaked agent key drains whatever that wallet holds, and a token-swapping settlement fails when the Parallelizer is paused (`PARALLELIZER_PAUSED`). @@ -221,9 +221,10 @@ The **MCP server** and **CLI** are a different dependency: the MCP server never ### How Parallel mitigates it -- **Verify, then settle.** The facilitator checks the signature off-chain before the merchant's handler runs, and submits the on-chain transfer only after a success response; a failed request is never charged, and a settle without a prior verify (or after the 120-second verify window) is rejected. See [verify vs settle](/agents/x402/verify-vs-settle). +- **Verify, then settle.** The facilitator checks the signature off-chain before the merchant's handler runs, and submits the on-chain transfer only after a success response; a failed request is never charged. A settle must present the token the facilitator issued at verify for that payment, required since 1 October 2026, and a settle without a verified payment is rejected. See [verify vs settle](/agents/x402/verify-vs-settle). +- **One settlement per payment.** The facilitator claims a payment before it submits anything, so the same payment never settles twice, and a settle repeated after a lost answer gets the recorded outcome instead of a second transfer. - **Non-custodial.** Funds settle straight to the merchant's `payTo` wallet: the facilitator never holds them, so there is nothing to withdraw or lose if it disappears; an unsettled authorization simply expires. -- **Bounded authorizations.** Every payment carries an amount, a chain, an expiry and a nonce; replays, expired signatures and chain mismatches are rejected and each signer is rate-limited hourly. See the [error codes page](/agents/x402/error-codes). +- **Bounded authorizations.** Every payment carries an amount, a chain, an expiry and a nonce; replays, expired signatures and chain mismatches are rejected and each signer is rate-limited hourly. Verify also refuses a payload that does not have its route's shape, does not deliver the asset the merchant requires, or does not pay the merchant's `payTo`. See the [error codes page](/agents/x402/error-codes). - **Audited settlement path.** The contracts that move tokens are the audited protocol contracts; gas sponsoring alone cannot move funds. - **Unsigned by design.** Every MCP write tool simulates the transaction and returns `simulation.success`, a revert reason on failure, and business warnings before you sign, such as the staking warnings in section 7. See [how MCP transactions work](/agents/mcp/transactions). @@ -231,7 +232,7 @@ The **MCP server** and **CLI** are a different dependency: the MCP server never - **Keep agent wallets small.** Fund an agent with only what it needs next and top it up, rather than holding a treasury behind a server-side key; use a dedicated wallet for the CLI, never your main one. - **Confirm settlement yourself.** Merchant [webhooks](/agents/x402/webhooks) are on the roadmap, not live: read the `payment-response` header (it carries the on-chain `txHash`) or watch your `payTo` wallet before treating a request as paid. -- **Handle the facilitator being down.** Catch `FACILITATOR_UNAVAILABLE` and `FACILITATOR_INVALID_RESPONSE` and decide whether to fail closed or serve unpaid. +- **Handle the facilitator being down.** Catch `FACILITATOR_UNAVAILABLE` and `FACILITATOR_INVALID_RESPONSE` (and `SETTLE_TIMEOUT` when you call the facilitator client yourself) and decide whether to fail closed or serve unpaid. Behind the middleware, a failed settlement answers the agent `402` with `PAYMENT_SETTLEMENT_FAILED` and a `reason`; alert on `AMOUNT_MISMATCH`, which means a metered settlement was confirmed for another amount than the one asked. - **Treat the facilitator as a vendor.** If your business cannot tolerate an unaudited hosted service, settle against the audited contracts yourself. - **Read before you sign.** Inspect the `to`, `chainId`, `value` and warnings of every transaction an MCP client shows you, and replace the default unlimited approval with an exact one if you prefer. From 067d16e1e513d1484c09970675ca95f7327f8b67 Mon Sep 17 00:00:00 2001 From: Noah Boisserie <51783223+JeanBrasse@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:10:34 +0400 Subject: [PATCH 2/8] =?UTF-8?q?docs(x402):=20QA's=20notes=20on=20#33=20?= =?UTF-8?q?=E2=80=94=20what=20the=20payment=20queue=20does=20and=20does=20?= =?UTF-8?q?not=20prevent,=20which=20settlement=20failures=20ask=20for=20a?= =?UTF-8?q?=20check=20with=20the=20merchant,=20and=20a=20Next.js=20tab=20t?= =?UTF-8?q?hat=20compiles?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - agent-quickstart, the safety model: a wrapper's queue keeps dailyBudget exact but does not set aside what it signed; two payments signed together can each fit a balance that covers one, and the chain refuses the second settlement (INSUFFICIENT_BALANCE), possibly after the merchant has served. QA reproduced it with 0.015 USDp and two 0.01 payments. - agent-quickstart, when the settlement fails: FACILITATOR_INVALID_RESPONSE, AMOUNT_MISMATCH and SETTLE_TOKEN_REQUIRED/INVALID ask for a check with the merchant, as the message @parallel-protocol/x402 0.8.0 sends the agent for each says. So does AUTHORIZATION_USED: the facilitator answers it as a 409, consumed or cancelled on-chain and not settled by it, and if someone else settled the authorization, the merchant was paid. The SDK settles once the handler has answered, before it sends the response. - quickstart, Next.js tab: payTo as const, and the handler returns NextResponse.json as withPayment's handler type requires; it compiles in strict TypeScript against x402 0.8.0 and Next 15.5.27 (it did not before this PR either). - concepts: the metered handler gets maxTimeoutSeconds minus 120 s, and 30 s at least. Co-Authored-By: Claude Opus 5.5 --- src/pages/agents/x402/agent-quickstart.mdx | 16 +++++++++++++--- src/pages/agents/x402/concepts.mdx | 2 +- src/pages/agents/x402/quickstart.mdx | 5 +++-- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/pages/agents/x402/agent-quickstart.mdx b/src/pages/agents/x402/agent-quickstart.mdx index 719730e..bc0645e 100644 --- a/src/pages/agents/x402/agent-quickstart.mdx +++ b/src/pages/agents/x402/agent-quickstart.mdx @@ -92,9 +92,18 @@ Metered payments are made in USDp. The cap counts in full against `maxAmount` an ## When the settlement fails -The merchant settles after it has answered. If that settlement fails, the agent gets a `402` instead of the response, with a JSON body: `error` is `PAYMENT_SETTLEMENT_FAILED`, `reason` says why in a code, and `message` in a sentence. `payFetch` hands that response back as it is: it does not pay again. +The merchant settles once its handler has answered, before it sends the response. If that settlement fails, the agent gets a `402` instead of the response, with a JSON body: `error` is `PAYMENT_SETTLEMENT_FAILED`, `reason` says why in a code, and `message` in a sentence. `payFetch` hands that response back as it is: it does not pay again. -Read `reason` before signing anything else. `INSUFFICIENT_BALANCE` (fund the wallet first), `PAYMENT_EXPIRED` and `AUTHORIZATION_USED` ask for a new payment, and `RELAYER_UNAVAILABLE` for a new one later. `SETTLE_TIMEOUT`, `FACILITATOR_UNAVAILABLE`, `SETTLE_IN_PROGRESS` and `RECEIPT_UNAVAILABLE` mean the first payment may still settle: check with the merchant before you pay again. See also the [error codes](/agents/x402/error-codes). +Read `reason` before signing anything else: + +- `INSUFFICIENT_BALANCE` (fund the wallet first) and `PAYMENT_EXPIRED` ask for a new payment, and `RELAYER_UNAVAILABLE` for a new one later. +- For these, check with the merchant before you pay again: + - `SETTLE_TIMEOUT`, `FACILITATOR_UNAVAILABLE`, `FACILITATOR_INVALID_RESPONSE`, `SETTLE_IN_PROGRESS` and `RECEIPT_UNAVAILABLE`: the first payment may have settled, or may still settle. + - `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. + - `AUTHORIZATION_USED`: the authorization was consumed or cancelled on-chain, and not by this facilitator. If someone else settled it, the merchant was paid. + +See also the [error codes](/agents/x402/error-codes). ## The safety model @@ -102,7 +111,8 @@ Read `reason` before signing anything else. `INSUFFICIENT_BALANCE` (fund the wal - **`maxAmount` is enforced client-side** against a verified token catalog — a merchant cannot re-scale amounts or trick the agent into overpaying. - **You only pay for success.** The merchant settles the payment only when it serves a successful response; an API error means nothing is charged, and unsettled authorizations simply expire. - **One payment settles once.** The facilitator claims a payment before it submits it, so the same authorization never settles twice. -- **One payment at a time.** A wrapper signs one payment at a time, so concurrent invoices never spend the same balance twice, and it never retries a payment on its own. A payment can still settle when the paid retry fails on the network: treat non-idempotent paid requests accordingly. +- **One payment at a time.** A wrapper signs one payment at a time, which keeps `dailyBudget` exact, and it never retries a payment on its own. It does not set aside what it has signed: each payment is checked against the wallet's on-chain balance, which a signed payment lowers only when it settles. Two payments signed together can each fit a balance that covers only one. The chain still refuses a double spend, so the second settlement fails with `INSUFFICIENT_BALANCE`, possibly after the merchant has served the request. +- **A payment can settle even when the paid retry fails on the network.** Treat non-idempotent paid requests accordingly. ## Next steps diff --git a/src/pages/agents/x402/concepts.mdx b/src/pages/agents/x402/concepts.mdx index 16530e0..1aafc29 100644 --- a/src/pages/agents/x402/concepts.mdx +++ b/src/pages/agents/x402/concepts.mdx @@ -29,7 +29,7 @@ A route is priced in one of two schemes: - **`exact`**, the default: the agent signs the price, and you receive it. - **`upto`**, for a resource whose cost is only known once it is served, such as an LLM completion: the agent signs the price as a cap, valid for the route's `maxTimeoutSeconds` (3,600 at most). Your handler names the amount it actually charges, and the escrow refunds the rest on-chain in the same settlement. Metered routes are paid in USDp only. -On a metered route the SDK keeps the last two minutes of that window for the settlement and its retry: on Express, Hono and Next.js the handler gets `maxTimeoutSeconds` minus 120 seconds. A settlement the facilitator confirms for another amount than the one your handler asked for is refused with `AMOUNT_MISMATCH` and the response is discarded. Alert on it: money moved, and the agent was not served. The configuration, with the `payment-settle-amount` header and the `meter` function, is in the [package README](https://www.npmjs.com/package/@parallel-protocol/x402). +On a metered route the SDK keeps up to the last two minutes of that window for the settlement and its retry: on Express, Hono and Next.js the handler gets `maxTimeoutSeconds` minus 120 seconds, and 30 seconds at least. A settlement the facilitator confirms for another amount than the one your handler asked for is refused with `AMOUNT_MISMATCH` and the response is discarded. Alert on it: money moved, and the agent was not served. The configuration, with the `payment-settle-amount` header and the `meter` function, is in the [package README](https://www.npmjs.com/package/@parallel-protocol/x402). ## Supported stablecoins diff --git a/src/pages/agents/x402/quickstart.mdx b/src/pages/agents/x402/quickstart.mdx index 72b7a3b..d10fcfc 100644 --- a/src/pages/agents/x402/quickstart.mdx +++ b/src/pages/agents/x402/quickstart.mdx @@ -60,17 +60,18 @@ app.listen(3000); ```ts // app/api/data/route.ts +import { NextResponse } from "next/server"; import { withPayment } from "@parallel-protocol/x402/next"; const config = { facilitator: { url: "https://agents.parallel.best" }, routes: { - "/api/data": { price: "0.10", network: "ethereum", payTo: "0xYourAddress" }, + "/api/data": { price: "0.10", network: "ethereum", payTo: "0xYourAddress" as const }, }, }; export const GET = withPayment(config, async (req) => { - return Response.json({ data: "protected content" }); + return NextResponse.json({ data: "protected content" }); }); ``` From 24f286cb0c5b18441709a8e1dc92f1525c9fdb34 Mon Sep 17 00:00:00 2001 From: Noah Boisserie <51783223+JeanBrasse@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:35:23 +0400 Subject: [PATCH 3/8] docs(x402): SUBMISSION_FAILED asks for a check with the merchant, and a repeated settle returns the confirmation or the refusal - agent-quickstart, when the settlement fails: SUBMISSION_FAILED joins the reasons that ask for a check with the merchant before paying again. The facilitator also returns it when a settlement is interrupted after a transaction went out, an outcome it cannot know yet, so paying again could pay twice. - concepts: a settle repeated after a lost answer returns what was recorded, the confirmation, marked alreadySettled, or the refusal. Co-Authored-By: Claude Opus 5.5 --- src/pages/agents/x402/agent-quickstart.mdx | 1 + src/pages/agents/x402/concepts.mdx | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/pages/agents/x402/agent-quickstart.mdx b/src/pages/agents/x402/agent-quickstart.mdx index bc0645e..393cfe2 100644 --- a/src/pages/agents/x402/agent-quickstart.mdx +++ b/src/pages/agents/x402/agent-quickstart.mdx @@ -99,6 +99,7 @@ Read `reason` before signing anything else: - `INSUFFICIENT_BALANCE` (fund the wallet first) and `PAYMENT_EXPIRED` ask for a new payment, and `RELAYER_UNAVAILABLE` for a new one later. - For these, check with the merchant before you pay again: - `SETTLE_TIMEOUT`, `FACILITATOR_UNAVAILABLE`, `FACILITATOR_INVALID_RESPONSE`, `SETTLE_IN_PROGRESS` and `RECEIPT_UNAVAILABLE`: the first payment may have settled, or may still settle. + - `SUBMISSION_FAILED`: the settlement may have been interrupted after a transaction went out, so the payment may still settle. - `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. - `AUTHORIZATION_USED`: the authorization was consumed or cancelled on-chain, and not by this facilitator. If someone else settled it, the merchant was paid. diff --git a/src/pages/agents/x402/concepts.mdx b/src/pages/agents/x402/concepts.mdx index 1aafc29..fd96b71 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, marked `alreadySettled`. 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 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. ## Exact and metered payments From 60e0b2b2a32932244ab7a5ba07e8fece02533263 Mon Sep 17 00:00:00 2001 From: Noah Boisserie <51783223+JeanBrasse@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:53:15 +0400 Subject: [PATCH 4/8] docs(x402): every settlement-failure reason gets advice that cannot make the agent pay twice When the settlement fails, in the agent quickstart: - TX_REVERTED joins the reasons that ask for a new payment. Like INSUFFICIENT_BALANCE, PAYMENT_EXPIRED and RELAYER_UNAVAILABLE, the payment was not taken and the facilitator will not settle it. - Four reasons join the ones that ask for a check with the merchant first: - UNKNOWN: the SDK could not read why the settlement failed; - PAYMENT_NOT_VERIFIED: a repeated settle also gets it after a first attempt whose transaction may still be mined; - PARALLELIZER_PAUSED and SERVICE_UNAVAILABLE: refused before anything was sent, the payment can still be settled until it expires. - Any reason the list does not name asks for a check with the merchant too, and the error codes page gives the detail. Co-Authored-By: Claude Opus 5.5 --- src/pages/agents/x402/agent-quickstart.mdx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/pages/agents/x402/agent-quickstart.mdx b/src/pages/agents/x402/agent-quickstart.mdx index 393cfe2..3da4847 100644 --- a/src/pages/agents/x402/agent-quickstart.mdx +++ b/src/pages/agents/x402/agent-quickstart.mdx @@ -96,15 +96,18 @@ The merchant settles once its handler has answered, before it sends the response Read `reason` before signing anything else: -- `INSUFFICIENT_BALANCE` (fund the wallet first) and `PAYMENT_EXPIRED` ask for a new payment, and `RELAYER_UNAVAILABLE` for a new one later. +- `INSUFFICIENT_BALANCE` (fund the wallet first), `PAYMENT_EXPIRED` and `TX_REVERTED` ask for a new payment, and `RELAYER_UNAVAILABLE` for a new one later: the payment was not taken, and the facilitator will not settle it. - For these, check with the merchant before you pay again: - `SETTLE_TIMEOUT`, `FACILITATOR_UNAVAILABLE`, `FACILITATOR_INVALID_RESPONSE`, `SETTLE_IN_PROGRESS` and `RECEIPT_UNAVAILABLE`: the first payment may have settled, or may still settle. - `SUBMISSION_FAILED`: the settlement may have been interrupted after a transaction went out, so the payment may still settle. + - `UNKNOWN`: the merchant's SDK could not read why the settlement failed, so the payment may still settle. + - `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. - `AUTHORIZATION_USED`: the authorization was consumed or cancelled on-chain, and not by this facilitator. If someone else settled it, the merchant was paid. -See also the [error codes](/agents/x402/error-codes). +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. ## The safety model From 33e04cfe6c45c359d25415a1126b3956bc1e6458 Mon Sep 17 00:00:00 2001 From: Noah Boisserie <51783223+JeanBrasse@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:37:36 +0400 Subject: [PATCH 5/8] docs(x402): x402-fetch 0.3.0 rejects a refused paid request with X402FetchError, and x402 0.8.1 calls the facilitator over https only agent-quickstart - x402-fetch 0.3.0 is the version a fresh install gets, still with the CLI 0.4.1. A project on 0.2 moves by installing it, since a ^0.2 range does not reach 0.3. - A paid request the merchant answers with 402 now rejects with X402FetchError instead of returning the response: - PAYMENT_REFUSED when the merchant asks for payment again (a new section); - SETTLEMENT_FAILED when it could not settle. Both carry reason and retryAfter. The code sample, the refusals table and "When the settlement fails" say where the agent reads them on 0.3.0, and on earlier versions. - The safety model: the engine now gets only the settings it needs, not the caller's whole environment. quickstart and migrate-from-coinbase-x402 - The facilitator URL must use https, plain http being accepted only on localhost, 127.0.0.1 and [::1]. A redirect is never followed: it fails the call with FACILITATOR_UNAVAILABLE. Both since x402 0.8.1. No page mentions FacilitatorClient.pay(), which 0.8.1 deprecates. Sources: the changelogs, READMEs and type definitions of x402-fetch 0.3.0 and x402 0.8.1 on npm (sdk-merchant #62 and #63, published by #64). Co-Authored-By: Claude Opus 5.5 --- .../recipes/migrate-from-coinbase-x402.mdx | 2 ++ src/pages/agents/x402/agent-quickstart.mdx | 35 ++++++++++++++++--- src/pages/agents/x402/quickstart.mdx | 2 ++ 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx b/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx index c2c9315..8d4179d 100644 --- a/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx +++ b/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx @@ -42,6 +42,8 @@ app.use(paymentMiddleware({ Install `@parallel-protocol/x402` 0.8.0 or later: since 1 October 2026 the facilitator refuses a settle that does not present the token it issued at verify, and earlier versions do not send it. +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`. + The shape changes — `payTo` moves into the route, and prices drop the `$` prefix — but every concept maps one-to-one. Agents paying in USDC keep paying in USDC. Agents holding USDp can now pay you natively, with the facilitator handling conversion at no extra fee. ## What you gain diff --git a/src/pages/agents/x402/agent-quickstart.mdx b/src/pages/agents/x402/agent-quickstart.mdx index 3da4847..c1c163c 100644 --- a/src/pages/agents/x402/agent-quickstart.mdx +++ b/src/pages/agents/x402/agent-quickstart.mdx @@ -15,7 +15,9 @@ This guide makes an agent pay x402 APIs autonomously. The whole integration is o npm install @parallel-protocol/x402-fetch ``` -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. 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 this release 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.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. + +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). ## 2. Fund a wallet @@ -44,8 +46,10 @@ try { console.log("paid:", receipt?.txHash, "gas sponsored:", receipt?.gasSponsored); } catch (err) { if (err instanceof X402FetchError) { - // A guard refused the invoice BEFORE signing — nothing was spent. - console.error(`refused [${err.code}]: ${err.message}`); + // PAYMENT_REFUSED and SETTLEMENT_FAILED: the merchant answered the paid + // request with 402, see err.reason and err.retryAfter. Every other code + // is raised before any payment is sent. + console.error(`payment failed [${err.code}]: ${err.message}`); } } ``` @@ -84,19 +88,39 @@ Every guard fires **before** the agent signs — a refused invoice never spends | `ENGINE_FAILED` | Payment preparation failed — the message carries the cause (usually balance, or a transient RPC error), and `engineCode` the engine's code, such as `INSUFFICIENT_BALANCE`. | | `ENGINE_TIMEOUT` | Payment preparation exceeded its time budget. | +Two more codes come after the payment is sent, when the merchant answers the paid request with `402`: `PAYMENT_REFUSED` and `SETTLEMENT_FAILED`. The sections below describe them. + ## Metered invoices A merchant can invoice a route with the `upto` scheme: a cap rather than a price, for a resource whose cost is only known once it is served. The agent signs the cap for the window the merchant announced (`maxTimeoutSeconds`, 3,600 seconds at most), the merchant charges its actual cost, and the escrow refunds the rest on-chain in the same settlement. The receipt's `amountSettled` is what was really paid. Metered payments are made in USDp. The cap counts in full against `maxAmount` and `dailyBudget`, and the refund is never credited back to the day's budget. +## When the merchant refuses the payment + +The merchant has the facilitator verify the payment before it runs its handler. If the facilitator refuses it, or the merchant cannot reach the facilitator, the merchant answers the paid request with a new `402` invoice that carries the refusal. `payFetch` then rejects with an `X402FetchError` whose `code` is `PAYMENT_REFUSED`, and it does not pay again. The error carries: + +- `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. + +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. + ## When the settlement fails -The merchant settles once its handler has answered, before it sends the response. If that settlement fails, the agent gets a `402` instead of the response, with a JSON body: `error` is `PAYMENT_SETTLEMENT_FAILED`, `reason` says why in a code, and `message` in a sentence. `payFetch` hands that response back as it is: it does not pay again. +The merchant settles once its handler has answered, before it sends the response. If that settlement fails, the merchant answers `402` instead of the response, with a JSON body: `error` is `PAYMENT_SETTLEMENT_FAILED`, `reason` says why in a code, and `message` in a sentence. + +`payFetch` then rejects with an `X402FetchError` whose `code` is `SETTLEMENT_FAILED`, and it does not pay again. The error carries: + +- `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. + +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. Read `reason` before signing anything else: -- `INSUFFICIENT_BALANCE` (fund the wallet first), `PAYMENT_EXPIRED` and `TX_REVERTED` ask for a new payment, and `RELAYER_UNAVAILABLE` for a new one later: the payment was not taken, and the facilitator will not settle it. +- `INSUFFICIENT_BALANCE` (fund the wallet first), `PAYMENT_EXPIRED` and `TX_REVERTED` ask for a new payment, and `RELAYER_UNAVAILABLE` for a new one later, after `retryAfter` when the error carries one: the payment was not taken, and the facilitator will not settle it. - For these, check with the merchant before you pay again: - `SETTLE_TIMEOUT`, `FACILITATOR_UNAVAILABLE`, `FACILITATOR_INVALID_RESPONSE`, `SETTLE_IN_PROGRESS` and `RECEIPT_UNAVAILABLE`: the first payment may have settled, or may still settle. - `SUBMISSION_FAILED`: the settlement may have been interrupted after a transaction went out, so the payment may still settle. @@ -116,6 +140,7 @@ For any other reason, check with the merchant as well before you pay again. The - **You only pay for success.** The merchant settles the payment only when it serves a successful response; an API error means nothing is charged, and unsettled authorizations simply expire. - **One payment settles once.** The facilitator claims a payment before it submits it, so the same authorization never settles twice. - **One payment at a time.** A wrapper signs one payment at a time, which keeps `dailyBudget` exact, and it never retries a payment on its own. It does not set aside what it has signed: each payment is checked against the wallet's on-chain balance, which a signed payment lowers only when it settles. Two payments signed together can each fit a balance that covers only one. The chain still refuses a double spend, so the second settlement fails with `INSUFFICIENT_BALANCE`, possibly after the merchant has served the request. +- **The engine gets only what it needs.** The signing engine runs as a child process of your agent. It receives the key and the settings it needs to start and reach the chain: `ALCHEMY_API_KEY`, the system paths, and the runtime's own settings (proxy, certificates, TLS and OpenSSL, `NODE_OPTIONS`). Since version 0.3.0, the rest of your environment is not passed to it. - **A payment can settle even when the paid retry fails on the network.** Treat non-idempotent paid requests accordingly. ## Next steps diff --git a/src/pages/agents/x402/quickstart.mdx b/src/pages/agents/x402/quickstart.mdx index d10fcfc..013e9c5 100644 --- a/src/pages/agents/x402/quickstart.mdx +++ b/src/pages/agents/x402/quickstart.mdx @@ -30,6 +30,8 @@ npm install express # or: next · fastify · hono Point the middleware at the facilitator, then declare which routes are paid, at what price, on which network, and where funds should settle. +Write the facilitator's URL with https, as below. Since version 0.8.1, the SDK refuses any other URL with an `X402ConfigError` when the middleware is created, except plain http on `localhost`, `127.0.0.1` and `[::1]`: `http://agents.parallel.best` is refused. The SDK calls that address only and never follows a redirect, which fails the call with `FACILITATOR_UNAVAILABLE`. + From 21dcdfc80f3937a7660e72f240408e4c843502d7 Mon Sep 17 00:00:00 2001 From: Noah Boisserie <51783223+JeanBrasse@users.noreply.github.com> Date: Mon, 5 Oct 2026 05:45:22 +0400 Subject: [PATCH 6/8] docs(x402): decode the receipt outside the payment's try decodePaymentResponse throws INVALID_INVOICE when the receipt header cannot be decoded, after the request was paid. In the quickstart it ran inside the try whose comment says every other code comes before any payment, so an agent following it could pay twice. It now runs after the try, with a comment saying the request is already paid. Also say that CLI 0.4.1 still loads a .env file from the working directory or a parent, and ~/.parallel/config.toml: the environment list does not cover files on disk. Co-Authored-By: Claude Opus 5.5 --- src/pages/agents/x402/agent-quickstart.mdx | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/pages/agents/x402/agent-quickstart.mdx b/src/pages/agents/x402/agent-quickstart.mdx index c1c163c..084154b 100644 --- a/src/pages/agents/x402/agent-quickstart.mdx +++ b/src/pages/agents/x402/agent-quickstart.mdx @@ -38,12 +38,9 @@ const payFetch = wrapFetchWithPayment(fetch, { maxAmount: "1", // hard spend cap per request }); +let res: Response; try { - const res = await payFetch("https://api.parallel.best/public/x402/base/snapshot"); - const data = await res.json(); - - const receipt = decodePaymentResponse(res); - console.log("paid:", receipt?.txHash, "gas sponsored:", receipt?.gasSponsored); + res = await payFetch("https://api.parallel.best/public/x402/base/snapshot"); } catch (err) { if (err instanceof X402FetchError) { // PAYMENT_REFUSED and SETTLEMENT_FAILED: the merchant answered the paid @@ -51,7 +48,15 @@ try { // is raised before any payment is sent. console.error(`payment failed [${err.code}]: ${err.message}`); } + throw err; } + +const data = await res.json(); + +// The request is paid by now: if the receipt header cannot be decoded, this +// throws INVALID_INVOICE, which is no reason to pay again. +const receipt = decodePaymentResponse(res); +console.log("paid:", receipt?.txHash, "gas sponsored:", receipt?.gasSponsored); ``` That's the entire agent. The first request costs nothing (it just reads the `402` invoice); the paid retry carries the signed authorization. @@ -82,7 +87,7 @@ Every guard fires **before** the agent signs — a refused invoice never spends | `BUDGET_EXCEEDED` | The invoice would take the day's spend past `dailyBudget`. | | `CHAIN_MISMATCH` | The invoice targets a different chain than configured. | | `UNSUPPORTED_SCHEME` | The invoice offers only schemes this client cannot pay on the configured chain. It pays `exact` invoices, and `upto` invoices in USDp. | -| `INVALID_INVOICE` | The `402` response is malformed. | +| `INVALID_INVOICE` | The `402` response is malformed. `decodePaymentResponse` also throws it, after the payment, when the receipt header cannot be decoded. | | `INSECURE_URL` | The merchant URL is plain `http://` (localhost excepted). | | `ENGINE_NOT_FOUND` | The payment engine, `@parallel-protocol/cli`, could not be found. | | `ENGINE_FAILED` | Payment preparation failed — the message carries the cause (usually balance, or a transient RPC error), and `engineCode` the engine's code, such as `INSUFFICIENT_BALANCE`. | @@ -140,7 +145,7 @@ For any other reason, check with the merchant as well before you pay again. The - **You only pay for success.** The merchant settles the payment only when it serves a successful response; an API error means nothing is charged, and unsettled authorizations simply expire. - **One payment settles once.** The facilitator claims a payment before it submits it, so the same authorization never settles twice. - **One payment at a time.** A wrapper signs one payment at a time, which keeps `dailyBudget` exact, and it never retries a payment on its own. It does not set aside what it has signed: each payment is checked against the wallet's on-chain balance, which a signed payment lowers only when it settles. Two payments signed together can each fit a balance that covers only one. The chain still refuses a double spend, so the second settlement fails with `INSUFFICIENT_BALANCE`, possibly after the merchant has served the request. -- **The engine gets only what it needs.** The signing engine runs as a child process of your agent. It receives the key and the settings it needs to start and reach the chain: `ALCHEMY_API_KEY`, the system paths, and the runtime's own settings (proxy, certificates, TLS and OpenSSL, `NODE_OPTIONS`). Since version 0.3.0, the rest of your environment is not passed to it. +- **The engine gets only what it needs.** The signing engine runs as a child process of your agent. It receives the key and the settings it needs to start and reach the chain: `ALCHEMY_API_KEY`, the system paths, and the runtime's own settings (proxy, certificates, TLS and OpenSSL, `NODE_OPTIONS`). Since version 0.3.0, the rest of your environment is not passed to it. That list does not cover files on disk: version 0.4.1 of `@parallel-protocol/cli` still loads a `.env` file from your agent's working directory or any parent directory, and `~/.parallel/config.toml`. - **A payment can settle even when the paid retry fails on the network.** Treat non-idempotent paid requests accordingly. ## Next steps From 8774ba3b81b051ac3055da499e222ec50782d14e Mon Sep 17 00:00:00 2001 From: Noah Boisserie <51783223+JeanBrasse@users.noreply.github.com> Date: Mon, 5 Oct 2026 06:39:58 +0400 Subject: [PATCH 7/8] docs(x402): 0.8.1 minimum, and three precisions in the agent quickstart - Merchant quickstart and Coinbase migration recipe: use @parallel-protocol/x402 0.8.1 or later. 0.8.0 is the first to send the settle token; 0.8.1 adds the https-only facilitator URL and the no-redirect rule these pages already describe. - Agent quickstart: - CLI 0.4.1 falls back to a .env found from its install directory, which is the project's, when none is found from the working directory; - the receipt comment says any payment was sent by now, rather than that the request is paid; - the two codes that come after the payment are those from payFetch. Co-Authored-By: Claude Opus 5.5 --- src/pages/agents/recipes/migrate-from-coinbase-x402.mdx | 2 +- src/pages/agents/x402/agent-quickstart.mdx | 6 +++--- src/pages/agents/x402/quickstart.mdx | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx b/src/pages/agents/recipes/migrate-from-coinbase-x402.mdx index 8d4179d..f399fc0 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.0 or later: since 1 October 2026 the facilitator refuses a settle that does not present the token it issued at verify, and earlier versions do not send it. +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. 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 084154b..493d249 100644 --- a/src/pages/agents/x402/agent-quickstart.mdx +++ b/src/pages/agents/x402/agent-quickstart.mdx @@ -53,7 +53,7 @@ try { const data = await res.json(); -// The request is paid by now: if the receipt header cannot be decoded, this +// Any payment was sent by now: if the receipt header cannot be decoded, this // throws INVALID_INVOICE, which is no reason to pay again. const receipt = decodePaymentResponse(res); console.log("paid:", receipt?.txHash, "gas sponsored:", receipt?.gasSponsored); @@ -93,7 +93,7 @@ Every guard fires **before** the agent signs — a refused invoice never spends | `ENGINE_FAILED` | Payment preparation failed — the message carries the cause (usually balance, or a transient RPC error), and `engineCode` the engine's code, such as `INSUFFICIENT_BALANCE`. | | `ENGINE_TIMEOUT` | Payment preparation exceeded its time budget. | -Two more codes come after the payment is sent, when the merchant answers the paid request with `402`: `PAYMENT_REFUSED` and `SETTLEMENT_FAILED`. The sections below describe them. +Two more codes from `payFetch` come after the payment is sent, when the merchant answers the paid request with `402`: `PAYMENT_REFUSED` and `SETTLEMENT_FAILED`. The sections below describe them. ## Metered invoices @@ -145,7 +145,7 @@ For any other reason, check with the merchant as well before you pay again. The - **You only pay for success.** The merchant settles the payment only when it serves a successful response; an API error means nothing is charged, and unsettled authorizations simply expire. - **One payment settles once.** The facilitator claims a payment before it submits it, so the same authorization never settles twice. - **One payment at a time.** A wrapper signs one payment at a time, which keeps `dailyBudget` exact, and it never retries a payment on its own. It does not set aside what it has signed: each payment is checked against the wallet's on-chain balance, which a signed payment lowers only when it settles. Two payments signed together can each fit a balance that covers only one. The chain still refuses a double spend, so the second settlement fails with `INSUFFICIENT_BALANCE`, possibly after the merchant has served the request. -- **The engine gets only what it needs.** The signing engine runs as a child process of your agent. It receives the key and the settings it needs to start and reach the chain: `ALCHEMY_API_KEY`, the system paths, and the runtime's own settings (proxy, certificates, TLS and OpenSSL, `NODE_OPTIONS`). Since version 0.3.0, the rest of your environment is not passed to it. That list does not cover files on disk: version 0.4.1 of `@parallel-protocol/cli` still loads a `.env` file from your agent's working directory or any parent directory, and `~/.parallel/config.toml`. +- **The engine gets only what it needs.** The signing engine runs as a child process of your agent. It receives the key and the settings it needs to start and reach the chain: `ALCHEMY_API_KEY`, the system paths, and the runtime's own settings (proxy, certificates, TLS and OpenSSL, `NODE_OPTIONS`). Since version 0.3.0, the rest of your environment is not passed to it. That list does not cover files on disk: version 0.4.1 of `@parallel-protocol/cli` still loads a `.env` file from your agent's working directory or any parent directory, or, failing that, from where the CLI is installed or any parent directory, which finds your project's `.env`. It also reads `~/.parallel/config.toml`. - **A payment can settle even when the paid retry fails on the network.** Treat non-idempotent paid requests accordingly. ## Next steps diff --git a/src/pages/agents/x402/quickstart.mdx b/src/pages/agents/x402/quickstart.mdx index 013e9c5..db5f854 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.0 or later. Since 1 October 2026 the facilitator settles a payment only when the settle presents the token it issued at verify, and earlier versions do not send it: their settlements are refused with `SETTLE_TOKEN_REQUIRED`, and the agent gets a `402` instead of your response. +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. ::: Install your framework separately — they are optional peer dependencies: From 12f8573e407f5a342c562410f715e3a377b0391d Mon Sep 17 00:00:00 2001 From: Noah Boisserie <51783223+JeanBrasse@users.noreply.github.com> Date: Mon, 5 Oct 2026 07:22:34 +0400 Subject: [PATCH 8/8] docs(x402): config.toml is not read for a payment; INVALID_INVOICE causes - The safety model no longer says the CLI reads ~/.parallel/config.toml. The CLI 0.4.1 reads it only for defaults that x402-fetch already passes (--chain and --wallet), so a payment does not read it. - The INVALID_INVOICE row names the malformed invoice fields, as in the x402-fetch 0.3.0 README: payTo or asset not an address, an amount that is not a positive integer, or decimals that contradict the token catalog or fall outside 0 to 36. A 402 without a readable invoice is not one of them. Co-Authored-By: Claude Opus 5.5 --- src/pages/agents/x402/agent-quickstart.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pages/agents/x402/agent-quickstart.mdx b/src/pages/agents/x402/agent-quickstart.mdx index 493d249..bf08abf 100644 --- a/src/pages/agents/x402/agent-quickstart.mdx +++ b/src/pages/agents/x402/agent-quickstart.mdx @@ -87,7 +87,7 @@ Every guard fires **before** the agent signs — a refused invoice never spends | `BUDGET_EXCEEDED` | The invoice would take the day's spend past `dailyBudget`. | | `CHAIN_MISMATCH` | The invoice targets a different chain than configured. | | `UNSUPPORTED_SCHEME` | The invoice offers only schemes this client cannot pay on the configured chain. It pays `exact` invoices, and `upto` invoices in USDp. | -| `INVALID_INVOICE` | The `402` response is malformed. `decodePaymentResponse` also throws it, after the payment, when the receipt header cannot be decoded. | +| `INVALID_INVOICE` | An invoice field is malformed: a `payTo` or `asset` that is not an address, an amount that is not a positive integer, or decimals that contradict the token catalog or fall outside 0 to 36. `decodePaymentResponse` also throws it, after the payment, when the receipt header cannot be decoded. | | `INSECURE_URL` | The merchant URL is plain `http://` (localhost excepted). | | `ENGINE_NOT_FOUND` | The payment engine, `@parallel-protocol/cli`, could not be found. | | `ENGINE_FAILED` | Payment preparation failed — the message carries the cause (usually balance, or a transient RPC error), and `engineCode` the engine's code, such as `INSUFFICIENT_BALANCE`. | @@ -145,7 +145,7 @@ For any other reason, check with the merchant as well before you pay again. The - **You only pay for success.** The merchant settles the payment only when it serves a successful response; an API error means nothing is charged, and unsettled authorizations simply expire. - **One payment settles once.** The facilitator claims a payment before it submits it, so the same authorization never settles twice. - **One payment at a time.** A wrapper signs one payment at a time, which keeps `dailyBudget` exact, and it never retries a payment on its own. It does not set aside what it has signed: each payment is checked against the wallet's on-chain balance, which a signed payment lowers only when it settles. Two payments signed together can each fit a balance that covers only one. The chain still refuses a double spend, so the second settlement fails with `INSUFFICIENT_BALANCE`, possibly after the merchant has served the request. -- **The engine gets only what it needs.** The signing engine runs as a child process of your agent. It receives the key and the settings it needs to start and reach the chain: `ALCHEMY_API_KEY`, the system paths, and the runtime's own settings (proxy, certificates, TLS and OpenSSL, `NODE_OPTIONS`). Since version 0.3.0, the rest of your environment is not passed to it. That list does not cover files on disk: version 0.4.1 of `@parallel-protocol/cli` still loads a `.env` file from your agent's working directory or any parent directory, or, failing that, from where the CLI is installed or any parent directory, which finds your project's `.env`. It also reads `~/.parallel/config.toml`. +- **The engine gets only what it needs.** The signing engine runs as a child process of your agent. It receives the key and the settings it needs to start and reach the chain: `ALCHEMY_API_KEY`, the system paths, and the runtime's own settings (proxy, certificates, TLS and OpenSSL, `NODE_OPTIONS`). Since version 0.3.0, the rest of your environment is not passed to it. That list does not cover files on disk: version 0.4.1 of `@parallel-protocol/cli` still loads a `.env` file from your agent's working directory or any parent directory, or, failing that, from where the CLI is installed or any parent directory, which finds your project's `.env`. - **A payment can settle even when the paid retry fails on the network.** Treat non-idempotent paid requests accordingly. ## Next steps