Skip to content
Merged
6 changes: 5 additions & 1 deletion src/pages/agents/cli/commands.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ parallel pay prepare --amount <n> --recipient <address> [--chain <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 <seconds>` 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
Expand Down Expand Up @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion src/pages/agents/cli/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion src/pages/agents/faq.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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?",
Expand Down
4 changes: 4 additions & 0 deletions src/pages/agents/recipes/migrate-from-coinbase-x402.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ 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.

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
Expand Down
89 changes: 78 additions & 11 deletions src/pages/agents/x402/agent-quickstart.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ 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.

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

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.
Expand All @@ -34,18 +38,25 @@ 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) {
// 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}`);
}
throw err;
}

const data = await res.json();

// 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);
```

That's the entire agent. The first request costs nothing (it just reads the `402` invoice); the paid retry carries the signed authorization.
Expand All @@ -57,29 +68,85 @@ 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

Every guard fires **before** the agent signs — a refused invoice never spends anything. Refusals throw an `X402FetchError` with a `code`:

| 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. |
| `INVALID_INVOICE` | The `402` response is malformed. |
| `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` | 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_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. |

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

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 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, 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.
- `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.

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

- **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, 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`.
- **A payment can settle even when the paid retry fails on the network.** Treat non-idempotent paid requests accordingly.

## Next steps

Expand Down
Loading