218 lines
14 KiB
Markdown
218 lines
14 KiB
Markdown
|
|
# x402 Micropayments
|
|
|
|
x402 is an HTTP payment protocol built on the 402 Payment Required status code. When a server requires payment, the client signs a payment authorization on-chain and retries with the proof.
|
|
|
|
## Client — Access a Paid Endpoint
|
|
|
|
```bash
|
|
twak x402 request <url> --max-payment <atomic>
|
|
```
|
|
|
|
### Flow
|
|
|
|
1. Client sends HTTP request without payment.
|
|
2. Server returns `402 Payment Required` with a challenge listing one or more `accepts` entries (chain + asset + amount + transfer method).
|
|
3. Client picker selects the best entry (EIP-3009 gasless preferred over Permit2). User confirms unless `--yes`.
|
|
4. Client signs a payment authorization (EIP-3009 transferWithAuthorization) or Permit2 witness, attaches it to the payment header — `X-PAYMENT` for V1 challenges, `PAYMENT-SIGNATURE` for V2 — and retries.
|
|
5. Server verifies on-chain settlement and returns the resource.
|
|
|
|
### Examples
|
|
|
|
```bash
|
|
# Minimum: pay up to 0.01 USDC (10000 atomic at 6dp). Prompts for confirmation.
|
|
twak x402 request https://api.example.com/data --max-payment 10000 --json
|
|
|
|
# Skip prompts (auto-confirm payments up to --max-payment)
|
|
twak x402 request https://api.example.com/data --max-payment 10000 --yes --json
|
|
|
|
# Force a specific chain (e.g. settle on BSC instead of Base)
|
|
twak x402 request https://api.example.com/data \
|
|
--max-payment 10000 --prefer-network bsc --yes --json
|
|
|
|
# Force a specific transfer method
|
|
twak x402 request https://api.example.com/data \
|
|
--max-payment 10000 --prefer-method eip3009 --yes --json
|
|
|
|
# Pick a specific token by name substring (case-insensitive) or contract address
|
|
twak x402 request https://api.example.com/data \
|
|
--max-payment 10000000000000000 --prefer-asset "Tether" --yes --json
|
|
|
|
twak x402 request https://api.example.com/data \
|
|
--max-payment 10000 --prefer-asset 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 --yes --json
|
|
|
|
# POST with JSON body
|
|
twak x402 request https://api.example.com/analyze \
|
|
--method POST --body '{"query":"price of ETH"}' \
|
|
--max-payment 10000 --yes --json
|
|
|
|
# First-time Permit2: also skip the one-time approval prompt (you pay gas for this tx)
|
|
twak x402 request https://api.example.com/data \
|
|
--max-payment 10000 --yes --auto-approve --json
|
|
```
|
|
|
|
### Safety
|
|
|
|
- Only `https://` URLs accepted; private/loopback IPs (including IPv4-mapped IPv6 like `::ffff:127.0.0.1`) rejected before any network call.
|
|
- `--max-payment` is required and capped against the server's requested amount; negative server amounts are rejected.
|
|
- Interactive confirmation before signing unless `--yes` is passed. Confirm prompt surfaces the asset contract address so a malicious `extra.name` cannot masquerade as the wrong token.
|
|
- Permit2 first-time approval requires a separate confirmation unless `--auto-approve` is passed (or `--yes` is on, which auto-approves the payment but **not** the Permit2 allowance — keep these independent).
|
|
|
|
### Client Options
|
|
|
|
| Flag | Type | Required | Description |
|
|
|------|------|----------|-------------|
|
|
| `--max-payment <atomic>` | string (integer atomic units) | yes | Max payment to auto-approve, in atomic units of the chosen asset (e.g. `"10000"` = 0.01 USDC at 6dp; `"10000000000000000"` = 0.01 of an 18-dp token). |
|
|
| `--method <method>` | string | no | HTTP method, uppercased before sending (default: `GET`). Not a fixed enum — any verb is accepted. Body is stripped on `GET` and `HEAD`. |
|
|
| `--body <json>` | string | no | Raw request body. Sent verbatim with `Content-Type: application/json`. |
|
|
| `--prefer-network <network>` | string | no | Restrict route to this chain. Accepts a TWAK chain key (`"base"`, `"bsc"`, `"ethereum"`, `"polygon"`, …), a CAIP-2 string (`"eip155:8453"`), or the seller's raw `network` string verbatim (e.g. a V1 challenge's `"smartchain"`). Case-insensitive. AND-combined with `--prefer-method`/`--prefer-asset`. |
|
|
| `--prefer-method <method>` | `eip3009` \| `permit2-exact` \| `permit2` | no | Restrict route to this transfer method. `permit2` is an alias canonicalized to `permit2-exact` — either spelling matches entries advertised as either. Default picker prefers `eip3009` (gasless) when offered. |
|
|
| `--prefer-asset <addr-or-name>` | string | no | Restrict route to this asset. Accepts a contract address (exact, case-insensitive) **or** a token-name substring matched against `extra.name` (`"Tether"`, `"USDC"`, `"United Stables"`). |
|
|
| `--yes` | boolean | no | Skip the per-payment confirmation prompt. Still respects `--max-payment`. |
|
|
| `--auto-approve` | boolean | no | Skip the Permit2 first-time approval prompt and broadcast `approve(Permit2, MAX)` (you pay gas; runs once per token+chain). Independent from `--yes`. |
|
|
| `--password <pw>` | string | no | Wallet password. Resolves from keychain or `TWAK_WALLET_PASSWORD` if omitted. |
|
|
| `--json` | boolean | no | Emit JSON output. Error envelope: `{ "error": <message>, "errorCode": <code> }`. |
|
|
|
|
### Error Codes (JSON output)
|
|
|
|
| `errorCode` | When |
|
|
|-------------|------|
|
|
| `VALIDATION_ERROR` | `http://` URL, private/loopback IP, DNS rebind to a private IP, or invalid `--max-payment`. |
|
|
| `CHAIN_UNSUPPORTED` | The picked route's chain is not in TWAK's chain map. |
|
|
| `NO_MATCHING_ROUTE` | One of `--prefer-network`/`--prefer-method`/`--prefer-asset` filtered out every offered entry. Message includes the active filters and the full offered list. Thrown only by the pre-filter — if entries survive the filter but none is signable, the code is `PAYMENT_INVALID_CHALLENGE` instead. |
|
|
| `PAYMENT_AMOUNT_EXCEEDED` | Server's requested amount exceeds `--max-payment`. |
|
|
| `PAYMENT_INVALID_CHALLENGE` | The 402 body/header is missing required fields, fails schema validation, or no offered entry (after `--prefer-*` filtering) uses a scheme this client can sign (`no supported scheme in 402 response …`). |
|
|
| `PAYMENT_CANCELLED` | User answered `n` at the confirmation prompt. |
|
|
| `PERMIT2_APPROVAL_REQUIRED` | Permit2 route chosen, existing allowance is below the required amount, and the approval prompt was declined. |
|
|
| `TX_FAILED` | The Permit2 approval tx reverted, or was not confirmed within 60s. |
|
|
| `NETWORK_ERROR` | The server returned a non-2xx, non-402 status. |
|
|
|
|
## Quote — Preview Payment Options Without Signing
|
|
|
|
```bash
|
|
twak x402 quote <url>
|
|
```
|
|
|
|
Read-only. Fetches the 402 challenge, parses it, and renders the available payment routes. No wallet password required — no on-chain action is taken.
|
|
|
|
Use this when:
|
|
- The user wants to see what an endpoint charges before committing to pay.
|
|
- An agent needs to surface a route menu to the user so they can pick which asset/chain to settle on.
|
|
- You're debugging a `NO_MATCHING_ROUTE` from `twak x402 request` and want to see what the server actually offered.
|
|
|
|
### Examples
|
|
|
|
```bash
|
|
# Preview a GET endpoint
|
|
twak x402 quote https://api.example.com/data
|
|
|
|
# Preview with the same method + body shape you plan to pay with
|
|
twak x402 quote https://api.example.com/analyze \
|
|
--method POST --body '{"query":"price of ETH"}'
|
|
|
|
# Emit the full JSON shape for scripting / agent consumption
|
|
twak x402 quote https://api.example.com/data --json
|
|
```
|
|
|
|
### Output Shape
|
|
|
|
Text mode renders a table sorted preferred-first plus a `Next:` line containing the literal `twak x402 request …` command you should run to pay. URL, `--method`, and `--body` are shell-quoted in the `Next:` line for safe copy-paste. Routes on chains TWAK does not recognize are dropped silently before rendering (no warning). If nothing remains, text mode prints `No supported route from this endpoint.` and exits `1`; if rows render but none is signable, it prints `No route here can be signed by this client.` and exits `1`.
|
|
|
|
JSON mode emits the full `QuoteX402Result`:
|
|
|
|
```jsonc
|
|
{
|
|
"success": true,
|
|
"resource": { // Only present on x402 v2 challenges.
|
|
"url": "https://api.example.com/data",
|
|
"description": "…",
|
|
"mimeType": "application/json"
|
|
},
|
|
"accepts": [ // Already filtered: routes on chains TWAK does not recognize are dropped before output.
|
|
{
|
|
"network": "eip155:8453", // CAIP-2 chain ID.
|
|
"scheme": "exact",
|
|
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
"tokenName": "USD Coin", // Seller-controlled (`extra.name`); raw — sanitize before rendering to a terminal.
|
|
"amount": "10000", // Atomic units (string, decimals-of-asset).
|
|
"payTo": "0x271189c860DB25bC43173B0335784aD68a680908",
|
|
"transferMethod": "eip3009", // or "permit2-exact".
|
|
"maxTimeoutSeconds": 30,
|
|
"preferred": true, // True for the route the client would pick if you called `twak x402 request` with no filters.
|
|
"requiresApproval": false, // True for Permit2 routes (one-time `approve(Permit2, MAX)` needed before first payment).
|
|
"description": "10000 of USD Coin on eip155:8453 via eip3009 (gasless)" // Sanitized: control chars stripped.
|
|
}
|
|
],
|
|
"summary": "Endpoint offers 3 payment option(s). Default route: 10000 of USD Coin on eip155:8453 via eip3009 (gasless).",
|
|
"nextAction": "Show these payment options to the user. Default route is 10000 USD Coin on Base. Pick one and run: twak x402 request 'https://api.example.com/data' --max-payment 10000 --prefer-asset <picked asset>. Omit --prefer-asset to use the default."
|
|
}
|
|
```
|
|
|
|
Failure envelope (HTTPS validation failure, endpoint not a 402, malformed challenge, etc.):
|
|
|
|
```jsonc
|
|
{
|
|
"success": false,
|
|
"code": "NETWORK_ERROR", // VALIDATION_ERROR / NO_PAYMENT_REQUIRED / PAYMENT_INVALID_CHALLENGE / NETWORK_ERROR
|
|
"message": "Endpoint returned 500 Internal Server Error; expected 402 challenge.",
|
|
"status": 500, // HTTP status (when applicable)
|
|
"error": "Endpoint returned 500 …", // Same as `message`; legacy envelope key.
|
|
"errorCode": "NETWORK_ERROR" // Same as `code`; legacy envelope key.
|
|
}
|
|
```
|
|
|
|
### Filtering Semantics
|
|
|
|
Routes on chains TWAK does not recognize are dropped before **both** output modes — silently, with no warning. The JSON `accepts` array is already filtered; only `summary`/`nextAction` reference the original offered count, and only when every route was dropped (`Endpoint offered N payment option(s), but none on chains this client supports.`).
|
|
|
|
Process exit code is `1` whenever no signable route remains, in both modes:
|
|
- Every route dropped → text mode prints `No supported route from this endpoint.`
|
|
- Routes remain on recognized chains but none uses a signable scheme (e.g. only `permit2-upto`) → text mode lists them, then prints `No route here can be signed by this client.`. JSON mode emits the raw library result: `success: true`, `preferred: false` on every `accepts` entry, a "no supported route" `nextAction`, and **no** `error`/`errorCode` keys. Detect this case by checking that no `accepts` entry has `preferred: true`.
|
|
|
|
### Sort Order
|
|
|
|
Sorted preferred-first in both modes. `preferred` is `false` for every entry when no remaining route uses a scheme this client can sign (e.g. the endpoint only offers `permit2-upto`); the picker runs on the already chain-filtered set, so an unsupported chain never causes this. In that case `nextAction` falls back to a "no supported route" message.
|
|
|
|
### Quote Options
|
|
|
|
| Flag | Type | Required | Description |
|
|
|------|------|----------|-------------|
|
|
| `--method <method>` | string | no | HTTP method, uppercased before sending (default: `GET`). Not a fixed enum — any verb is accepted. Body is stripped on `GET` and `HEAD`. Must match the method you plan to use on `twak x402 request` — the server may emit a different 402 for a different verb. |
|
|
| `--body <json>` | string | no | Raw request body. Must match the body you plan to use on `twak x402 request`. |
|
|
| `--json` | boolean | no | Emit the JSON shape above. Without `--json`, renders the human-readable table. |
|
|
|
|
`twak x402 quote` does NOT take `--max-payment`, `--password`, `--prefer-*`, `--yes`, or `--auto-approve` — it's read-only.
|
|
|
|
## Picker Behaviour
|
|
|
|
When the server offers multiple `accepts` entries:
|
|
|
|
1. **Filter** by `--prefer-network` / `--prefer-method` / `--prefer-asset` (AND-combined). Empty result → `NO_MATCHING_ROUTE`.
|
|
2. **Skip unsignable entries.** Each kept entry must use scheme `exact` with a method the client can sign (`eip3009`, `permit2`, `permit2-exact`); anything else (e.g. `permit2-upto`) is skipped.
|
|
- EIP-3009 entries additionally **require** `extra.name` and `extra.version` (used to build the EIP-712 domain separator). Entries missing either field are skipped entirely — not signable, even if they're the only EIP-3009 option offered.
|
|
- `permit2` / `permit2-exact` entries (aliases for the same flow) need no extra metadata.
|
|
3. **Prefer EIP-3009** over Permit2 among the surviving entries (no approval, no gas).
|
|
4. **Fall back** to Permit2 (`permit2` / `permit2-exact`) on the first surviving entry. Requires a one-time `approve(Permit2, MAX)` if the existing Permit2 allowance is below the payment amount.
|
|
|
|
Error attribution: `NO_MATCHING_ROUTE` is thrown only when the `--prefer-*` pre-filter (step 1) removes every entry. If entries survive the filter but none is signable (step 2 onward), the error is `PAYMENT_INVALID_CHALLENGE` (`no supported scheme in 402 response …`).
|
|
|
|
EIP-3009 is always cheaper for the buyer (no approval, no gas) so it wins by default whenever offered with valid metadata.
|
|
|
|
## Payment Info
|
|
|
|
```bash
|
|
twak x402 info
|
|
```
|
|
|
|
## Supported Settlement Routes
|
|
|
|
Route selection accepts any chain in TWAK's chain map; signing (EIP-3009 and Permit2) is EVM-only. EIP-3009 additionally requires the token contract to implement `transferWithAuthorization` — support is per-token, not per-chain. Permit2-exact requires Uniswap's Permit2 contract to be deployed on the chain. When the picked route's chain is not in the chain map, `twak x402 request` returns `CHAIN_UNSUPPORTED` (`quote` silently drops such routes instead).
|
|
|
|
Example routes from live merchant endpoints (merchant-configured — verify with `twak x402 quote`, not guaranteed):
|
|
|
|
| Asset | Chain | Method | Notes |
|
|
|-------|-------|--------|-------|
|
|
| USDC | `base` (`eip155:8453`) | EIP-3009 | Recommended — low fees, gasless, fast finality. |
|
|
| USDC | `bsc` (`eip155:56`) | EIP-3009 / Permit2-exact | |
|
|
| USDT | `bsc` (`eip155:56`) | EIP-3009 / Permit2-exact | Atomic units at 18dp on BSC. |
|