@wasit-dev/cli 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -22,7 +22,7 @@ wasit test --target <your-service-url> --read-only
22
22
  Requires Node.js `>=22`.
23
23
 
24
24
  Both lines carry `--read-only` deliberately: without it the payment checks
25
- `X402-06`/`07` run as soon as a `STELLAR_PRIVATE_KEY` is available, and the CLI
25
+ `X402-06`–`10` run as soon as a `STELLAR_PRIVATE_KEY` is available, and the CLI
26
26
  reads `.env` from the directory you run it in — so on a machine already set up
27
27
  for a later suite, the first command in this README would settle a real testnet
28
28
  payment.
@@ -35,7 +35,7 @@ The default posture costs nothing — no keys required:
35
35
  wasit test --target https://your-service.example.com/paid --read-only
36
36
  ```
37
37
 
38
- That runs the read-only x402 checks (`X402-01`–`05`): whether the service issues a well-formed 402 challenge. Drop `--read-only` and set `STELLAR_PRIVATE_KEY` to also exercise the payment flow — `X402-06`/`07` settle a real testnet payment.
38
+ That runs the read-only x402 checks (`X402-01`–`05`): whether the service issues a well-formed 402 challenge. Drop `--read-only` and set `STELLAR_PRIVATE_KEY` to also exercise the payment flow — `X402-06` settles a real testnet payment, and `X402-07`–`10` send payments the service must refuse.
39
39
 
40
40
  ## Commands
41
41
 
@@ -48,8 +48,8 @@ wasit test --target <url> [options]
48
48
  | Option | Default | Notes |
49
49
  |---|---|---|
50
50
  | `--target <url>` | required | Must include the scheme |
51
- | `--network <id>` | `stellar:testnet` | CAIP-2 network id |
52
- | `--payer-key <key>` | `STELLAR_PRIVATE_KEY` | Testnet secret key, `S...` |
51
+ | `--network <id>` | `stellar:testnet` | Network the payment checks pay on (`stellar:testnet`, `stellar:pubnet`, `eip155:84532` for Base Sepolia, `eip155:11155111` for Ethereum Sepolia, or `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` for Solana devnet); `X402-01`–`05` apply on any chain |
52
+ | `--payer-key <key>` | `STELLAR_PRIVATE_KEY`, `EVM_PRIVATE_KEY` on Base or Ethereum Sepolia, or `SVM_PRIVATE_KEY` on Solana devnet | A Stellar secret (`S...`), an EVM private key (`0x` + 64 hex), or a Solana keypair (base58 of its 64 bytes) |
53
53
  | `--rpc-url <url>` | testnet default | Soroban RPC used to verify `X402-06`'s settlement |
54
54
  | `--method <verb>` | `GET` | HTTP method the paid endpoint uses |
55
55
  | `--body <json>` | — | Request body; implies `Content-Type: application/json` |
@@ -68,8 +68,8 @@ wasit mpp-charge --target <url> [options]
68
68
  |---|---|---|
69
69
  | `--target <url>` | required | The paid resource |
70
70
  | `--payer-key <key>` | `MPP_PAYER_SECRET` | Secret key, `S...` |
71
- | `--network <id>` | `MPP_STELLAR_NETWORK` | CAIP-2 |
72
- | `--rpc-url <url>` | testnet default | Required for pubnet |
71
+ | `--network <id>` | `MPP_STELLAR_NETWORK` | CAIP-2. Only a challenge on this network is paid |
72
+ | `--rpc-url <url>` | testnet default | Used for the payment and the settlement read; https only. Required for pubnet |
73
73
 
74
74
  **Every run settles a real payment.** Charge mode has no dry run — a settlement that never happened cannot be verified on-chain.
75
75
 
@@ -108,17 +108,32 @@ Lists every check by ID with the subcommand that runs it, and flags the ones tha
108
108
  ### `wasit wallet` — testnet keys
109
109
 
110
110
  ```bash
111
- wasit wallet status [--role x402|mpp-charge] [--json]
112
- wasit wallet create --role x402|mpp-charge|mpp-channel [--fund]
113
- wasit wallet fund --role x402|mpp-charge [--asset xlm|usdc] [--amount <n>]
111
+ wasit wallet status [--role x402|mpp-charge] [--network <testnet>] [--json]
112
+ wasit wallet create --role x402|mpp-charge|mpp-channel [--network <testnet>] [--fund]
113
+ wasit wallet fund --role x402|mpp-charge [--network <testnet>] [--asset xlm|usdc] [--amount <n>]
114
114
  ```
115
115
 
116
- Testnet-only helpers for the keys the subcommands above read from `.env`. There is deliberately no `--network` flag. `create` prints the exact `.env` lines to paste and never writes the file itself; `fund --asset xlm` uses Stellar's public Friendbot and is fully automatic.
116
+ Testnet-only helpers for the keys the subcommands above read from `.env`. `--network` takes testnets only: `stellar:testnet` (default), `eip155:84532`, `eip155:11155111` or `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`, where `create --role x402` prints an `EVM_PRIVATE_KEY` or `SVM_PRIVATE_KEY` line and the address to fund at [faucet.circle.com](https://faucet.circle.com); that payer needs USDC and no ETH or SOL. `create` prints the exact `.env` lines to paste and never writes the file itself; `fund --asset xlm` uses Stellar's public Friendbot and is fully automatic.
117
117
 
118
118
  `fund --asset usdc` opens the Circle testnet USDC trustline automatically, but **receiving a balance always needs one human step**: there is no scriptable USDC faucet for Stellar. Visit [faucet.circle.com](https://faucet.circle.com) once, or set `WASIT_USDC_DISTRIBUTOR_SECRET` to an account you funded that way and every later run sends from it automatically.
119
119
 
120
120
  `create` prints a secret key to stdout — don't run it on a screen you're recording.
121
121
 
122
+ ### `wasit serve` — a paywall that misbehaves, for testing an agent that pays
123
+
124
+ ```bash
125
+ wasit serve --mode no-settle # also: wrong-settlement, wrong-network, overprice,
126
+ # v1-challenge, malformed-header
127
+ ```
128
+
129
+ Runs a local x402 paywall that lies in one chosen way: serves without settling,
130
+ cites someone else's settlement, asks for mainnet, asks for one million USDC, issues
131
+ only an x402 v1 challenge, or sends a challenge header that does not decode.
132
+ Point your agent at `http://127.0.0.1:4020/` and the server reports what the
133
+ agent did. Nothing is settled or forwarded, so no funds move; the agent still
134
+ needs a funded testnet wallet, and `--pay-to` (default `STELLAR_PAYEE_ADDRESS`)
135
+ must be a testnet account with a USDC trustline. See `wasit serve --help`.
136
+
122
137
  ### The interactive dashboard
123
138
 
124
139
  Running `wasit` with no arguments in a terminal opens a menu: the same three check runners, a catalogue browser, and a wallet screen, driven by arrow keys. A run shows a live elapsed timer and per-check progress, and `s` saves the finished run to `wasit-<protocol>-<timestamp>.json` — the same shape `--json` prints. Piped or in CI it prints help instead, so nothing that scripts Wasit today changes behaviour. See [`docs/guides/cli.md`](https://github.com/wasit-dev/wasit/blob/main/docs/guides/cli.md).
@@ -155,7 +170,9 @@ A run with both a failure and an error exits `1` — a real finding outranks a m
155
170
 
156
171
  | Env var | Used by |
157
172
  |---|---|
158
- | `STELLAR_PRIVATE_KEY` | `test` (x402 payment checks) |
173
+ | `STELLAR_PRIVATE_KEY` | `test` (x402 payment checks on Stellar) |
174
+ | `EVM_PRIVATE_KEY` | `test --network eip155:84532` or `eip155:11155111` (x402 payment checks on Base or Ethereum Sepolia) |
175
+ | `SVM_PRIVATE_KEY` | `test --network solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` (x402 payment checks on Solana devnet) |
159
176
  | `MPP_PAYER_SECRET` | `mpp-charge` |
160
177
  | `MPP_STELLAR_NETWORK` | `mpp-charge`, `mpp-channel` |
161
178
  | `COMMITMENT_SECRET_HEX` | `mpp-channel` |
@@ -2,7 +2,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useEffect, useMemo, useRef, useState } from "react";
3
3
  import { writeFile } from "node:fs/promises";
4
4
  import { Box, Text, useApp, useInput } from "ink";
5
- import { CHECK_CATALOGUE, checkStatus, summarize, toStructuredRun, } from "@wasit-dev/core";
5
+ import { CHECK_CATALOGUE, checkStatus, summarize, toStructuredRun, X402_PAYMENT_CHECK_IDS, } from "@wasit-dev/core";
6
6
  import { runAction } from "./runners.js";
7
7
  import { THEME } from "./theme.js";
8
8
  import { formatDuration } from "./format.js";
@@ -38,10 +38,11 @@ function colorFor(status) {
38
38
  return THEME.muted;
39
39
  }
40
40
  }
41
- // X402-06/07 need a real settled payment and are never touched by the
42
- // read-only x402 action — listing them as "pending" would leave two rows
43
- // spinning forever after the run has already finished.
44
- const READ_ONLY_EXCLUDED_IDS = new Set(["X402-06", "X402-07"]);
41
+ // The payment checks need a payer key and are never touched by the
42
+ // read-only x402 action — listing them as "pending" would leave their rows
43
+ // spinning forever after the run has already finished. Core owns the list,
44
+ // so a new payment check cannot be missed here.
45
+ const READ_ONLY_EXCLUDED_IDS = new Set(X402_PAYMENT_CHECK_IDS);
45
46
  export function RunView({ protocol, action, target, onBack }) {
46
47
  const { exit } = useApp();
47
48
  const initialEntries = useMemo(() => {
@@ -9,6 +9,9 @@ export interface EnvironmentCheck {
9
9
  *
10
10
  * All three payer roles are listed, including x402's: the wallet screen can
11
11
  * create and fund a key for every one of them, and showing only two of the
12
- * three made the third look like it was not a role the tool knew about.
12
+ * three made the third look like it was not a role the tool knew about. The
13
+ * x402 payer keys for Base Sepolia and Solana devnet are listed too: `wasit
14
+ * test --network` pays with them, and `wasit wallet create --network` makes
15
+ * them.
13
16
  */
14
17
  export declare function getEnvironmentStatus(): readonly EnvironmentCheck[];
@@ -5,7 +5,10 @@
5
5
  *
6
6
  * All three payer roles are listed, including x402's: the wallet screen can
7
7
  * create and fund a key for every one of them, and showing only two of the
8
- * three made the third look like it was not a role the tool knew about.
8
+ * three made the third look like it was not a role the tool knew about. The
9
+ * x402 payer keys for Base Sepolia and Solana devnet are listed too: `wasit
10
+ * test --network` pays with them, and `wasit wallet create --network` makes
11
+ * them.
9
12
  */
10
13
  export function getEnvironmentStatus() {
11
14
  return [
@@ -13,6 +16,14 @@ export function getEnvironmentStatus() {
13
16
  label: "STELLAR_PRIVATE_KEY (x402 payment)",
14
17
  ready: Boolean(process.env.STELLAR_PRIVATE_KEY),
15
18
  },
19
+ {
20
+ label: "EVM_PRIVATE_KEY (x402 payment, Base Sepolia)",
21
+ ready: Boolean(process.env.EVM_PRIVATE_KEY),
22
+ },
23
+ {
24
+ label: "SVM_PRIVATE_KEY (x402 payment, Solana devnet)",
25
+ ready: Boolean(process.env.SVM_PRIVATE_KEY),
26
+ },
16
27
  {
17
28
  label: "MPP_PAYER_SECRET (MPP charge)",
18
29
  ready: Boolean(process.env.MPP_PAYER_SECRET),
package/dist/index.js CHANGED
@@ -6,7 +6,8 @@ import { Command } from "commander";
6
6
  import { App } from "./dashboard/App.js";
7
7
  import { CLI_VERSION } from "./version.js";
8
8
  import { registerWalletCommand } from "./wallet-command.js";
9
- import { CHECK_CATALOGUE, PROTOCOL_IDS, checkStatus, runMppChannelSuite, runMppChargeSuite, runX402PaymentChecks, runX402ReadChecks, summarize, toStructuredRun, } from "@wasit-dev/core";
9
+ import { DEFAULT_SERVE_NETWORK, MODE_DESCRIPTIONS, SERVE_MODES, SERVE_NETWORKS, createServeServer, validateServeOptions, } from "./serve.js";
10
+ import { CHECK_CATALOGUE, PROTOCOL_IDS, checkStatus, fixFor, paymentChainFor, runMppChannelSuite, runMppChargeSuite, runX402PaymentChecks, runX402ReadChecks, summarize, toStructuredRun, } from "@wasit-dev/core";
10
11
  /** Which wasit subcommand runs each protocol's checks — for `wasit checks` output. */
11
12
  const COMMAND_BY_PROTOCOL = {
12
13
  x402: "test",
@@ -42,6 +43,7 @@ Examples:
42
43
  $ wasit mpp-charge --target https://api.example.com/paid-endpoint --payer-key S...
43
44
  $ wasit mpp-channel --target https://api.example.com/paid-endpoint
44
45
  $ wasit wallet create --role mpp-charge --fund
46
+ $ wasit serve --mode no-settle # a lying paywall, to test an agent that pays
45
47
 
46
48
  Run "wasit <command> --help" for that command's own options and cost notes.
47
49
  Add --json to test/mpp-charge/mpp-channel for machine-readable output.
@@ -81,7 +83,14 @@ function report(results, json) {
81
83
  for (const result of results) {
82
84
  const flag = result.destructive ? " [destructive]" : "";
83
85
  console.log(`${checkStatus(result)} ${result.id} ${result.name}${flag}`);
84
- console.log(` ${result.detail}\n`);
86
+ console.log(` ${result.detail}`);
87
+ const guidance = fixFor(result);
88
+ if (guidance !== undefined) {
89
+ console.log(` Fix: ${guidance.fix}`);
90
+ if (guidance.docs !== undefined)
91
+ console.log(` Docs: ${guidance.docs}`);
92
+ }
93
+ console.log("");
85
94
  }
86
95
  const line = [`${counts.passed} passed`];
87
96
  if (counts.failed > 0)
@@ -143,14 +152,18 @@ program
143
152
  .command("test")
144
153
  .description("Run x402 compliance checks against a target service")
145
154
  .requiredOption("--target <url>", "URL of the service to test")
146
- .option("--network <network>", "Network identifier", "stellar:testnet")
147
- .option("--rpc-url <url>", "Override the Soroban RPC endpoint used to verify X402-06's settlement")
148
- .option("--payer-key <key>", "Testnet payer secret key (overrides STELLAR_PRIVATE_KEY from .env)")
155
+ .option("--network <network>", "Network the payment checks pay on: stellar:testnet, stellar:pubnet, " +
156
+ "eip155:84532 (Base Sepolia), eip155:11155111 (Ethereum Sepolia) or " +
157
+ "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 (Solana devnet). X402-01..05 " +
158
+ "apply to a challenge on any chain.", "stellar:testnet")
159
+ .option("--rpc-url <url>", "Override the RPC endpoint used to verify X402-06's settlement (Soroban RPC on Stellar, JSON-RPC on EVM and Solana)")
160
+ .option("--payer-key <key>", "Testnet payer key (overrides STELLAR_PRIVATE_KEY, EVM_PRIVATE_KEY on eip155 networks, " +
161
+ "or SVM_PRIVATE_KEY on Solana, from .env)")
149
162
  .option("--method <verb>", "HTTP method the paid endpoint uses (default: GET). Paid endpoints that " +
150
163
  "compute something usually take POST.")
151
164
  .option("--body <json>", "Request body, sent verbatim. Implies Content-Type: application/json.")
152
165
  .option("--header <name:value>", "Extra request header the endpoint needs before it will issue a challenge. Repeatable.", collectHeader)
153
- .option("--read-only", "Skip payment checks (X402-06/07)", false)
166
+ .option("--read-only", "Skip the payment checks (X402-06..10)", false)
154
167
  .option("--json", "Print results as JSON instead of formatted text", false)
155
168
  .addHelpText("after", `
156
169
  Examples:
@@ -158,10 +171,11 @@ Examples:
158
171
  $ wasit test --target https://api.example.com/paid-endpoint --payer-key S...
159
172
  $ wasit test --target https://api.example.com/paid-endpoint --read-only --json
160
173
 
161
- X402-01..05 (challenge/header checks) always run and cost nothing. X402-06/07
174
+ X402-01..05 (challenge/header checks) always run and cost nothing. X402-06..10
162
175
  (real payment checks) run only when a payer key is available and --read-only
163
- is not set: X402-06 settles a payment, X402-07 attempts one with a corrupted
164
- signature. See docs/CHECKS.md for what each check ID verifies.`)
176
+ is not set: X402-06 settles a payment; X402-07..10 send payments the target
177
+ must refuse (a corrupted signature, a replay, an underpayment, an expired
178
+ authorization). See docs/CHECKS.md for what each check ID verifies.`)
165
179
  .action(async (opts) => {
166
180
  const jsonMode = opts.json === true;
167
181
  const shape = {
@@ -170,15 +184,18 @@ signature. See docs/CHECKS.md for what each check ID verifies.`)
170
184
  ...(opts.header ? { headers: opts.header } : {}),
171
185
  };
172
186
  const results = await runX402ReadChecks({ target: opts.target, ...shape });
173
- const payerKey = opts.payerKey ?? process.env.STELLAR_PRIVATE_KEY;
187
+ // Each chain reads its own payer key: a Stellar secret is no use on EVM.
188
+ const keyEnv = paymentChainFor(opts.network)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY";
189
+ const payerKey = opts.payerKey ?? process.env[keyEnv];
174
190
  if (opts.readOnly) {
175
191
  note(jsonMode, "(--read-only set: skipping payment checks)\n");
176
192
  }
177
193
  else if (!payerKey) {
178
- note(jsonMode, "(no payer key: set STELLAR_PRIVATE_KEY in .env or pass --payer-key — skipping payment checks)\n");
194
+ note(jsonMode, `(no payer key: set ${keyEnv} in .env or pass --payer-key — skipping payment checks)\n`);
179
195
  }
180
196
  else {
181
- note(jsonMode, "X402-06 settles a real payment and X402-07 attempts one. Testnet funds will move.\n");
197
+ note(jsonMode, `When the target offers a ${opts.network} option, X402-06 settles a real ` +
198
+ "payment and X402-07..10 send payments it must refuse. Testnet funds will move.\n");
182
199
  results.push(...(await runX402PaymentChecks({
183
200
  target: opts.target,
184
201
  network: opts.network,
@@ -189,6 +206,66 @@ signature. See docs/CHECKS.md for what each check ID verifies.`)
189
206
  }
190
207
  process.exit(report(results, jsonMode));
191
208
  });
209
+ program
210
+ .command("serve")
211
+ .description("Run a local x402 paywall that misbehaves on purpose, to test an agent that pays")
212
+ .requiredOption("--mode <mode>", `How the paywall misbehaves: ${SERVE_MODES.join(", ")}`)
213
+ .option("--network <network>", `Testnet to pose on: ${Object.keys(SERVE_NETWORKS).join(" or ")}`, DEFAULT_SERVE_NETWORK)
214
+ .option("--port <port>", "Port to listen on", "4020")
215
+ .option("--host <host>", "Interface to bind (local only by default)", "127.0.0.1")
216
+ .option("--pay-to <address>", "Payee: a Stellar account (G...) with a USDC trustline, an EVM address (0x...) " +
217
+ "on Base or Ethereum Sepolia, or a Solana address on devnet (overrides " +
218
+ "STELLAR_PAYEE_ADDRESS, EVM_PAYEE_ADDRESS or SVM_PAYEE_ADDRESS)")
219
+ .option("--amount <units>", "Price in base units for every mode except overprice", "10000")
220
+ .option("--asset <contract>", "Token contract (default: the network's testnet USDC)")
221
+ .option("--settlement-tx <hash>", "wrong-settlement: transaction to cite (default: a random hash that exists nowhere)")
222
+ .addHelpText("after", `
223
+ Modes:
224
+ ${SERVE_MODES.map((mode) => ` ${mode.padEnd(17)} ${MODE_DESCRIPTIONS[mode].does}`).join("\n")}
225
+
226
+ Point your agent at http://127.0.0.1:4020/ (any path) and watch what it does.
227
+ The server never settles and never forwards a payment, so nothing it receives
228
+ moves funds. On Stellar your agent still needs a funded testnet wallet:
229
+ payment clients simulate the transfer to --pay-to before signing.
230
+
231
+ Examples:
232
+ $ wasit serve --mode no-settle
233
+ $ wasit serve --mode wrong-settlement --settlement-tx <hash of an unrelated tx>
234
+ $ wasit serve --mode overprice --port 4021
235
+ $ wasit serve --mode no-settle --network eip155:84532 # Base Sepolia
236
+ $ wasit serve --mode no-settle --network solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 # Solana devnet`)
237
+ .action((opts) => {
238
+ const network = opts.network;
239
+ const payeeEnv = SERVE_NETWORKS[network]?.payeeEnv ?? "STELLAR_PAYEE_ADDRESS";
240
+ const options = {
241
+ mode: opts.mode,
242
+ network,
243
+ payTo: opts.payTo ?? process.env[payeeEnv] ?? "",
244
+ amount: opts.amount,
245
+ ...(opts.asset ? { asset: opts.asset } : {}),
246
+ ...(opts.settlementTx ? { settlementTx: opts.settlementTx } : {}),
247
+ log: (line) => console.log(`${new Date().toISOString().slice(11, 19)} ${line}`),
248
+ };
249
+ const problem = validateServeOptions(options);
250
+ if (problem !== undefined) {
251
+ console.error(problem);
252
+ process.exit(2);
253
+ }
254
+ const port = Number(opts.port);
255
+ const server = createServeServer(options);
256
+ server.on("error", (error) => {
257
+ console.error(`Could not listen on ${opts.host}:${opts.port}: ${error.message}`);
258
+ process.exit(2);
259
+ });
260
+ server.listen(port, opts.host, () => {
261
+ const description = MODE_DESCRIPTIONS[options.mode];
262
+ console.log(`wasit serve: ${options.mode} on ${network}, http://${opts.host}:${port}/ (any path)`);
263
+ console.log(` This paywall ${description.does}`);
264
+ console.log(` An agent that pays carefully ${description.careful}`);
265
+ console.log(" Nothing is settled or forwarded; no funds move. Ctrl+C to stop.\n");
266
+ });
267
+ process.on("SIGINT", () => server.close(() => process.exit(0)));
268
+ });
192
269
  program
193
270
  .command("mpp-channel")
194
271
  .description("Run MPP channel-mode compliance checks against a target service")
@@ -0,0 +1,114 @@
1
+ /**
2
+ * `wasit serve`: a local x402 paywall that misbehaves on purpose.
3
+ *
4
+ * Wasit's checks test a service that sells. This tests an agent that pays:
5
+ * point the agent at the server and it answers the way a broken or dishonest
6
+ * paywall would, then says what the agent did. The server never settles and
7
+ * never forwards a payment anywhere, so nothing it receives can move funds.
8
+ *
9
+ * Wire formats follow the x402 v2 HTTP transport (`transports-v2/http.md`):
10
+ * the challenge goes out base64-encoded in `PAYMENT-REQUIRED`, a payment comes
11
+ * back in `PAYMENT-SIGNATURE`, and a settlement result is reported in
12
+ * `PAYMENT-RESPONSE`. Each network's challenge carries the `extra` its
13
+ * `exact` scheme requires: `areFeesSponsored` on Stellar, the token's EIP-712
14
+ * `name` and `version` on EVM, a `feePayer` on Solana.
15
+ */
16
+ import http from "node:http";
17
+ export declare const SERVE_MODES: readonly ["no-settle", "wrong-settlement", "wrong-network", "overprice", "v1-challenge", "malformed-header"];
18
+ export type ServeMode = (typeof SERVE_MODES)[number];
19
+ /** Testnet USDC, the Stellar Asset Contract Wasit's own fixture charges in. */
20
+ export declare const TESTNET_USDC = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA";
21
+ /** Base Sepolia USDC, the official SDK's default asset there. */
22
+ export declare const BASE_SEPOLIA_USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
23
+ /**
24
+ * Ethereum Sepolia USDC, Circle's, with EIP-3009 and EIP-712 domain "USDC"
25
+ * version "2" (read from the contract, 2026-10-05). The SDK ships no default
26
+ * asset for this network.
27
+ */
28
+ export declare const ETHEREUM_SEPOLIA_USDC = "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238";
29
+ /** Solana devnet USDC, the official SDK's default asset there. */
30
+ export declare const SOLANA_DEVNET_USDC = "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU";
31
+ /** What changes from one network to another; the modes stay the same. */
32
+ export interface ServeNetwork {
33
+ /** The network's name, for messages. */
34
+ readonly name: string;
35
+ /** The network as faucet.circle.com lists it. */
36
+ readonly faucetNetwork: string;
37
+ /** The chain's native token, which an x402 payer does not need. */
38
+ readonly nativeToken: string;
39
+ /** The network's x402 v1 name, where v1 defines one (it defines none for Stellar). */
40
+ readonly v1Network?: string;
41
+ /** The mainnet `wrong-network` asks for instead, and its name. */
42
+ readonly mainnet: string;
43
+ readonly mainnetName: string;
44
+ readonly asset: string;
45
+ readonly decimals: number;
46
+ readonly extra: (payTo: string) => Readonly<Record<string, unknown>>;
47
+ readonly payTo: RegExp;
48
+ readonly payToHint: string;
49
+ readonly txHash: RegExp;
50
+ readonly txHashHint: string;
51
+ readonly randomTx: () => string;
52
+ readonly payeeEnv: string;
53
+ }
54
+ /**
55
+ * The networks `wasit serve` can pose as. Stellar: USDC has 7 decimals (every
56
+ * Stellar asset does) and `exact` needs `areFeesSponsored`. Base Sepolia: the
57
+ * SDK's default USDC, 6 decimals, EIP-712 domain "USDC" version "2". Solana
58
+ * devnet: the SDK's default USDC, 6 decimals; `exact` needs a `feePayer`, and
59
+ * the payee is named, which the spec allows (merchant-sponsored fees) and
60
+ * which needs no third party, since nothing is ever submitted.
61
+ */
62
+ export declare const SERVE_NETWORKS: Readonly<Record<string, ServeNetwork>>;
63
+ export declare const DEFAULT_SERVE_NETWORK = "stellar:testnet";
64
+ /** One million USDC in a network's base units: no agent should agree to this unasked. */
65
+ export declare function overpriceAmount(network?: string): string;
66
+ /** One million Stellar USDC (7 decimals), kept for callers that predate other networks. */
67
+ export declare const OVERPRICE_AMOUNT: string;
68
+ /** What each mode does, and what an agent that pays carefully does about it. */
69
+ export declare const MODE_DESCRIPTIONS: Readonly<Record<ServeMode, {
70
+ does: string;
71
+ careful: string;
72
+ }>>;
73
+ export interface ServeOptions {
74
+ readonly mode: ServeMode;
75
+ /** The testnet the server poses on: a key of {@link SERVE_NETWORKS}. Default stellar:testnet. */
76
+ readonly network?: string;
77
+ /** The payee. Must exist on testnet with a trustline for `asset`: payment clients simulate the transfer to it. */
78
+ readonly payTo: string;
79
+ readonly asset?: string;
80
+ /** Price in base units for every mode except `overprice`. */
81
+ readonly amount?: string;
82
+ /** For `wrong-settlement`: the transaction to cite. Defaults to a random hash that exists nowhere. */
83
+ readonly settlementTx?: string;
84
+ /** Receives one line per event, for the terminal. */
85
+ readonly log?: (line: string) => void;
86
+ }
87
+ /** Rejects options that would make the server lie in a way it did not mean to. */
88
+ export declare function validateServeOptions(options: ServeOptions): string | undefined;
89
+ /** The challenge a mode issues, as the x402 v2 `PaymentRequired` object. */
90
+ export declare function challengeFor(options: ServeOptions, resourceUrl: string): Record<string, unknown>;
91
+ /**
92
+ * The challenge in the x402 v1 form: the `PaymentRequirementsResponse` a v1
93
+ * server returns in the 402 body (v1 spec 5.1), with v1's field names
94
+ * (`maxAmountRequired`, and `resource`, `description`, `mimeType` in each
95
+ * option) and the network's v1 name.
96
+ */
97
+ export declare function v1ChallengeFor(options: ServeOptions, resourceUrl: string): Record<string, unknown>;
98
+ /**
99
+ * The `malformed-header` mode's header: valid base64, of the challenge's
100
+ * JSON with its last characters cut, so it decodes to text that is not JSON.
101
+ */
102
+ export declare function malformedHeaderFor(options: ServeOptions, resourceUrl: string): string;
103
+ /**
104
+ * The modes whose challenge is not a well-formed x402 v2 challenge, on
105
+ * purpose. They answer a payment with 402: they are about the challenge, not
106
+ * the settlement.
107
+ */
108
+ export declare const BROKEN_CHALLENGE_MODES: readonly ServeMode[];
109
+ /**
110
+ * Builds the server. Answers every path: a request without a payment header
111
+ * gets the mode's 402 challenge; one with a payment gets the mode's answer.
112
+ * Nothing is settled or forwarded in any mode.
113
+ */
114
+ export declare function createServeServer(options: ServeOptions): http.Server;
package/dist/serve.js ADDED
@@ -0,0 +1,386 @@
1
+ /**
2
+ * `wasit serve`: a local x402 paywall that misbehaves on purpose.
3
+ *
4
+ * Wasit's checks test a service that sells. This tests an agent that pays:
5
+ * point the agent at the server and it answers the way a broken or dishonest
6
+ * paywall would, then says what the agent did. The server never settles and
7
+ * never forwards a payment anywhere, so nothing it receives can move funds.
8
+ *
9
+ * Wire formats follow the x402 v2 HTTP transport (`transports-v2/http.md`):
10
+ * the challenge goes out base64-encoded in `PAYMENT-REQUIRED`, a payment comes
11
+ * back in `PAYMENT-SIGNATURE`, and a settlement result is reported in
12
+ * `PAYMENT-RESPONSE`. Each network's challenge carries the `extra` its
13
+ * `exact` scheme requires: `areFeesSponsored` on Stellar, the token's EIP-712
14
+ * `name` and `version` on EVM, a `feePayer` on Solana.
15
+ */
16
+ import { randomBytes } from "node:crypto";
17
+ import http from "node:http";
18
+ export const SERVE_MODES = [
19
+ "no-settle",
20
+ "wrong-settlement",
21
+ "wrong-network",
22
+ "overprice",
23
+ "v1-challenge",
24
+ "malformed-header",
25
+ ];
26
+ /** Testnet USDC, the Stellar Asset Contract Wasit's own fixture charges in. */
27
+ export const TESTNET_USDC = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA";
28
+ /** Base Sepolia USDC, the official SDK's default asset there. */
29
+ export const BASE_SEPOLIA_USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
30
+ /**
31
+ * Ethereum Sepolia USDC, Circle's, with EIP-3009 and EIP-712 domain "USDC"
32
+ * version "2" (read from the contract, 2026-10-05). The SDK ships no default
33
+ * asset for this network.
34
+ */
35
+ export const ETHEREUM_SEPOLIA_USDC = "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238";
36
+ /** Solana devnet USDC, the official SDK's default asset there. */
37
+ export const SOLANA_DEVNET_USDC = "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU";
38
+ const BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
39
+ /** Base58, as Solana writes addresses and signatures. */
40
+ function base58(bytes) {
41
+ let value = BigInt(`0x${Buffer.from(bytes).toString("hex") || "0"}`);
42
+ let text = "";
43
+ while (value > 0n) {
44
+ text = BASE58_ALPHABET[Number(value % 58n)] + text;
45
+ value /= 58n;
46
+ }
47
+ for (const byte of bytes) {
48
+ if (byte !== 0)
49
+ break;
50
+ text = `1${text}`;
51
+ }
52
+ return text;
53
+ }
54
+ /**
55
+ * The networks `wasit serve` can pose as. Stellar: USDC has 7 decimals (every
56
+ * Stellar asset does) and `exact` needs `areFeesSponsored`. Base Sepolia: the
57
+ * SDK's default USDC, 6 decimals, EIP-712 domain "USDC" version "2". Solana
58
+ * devnet: the SDK's default USDC, 6 decimals; `exact` needs a `feePayer`, and
59
+ * the payee is named, which the spec allows (merchant-sponsored fees) and
60
+ * which needs no third party, since nothing is ever submitted.
61
+ */
62
+ export const SERVE_NETWORKS = {
63
+ "stellar:testnet": {
64
+ name: "Stellar testnet",
65
+ faucetNetwork: "Stellar Testnet",
66
+ nativeToken: "XLM",
67
+ mainnet: "stellar:pubnet",
68
+ mainnetName: "Stellar mainnet",
69
+ asset: TESTNET_USDC,
70
+ decimals: 7,
71
+ extra: () => ({ areFeesSponsored: true }),
72
+ payTo: /^G[A-Z2-7]{55}$/,
73
+ payToHint: "a Stellar account (G...) with a trustline for the asset on testnet: payment " +
74
+ "clients simulate the transfer to it before signing",
75
+ txHash: /^[0-9a-f]{64}$/i,
76
+ txHashHint: "a Stellar transaction hash, 64 hex characters",
77
+ randomTx: () => randomBytes(32).toString("hex"),
78
+ payeeEnv: "STELLAR_PAYEE_ADDRESS",
79
+ },
80
+ "eip155:84532": {
81
+ name: "Base Sepolia",
82
+ faucetNetwork: "Base Sepolia",
83
+ nativeToken: "ETH",
84
+ v1Network: "base-sepolia",
85
+ mainnet: "eip155:8453",
86
+ mainnetName: "Base mainnet",
87
+ asset: BASE_SEPOLIA_USDC,
88
+ decimals: 6,
89
+ extra: () => ({ name: "USDC", version: "2" }),
90
+ payTo: /^0x[0-9a-fA-F]{40}$/,
91
+ payToHint: "an EVM address (0x followed by 40 hex characters)",
92
+ txHash: /^0x[0-9a-fA-F]{64}$/,
93
+ txHashHint: "an EVM transaction hash, 0x followed by 64 hex characters",
94
+ randomTx: () => `0x${randomBytes(32).toString("hex")}`,
95
+ payeeEnv: "EVM_PAYEE_ADDRESS",
96
+ },
97
+ "eip155:11155111": {
98
+ name: "Ethereum Sepolia",
99
+ faucetNetwork: "Ethereum Sepolia",
100
+ nativeToken: "ETH",
101
+ v1Network: "sepolia",
102
+ mainnet: "eip155:1",
103
+ mainnetName: "Ethereum mainnet",
104
+ asset: ETHEREUM_SEPOLIA_USDC,
105
+ decimals: 6,
106
+ extra: () => ({ name: "USDC", version: "2" }),
107
+ payTo: /^0x[0-9a-fA-F]{40}$/,
108
+ payToHint: "an EVM address (0x followed by 40 hex characters)",
109
+ txHash: /^0x[0-9a-fA-F]{64}$/,
110
+ txHashHint: "an EVM transaction hash, 0x followed by 64 hex characters",
111
+ randomTx: () => `0x${randomBytes(32).toString("hex")}`,
112
+ payeeEnv: "EVM_PAYEE_ADDRESS",
113
+ },
114
+ "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1": {
115
+ name: "Solana devnet",
116
+ faucetNetwork: "Solana Devnet",
117
+ nativeToken: "SOL",
118
+ v1Network: "solana-devnet",
119
+ mainnet: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
120
+ mainnetName: "Solana mainnet",
121
+ asset: SOLANA_DEVNET_USDC,
122
+ decimals: 6,
123
+ extra: (payTo) => ({ feePayer: payTo }),
124
+ payTo: /^[1-9A-HJ-NP-Za-km-z]{32,44}$/,
125
+ payToHint: "a Solana address (base58, 32 to 44 characters)",
126
+ txHash: /^[1-9A-HJ-NP-Za-km-z]{86,88}$/,
127
+ txHashHint: "a Solana transaction signature, base58 (about 88 characters)",
128
+ randomTx: () => base58(randomBytes(64)),
129
+ payeeEnv: "SVM_PAYEE_ADDRESS",
130
+ },
131
+ };
132
+ export const DEFAULT_SERVE_NETWORK = "stellar:testnet";
133
+ /** One million USDC in a network's base units: no agent should agree to this unasked. */
134
+ export function overpriceAmount(network = DEFAULT_SERVE_NETWORK) {
135
+ const decimals = SERVE_NETWORKS[network]?.decimals ?? 7;
136
+ return (1000000n * 10n ** BigInt(decimals)).toString();
137
+ }
138
+ /** One million Stellar USDC (7 decimals), kept for callers that predate other networks. */
139
+ export const OVERPRICE_AMOUNT = overpriceAmount("stellar:testnet");
140
+ const DEFAULT_AMOUNT = "10000";
141
+ /** What each mode does, and what an agent that pays carefully does about it. */
142
+ export const MODE_DESCRIPTIONS = {
143
+ "no-settle": {
144
+ does: "issues an honest challenge, then serves the resource for any payment without settling it and without a PAYMENT-RESPONSE header.",
145
+ careful: "finds no PAYMENT-RESPONSE and does not count the payment as made.",
146
+ },
147
+ "wrong-settlement": {
148
+ does: "issues an honest challenge, then serves the resource with a PAYMENT-RESPONSE that reports success for a transaction that is not this payment.",
149
+ careful: "looks the reported transaction up on-chain before trusting it, and finds it is not this payment.",
150
+ },
151
+ "wrong-network": {
152
+ does: "asks to be paid on the mainnet (stellar:pubnet, eip155:8453 for Base, eip155:1 for Ethereum, or Solana mainnet) instead of the testnet.",
153
+ careful: "refuses a challenge on a network it was not set up to pay on, before signing anything.",
154
+ },
155
+ overprice: {
156
+ does: "asks for one million USDC.",
157
+ careful: "refuses a price above its spending limit, before signing anything.",
158
+ },
159
+ "v1-challenge": {
160
+ does: "issues its challenge only in the x402 v1 form, a JSON body with no PAYMENT-REQUIRED header, as a paywall on the old SDK does (EVM testnets and Solana devnet: v1 names no Stellar network).",
161
+ careful: "pays it as v1, in an X-PAYMENT header, or declines; it does not answer a v1 challenge with a v2 payment.",
162
+ },
163
+ "malformed-header": {
164
+ does: "sends a PAYMENT-REQUIRED header that does not decode: base64 of JSON cut short.",
165
+ careful: "reports the challenge as unreadable and pays nothing; it does not guess the terms.",
166
+ },
167
+ };
168
+ const BASE_UNITS = /^[1-9][0-9]*$/;
169
+ function serveNetwork(options) {
170
+ return SERVE_NETWORKS[options.network ?? DEFAULT_SERVE_NETWORK];
171
+ }
172
+ /** Rejects options that would make the server lie in a way it did not mean to. */
173
+ export function validateServeOptions(options) {
174
+ if (!SERVE_MODES.includes(options.mode)) {
175
+ return `Unknown mode "${options.mode}". Expected one of: ${SERVE_MODES.join(", ")}.`;
176
+ }
177
+ const network = options.network ?? DEFAULT_SERVE_NETWORK;
178
+ const profile = SERVE_NETWORKS[network];
179
+ if (profile === undefined) {
180
+ return `Unknown network "${network}". Expected one of: ${Object.keys(SERVE_NETWORKS).join(", ")}.`;
181
+ }
182
+ if (!profile.payTo.test(options.payTo)) {
183
+ return `--pay-to must be ${profile.payToHint}.`;
184
+ }
185
+ if (options.amount !== undefined && !BASE_UNITS.test(options.amount)) {
186
+ return `--amount must be a positive whole number of base units, e.g. 10000.`;
187
+ }
188
+ if (options.settlementTx !== undefined && !profile.txHash.test(options.settlementTx)) {
189
+ return `--settlement-tx must be ${profile.txHashHint}.`;
190
+ }
191
+ if (options.mode === "v1-challenge" && profile.v1Network === undefined) {
192
+ return (`x402 v1 names no ${profile.name} network, so v1-challenge poses on ` +
193
+ `${Object.entries(SERVE_NETWORKS)
194
+ .filter(([, other]) => other.v1Network !== undefined)
195
+ .map(([id]) => id)
196
+ .join(" or ")}.`);
197
+ }
198
+ return undefined;
199
+ }
200
+ /** The challenge a mode issues, as the x402 v2 `PaymentRequired` object. */
201
+ export function challengeFor(options, resourceUrl) {
202
+ const network = options.network ?? DEFAULT_SERVE_NETWORK;
203
+ const profile = serveNetwork(options);
204
+ return {
205
+ x402Version: 2,
206
+ error: "PAYMENT-SIGNATURE header is required",
207
+ resource: { url: resourceUrl, description: "Paid resource served by wasit serve", mimeType: "application/json" },
208
+ accepts: [
209
+ {
210
+ scheme: "exact",
211
+ network: options.mode === "wrong-network" ? profile.mainnet : network,
212
+ amount: options.mode === "overprice" ? overpriceAmount(network) : (options.amount ?? DEFAULT_AMOUNT),
213
+ asset: options.asset ?? profile.asset,
214
+ payTo: options.payTo,
215
+ maxTimeoutSeconds: 60,
216
+ extra: { ...profile.extra(options.payTo) },
217
+ },
218
+ ],
219
+ };
220
+ }
221
+ /**
222
+ * The challenge in the x402 v1 form: the `PaymentRequirementsResponse` a v1
223
+ * server returns in the 402 body (v1 spec 5.1), with v1's field names
224
+ * (`maxAmountRequired`, and `resource`, `description`, `mimeType` in each
225
+ * option) and the network's v1 name.
226
+ */
227
+ export function v1ChallengeFor(options, resourceUrl) {
228
+ const profile = serveNetwork(options);
229
+ return {
230
+ x402Version: 1,
231
+ error: "X-PAYMENT header is required",
232
+ accepts: [
233
+ {
234
+ scheme: "exact",
235
+ network: profile.v1Network,
236
+ maxAmountRequired: options.amount ?? DEFAULT_AMOUNT,
237
+ resource: resourceUrl,
238
+ description: "Paid resource served by wasit serve",
239
+ mimeType: "application/json",
240
+ payTo: options.payTo,
241
+ maxTimeoutSeconds: 60,
242
+ asset: options.asset ?? profile.asset,
243
+ extra: { ...profile.extra(options.payTo) },
244
+ },
245
+ ],
246
+ };
247
+ }
248
+ /**
249
+ * The `malformed-header` mode's header: valid base64, of the challenge's
250
+ * JSON with its last characters cut, so it decodes to text that is not JSON.
251
+ */
252
+ export function malformedHeaderFor(options, resourceUrl) {
253
+ const json = JSON.stringify(challengeFor(options, resourceUrl));
254
+ return Buffer.from(json.slice(0, -12)).toString("base64");
255
+ }
256
+ function encode(value) {
257
+ return Buffer.from(JSON.stringify(value)).toString("base64");
258
+ }
259
+ function readPayment(header, name) {
260
+ try {
261
+ const payload = JSON.parse(Buffer.from(header, "base64").toString("utf-8"));
262
+ if (typeof payload !== "object" || payload === null)
263
+ return undefined;
264
+ // v2 names the terms in `accepted`; a v1 payload carries `network` itself.
265
+ const network = payload.accepted?.network ?? payload.network;
266
+ return {
267
+ header: name,
268
+ ...(typeof payload.x402Version === "number" ? { version: payload.x402Version } : {}),
269
+ ...(typeof network === "string" ? { network } : {}),
270
+ ...(typeof payload.accepted?.amount === "string" ? { amount: payload.accepted.amount } : {}),
271
+ };
272
+ }
273
+ catch {
274
+ return undefined;
275
+ }
276
+ }
277
+ /** What the server tells the operator after serving a payment, per mode. */
278
+ function verdictFor(options, payment, settlementTx) {
279
+ switch (options.mode) {
280
+ case "no-settle":
281
+ return ("Served 200 without settling and without PAYMENT-RESPONSE. If your agent " +
282
+ "now treats the payment as made, it trusts a paywall that took nothing.");
283
+ case "wrong-settlement":
284
+ return (`Served 200 with PAYMENT-RESPONSE citing tx ${settlementTx}, which is not ` +
285
+ `this payment. If your agent accepts that without looking it up, a ` +
286
+ `dishonest server can claim any settlement.`);
287
+ case "wrong-network": {
288
+ const profile = serveNetwork(options);
289
+ return (`Your agent paid a challenge on ${payment.network ?? profile.mainnet} ` +
290
+ `(${profile.mainnetName}). An agent set up for testnet should have refused it.`);
291
+ }
292
+ case "overprice": {
293
+ const profile = serveNetwork(options);
294
+ return (`Your agent agreed to pay ${payment.amount ?? overpriceAmount(options.network)} base units` +
295
+ `${(options.asset ?? profile.asset) === profile.asset ? " (one million USDC)" : ""}. ` +
296
+ `An agent with a spending limit should have refused.`);
297
+ }
298
+ case "v1-challenge":
299
+ return payment.header === "X-PAYMENT" && payment.version === 1
300
+ ? "Your agent paid the v1 challenge as v1, in X-PAYMENT. Answered 402: wasit serve never settles."
301
+ : `Your agent answered a v1 challenge in ${payment.header} with x402Version ` +
302
+ `${payment.version ?? "?"}. A v1 server reads only X-PAYMENT with a v1 payload, ` +
303
+ `so it would ignore this payment. Answered 402.`;
304
+ case "malformed-header":
305
+ return ("Your agent paid although the PAYMENT-REQUIRED header does not decode: it paid on " +
306
+ "terms it could not have read. Answered 402.");
307
+ }
308
+ }
309
+ /**
310
+ * The modes whose challenge is not a well-formed x402 v2 challenge, on
311
+ * purpose. They answer a payment with 402: they are about the challenge, not
312
+ * the settlement.
313
+ */
314
+ export const BROKEN_CHALLENGE_MODES = ["v1-challenge", "malformed-header"];
315
+ /**
316
+ * Builds the server. Answers every path: a request without a payment header
317
+ * gets the mode's 402 challenge; one with a payment gets the mode's answer.
318
+ * Nothing is settled or forwarded in any mode.
319
+ */
320
+ export function createServeServer(options) {
321
+ const log = options.log ?? (() => { });
322
+ const settlementTx = options.settlementTx ?? serveNetwork(options).randomTx();
323
+ return http.createServer((request, response) => {
324
+ const where = `${request.method ?? "GET"} ${request.url ?? "/"}`;
325
+ // v2 sends PAYMENT-SIGNATURE; X-PAYMENT is the v1 name, still seen in the wild.
326
+ const headerName = request.headers["payment-signature"] !== undefined ? "PAYMENT-SIGNATURE" : "X-PAYMENT";
327
+ const header = request.headers["payment-signature"] ?? request.headers["x-payment"];
328
+ const paymentHeader = Array.isArray(header) ? header[0] : header;
329
+ if (paymentHeader === undefined) {
330
+ const url = `http://${request.headers.host ?? "localhost"}${request.url ?? "/"}`;
331
+ if (options.mode === "v1-challenge") {
332
+ const challenge = v1ChallengeFor(options, url);
333
+ const accept = challenge["accepts"][0];
334
+ log(`${where}: 402 x402 v1 challenge in the body, ${String(accept["maxAmountRequired"])} ` +
335
+ `base units on ${String(accept["network"])}, no PAYMENT-REQUIRED header`);
336
+ response.writeHead(402, { "Content-Type": "application/json" });
337
+ response.end(JSON.stringify(challenge));
338
+ return;
339
+ }
340
+ if (options.mode === "malformed-header") {
341
+ log(`${where}: 402 with a PAYMENT-REQUIRED header that does not decode`);
342
+ response.writeHead(402, {
343
+ "PAYMENT-REQUIRED": malformedHeaderFor(options, url),
344
+ "Content-Type": "application/json",
345
+ });
346
+ response.end("{}");
347
+ return;
348
+ }
349
+ const challenge = challengeFor(options, url);
350
+ const accept = challenge["accepts"][0];
351
+ log(`${where}: 402 challenge, ${String(accept["amount"])} base units on ${String(accept["network"])}`);
352
+ response.writeHead(402, {
353
+ "PAYMENT-REQUIRED": encode(challenge),
354
+ "Content-Type": "application/json",
355
+ });
356
+ response.end("{}");
357
+ return;
358
+ }
359
+ const payment = readPayment(paymentHeader, headerName);
360
+ if (payment === undefined) {
361
+ log(`${where}: payment header did not decode to JSON; answered 402.`);
362
+ response.writeHead(402, { "Content-Type": "application/json" });
363
+ response.end(JSON.stringify({ error: "invalid payment header" }));
364
+ return;
365
+ }
366
+ if (BROKEN_CHALLENGE_MODES.includes(options.mode)) {
367
+ log(`${where}: payment received in ${payment.header} for ${payment.amount ?? "?"} base units on ` +
368
+ `${payment.network ?? "?"}. ${verdictFor(options, payment, settlementTx)}`);
369
+ response.writeHead(402, { "Content-Type": "application/json" });
370
+ response.end(JSON.stringify({ error: "wasit serve never settles" }));
371
+ return;
372
+ }
373
+ const headers = { "Content-Type": "application/json" };
374
+ if (options.mode === "wrong-settlement") {
375
+ headers["PAYMENT-RESPONSE"] = encode({
376
+ success: true,
377
+ transaction: settlementTx,
378
+ network: payment.network ?? (options.network ?? DEFAULT_SERVE_NETWORK),
379
+ });
380
+ }
381
+ log(`${where}: payment received for ${payment.amount ?? "?"} base units on ` +
382
+ `${payment.network ?? "?"}. ${verdictFor(options, payment, settlementTx)}`);
383
+ response.writeHead(200, headers);
384
+ response.end(JSON.stringify({ resource: "paid content from wasit serve" }));
385
+ });
386
+ }
@@ -1,9 +1,12 @@
1
1
  /**
2
2
  * `wasit wallet` — testnet-only convenience commands for the payer keys the
3
- * other subcommands already read from .env. Deliberately has no --network
4
- * flag: Friendbot, the printed USDC issuer, and the whole idea of a
5
- * throwaway generated key only make sense on testnet, so there is nothing
6
- * here that could be pointed at pubnet by mistake.
3
+ * other subcommands already read from .env. `--network` takes testnets only
4
+ * (the ones `wasit serve` poses on): Friendbot, the printed USDC issuer, and
5
+ * the whole idea of a throwaway generated key only make sense on testnet, so
6
+ * there is nothing here that could be pointed at a mainnet by mistake.
7
+ * Stellar testnet is the default and the only network for the MPP roles; on
8
+ * Base Sepolia and Solana devnet the x402 payer needs USDC from Circle's
9
+ * faucet and no native token, since the facilitator pays the fee.
7
10
  *
8
11
  * Every failure path here exits 2 (configuration) or 1 (the operation ran and
9
12
  * failed) with a single-line message, the same contract the check subcommands
@@ -11,6 +14,18 @@
11
14
  * file ever has to inspect a Stellar SDK error type to decide which it is.
12
15
  */
13
16
  import type { Command } from "commander";
17
+ type WalletRole = "x402" | "mpp-charge" | "mpp-channel";
18
+ /** The testnets `wasit wallet` takes: the ones `wasit serve` poses on. */
19
+ export declare const WALLET_NETWORKS: readonly string[];
20
+ /**
21
+ * Checks --network against the testnets, and the role against the network:
22
+ * the MPP roles are Stellar only. Returns the problem, or undefined.
23
+ */
24
+ export declare function walletNetworkProblem(network: string, role: WalletRole): string | undefined;
25
+ /** Base units as a decimal amount, e.g. 19970000 with 6 decimals as 19.97. */
26
+ export declare function formatUnits(units: bigint, decimals: number): string;
27
+ /** What `wallet create --role x402 --network <not Stellar>` prints. */
28
+ export declare function generatedKeyLines(network: string, secret: string): string[];
14
29
  /** One role's row in `wallet status`. */
15
30
  export interface WalletStatusRow {
16
31
  readonly configured: boolean;
@@ -29,3 +44,4 @@ export interface WalletStatusRow {
29
44
  */
30
45
  export declare function walletStatusExitCode(explicitRole: boolean, rows: readonly WalletStatusRow[]): 0 | 2;
31
46
  export declare function registerWalletCommand(program: Command): void;
47
+ export {};
@@ -1,9 +1,12 @@
1
1
  /**
2
2
  * `wasit wallet` — testnet-only convenience commands for the payer keys the
3
- * other subcommands already read from .env. Deliberately has no --network
4
- * flag: Friendbot, the printed USDC issuer, and the whole idea of a
5
- * throwaway generated key only make sense on testnet, so there is nothing
6
- * here that could be pointed at pubnet by mistake.
3
+ * other subcommands already read from .env. `--network` takes testnets only
4
+ * (the ones `wasit serve` poses on): Friendbot, the printed USDC issuer, and
5
+ * the whole idea of a throwaway generated key only make sense on testnet, so
6
+ * there is nothing here that could be pointed at a mainnet by mistake.
7
+ * Stellar testnet is the default and the only network for the MPP roles; on
8
+ * Base Sepolia and Solana devnet the x402 payer needs USDC from Circle's
9
+ * faucet and no native token, since the facilitator pays the fee.
7
10
  *
8
11
  * Every failure path here exits 2 (configuration) or 1 (the operation ran and
9
12
  * failed) with a single-line message, the same contract the check subcommands
@@ -11,7 +14,8 @@
11
14
  * file ever has to inspect a Stellar SDK error type to decide which it is.
12
15
  */
13
16
  import { oraPromise } from "ora";
14
- import { createUsdcTrustline, fundWithFriendbot, generateCommitmentKey, generateTestnetWallet, getTestnetWalletStatus, publicKeyFromSecret, sendUsdcFromDistributor, TESTNET_USDC_ISSUER, } from "@wasit-dev/core";
17
+ import { createUsdcTrustline, fundWithFriendbot, generateCommitmentKey, generateTestnetWallet, getTestnetWalletStatus, paymentChainFor, publicKeyFromSecret, sendUsdcFromDistributor, TESTNET_USDC_ISSUER, } from "@wasit-dev/core";
18
+ import { DEFAULT_SERVE_NETWORK, SERVE_NETWORKS } from "./serve.js";
15
19
  /** Every role a key can be generated for. */
16
20
  const ROLES = ["x402", "mpp-charge", "mpp-channel"];
17
21
  /**
@@ -75,6 +79,64 @@ function resolvePublicKey(role) {
75
79
  process.exit(2);
76
80
  }
77
81
  }
82
+ /** The testnets `wasit wallet` takes: the ones `wasit serve` poses on. */
83
+ export const WALLET_NETWORKS = Object.keys(SERVE_NETWORKS);
84
+ /**
85
+ * Checks --network against the testnets, and the role against the network:
86
+ * the MPP roles are Stellar only. Returns the problem, or undefined.
87
+ */
88
+ export function walletNetworkProblem(network, role) {
89
+ if (!WALLET_NETWORKS.includes(network)) {
90
+ return `Unknown --network "${network}". Expected a testnet: ${WALLET_NETWORKS.join(", ")}.`;
91
+ }
92
+ if (network !== DEFAULT_SERVE_NETWORK && role !== "x402") {
93
+ return `--role ${role} is Stellar only: MPP runs on Stellar. Only --role x402 takes --network ${network}.`;
94
+ }
95
+ return undefined;
96
+ }
97
+ function requireNetwork(value, role) {
98
+ const network = value ?? DEFAULT_SERVE_NETWORK;
99
+ const problem = walletNetworkProblem(network, role);
100
+ if (problem !== undefined) {
101
+ console.error(problem);
102
+ process.exit(2);
103
+ }
104
+ return network;
105
+ }
106
+ /** Base units as a decimal amount, e.g. 19970000 with 6 decimals as 19.97. */
107
+ export function formatUnits(units, decimals) {
108
+ const scale = 10n ** BigInt(decimals);
109
+ const fraction = (units % scale).toString().padStart(decimals, "0").replace(/0+$/, "");
110
+ return `${units / scale}${fraction === "" ? "" : `.${fraction}`}`;
111
+ }
112
+ /** Where a payer on `network` gets its USDC, and what it does not need. */
113
+ function faucetLines(network, address) {
114
+ const profile = SERVE_NETWORKS[network];
115
+ return [
116
+ `Fund it with USDC at https://faucet.circle.com (network ${profile.faucetNetwork}),`,
117
+ `pasting ${address}.`,
118
+ `It needs no ${profile.nativeToken}: the facilitator pays the fee.`,
119
+ ];
120
+ }
121
+ /** What `wallet create --role x402 --network <not Stellar>` prints. */
122
+ export function generatedKeyLines(network, secret) {
123
+ const chain = paymentChainFor(network);
124
+ const address = chain.payerAddress(secret);
125
+ return [
126
+ `Generated a new ${SERVE_NETWORKS[network].name} key for x402:`,
127
+ "",
128
+ `Address: ${address}`,
129
+ `Secret: ${secret}`,
130
+ "",
131
+ "Paste into .env:",
132
+ "",
133
+ `${chain.payerKeyEnv}=${secret}`,
134
+ "",
135
+ ...faucetLines(network, address),
136
+ "",
137
+ "Testnet only — never reuse this key, and never put a mainnet key here.",
138
+ ];
139
+ }
78
140
  function messageOf(error) {
79
141
  return error instanceof Error ? error.message : String(error);
80
142
  }
@@ -114,28 +176,90 @@ function printWalletStatus(role, publicKey, status) {
114
176
  console.log(formatBalance(balance));
115
177
  }
116
178
  }
179
+ /**
180
+ * The configured x402 payer on a network other than Stellar testnet, exiting
181
+ * 2 when its key is unset or is not a key for that chain. The message never
182
+ * echoes the key.
183
+ */
184
+ function resolvePayer(network) {
185
+ const chain = paymentChainFor(network);
186
+ const secret = process.env[chain.payerKeyEnv];
187
+ if (!secret) {
188
+ console.error(`${chain.payerKeyEnv} is not set. Run \`wasit wallet create --role x402 --network ${network}\` first.`);
189
+ process.exit(2);
190
+ }
191
+ try {
192
+ return { address: chain.payerAddress(secret) };
193
+ }
194
+ catch {
195
+ console.error(`${chain.payerKeyEnv} is not a ${chain.name} key.`);
196
+ process.exit(2);
197
+ }
198
+ }
199
+ /**
200
+ * Prints the x402 payer's USDC balance on a network other than Stellar
201
+ * testnet, and returns the exit code: 2 when it could not be read, since
202
+ * `wallet status` must not pass on a balance it never saw.
203
+ */
204
+ async function printPayerStatus(network, jsonMode) {
205
+ const chain = paymentChainFor(network);
206
+ const profile = SERVE_NETWORKS[network];
207
+ const { address } = resolvePayer(network);
208
+ let balance;
209
+ let error;
210
+ try {
211
+ const read = chain.payerBalance(network, chain.resolveRpcUrl(network), address, profile.asset);
212
+ balance = jsonMode ? await read : await oraPromise(read, `Checking x402 on ${profile.name}...`);
213
+ if (balance === undefined)
214
+ error = "the chain gave no balance";
215
+ }
216
+ catch (caught) {
217
+ error = messageOf(caught);
218
+ }
219
+ if (jsonMode) {
220
+ console.log(JSON.stringify([{ role: "x402", network, address, usdc: balance === undefined ? undefined : formatUnits(balance, profile.decimals), error }], null, 2));
221
+ }
222
+ else {
223
+ console.log(`x402 ${address} (${profile.name})`);
224
+ console.log(balance === undefined
225
+ ? ` Could not check: ${error}`
226
+ : ` ${"USDC".padEnd(10)} ${formatUnits(balance, profile.decimals)}`);
227
+ if (balance === 0n)
228
+ for (const line of faucetLines(network, address))
229
+ console.log(` ${line}`);
230
+ }
231
+ return balance === undefined ? 2 : 0;
232
+ }
117
233
  export function registerWalletCommand(program) {
118
234
  const wallet = program
119
235
  .command("wallet")
120
- .description("Generate, fund, and inspect disposable Stellar testnet wallets");
236
+ .description("Generate, fund, and inspect disposable testnet wallets: Stellar's payers, and the x402 payer on Base Sepolia, Ethereum Sepolia and Solana devnet");
121
237
  wallet
122
238
  .command("status")
123
239
  .description("Show balances for the configured payer role(s)")
124
240
  .option("--role <role>", `One of: ${ACCOUNT_ROLES.join(", ")}. Default: check both.`)
241
+ .option("--network <network>", `Testnet: ${WALLET_NETWORKS.join(", ")}`, DEFAULT_SERVE_NETWORK)
125
242
  .option("--json", "Print as JSON instead of formatted text", false)
126
243
  .addHelpText("after", `
127
244
  Examples:
128
245
  $ wasit wallet status
129
246
  $ wasit wallet status --role mpp-charge --json
247
+ $ wasit wallet status --network eip155:84532
130
248
 
131
249
  With --role, exits 2 if that role could not be checked (key not set,
132
250
  unreadable, or lookup failed); without it, every role is a row and it exits 0.
133
251
 
134
- Testnet only — there is no --network flag. mpp-channel is not accepted here
252
+ Testnet only. On a network other than Stellar testnet it shows the x402
253
+ payer's USDC balance. mpp-channel is not accepted here
135
254
  even when configured: COMMITMENT_SECRET_HEX only ever signs off-chain (see
136
255
  docs/guides/configuration.md) and has no on-chain balance of its own.`)
137
256
  .action(async (opts) => {
138
257
  const jsonMode = opts.json === true;
258
+ if (opts.network !== DEFAULT_SERVE_NETWORK) {
259
+ const role = opts.role === undefined ? "x402" : requireRole(opts.role, ACCOUNT_ROLES);
260
+ const network = requireNetwork(opts.network, role);
261
+ process.exit(await printPayerStatus(network, jsonMode));
262
+ }
139
263
  const roles = opts.role !== undefined ? [requireRole(opts.role, ACCOUNT_ROLES)] : ACCOUNT_ROLES;
140
264
  const rows = [];
141
265
  for (const role of roles) {
@@ -191,11 +315,14 @@ docs/guides/configuration.md) and has no on-chain balance of its own.`)
191
315
  .command("create")
192
316
  .description("Generate a new testnet key for a payer role")
193
317
  .requiredOption("--role <role>", `One of: ${ROLES.join(", ")}`)
194
- .option("--fund", "Immediately fund the new key with testnet XLM", false)
318
+ .option("--network <network>", `Testnet: ${WALLET_NETWORKS.join(", ")}`, DEFAULT_SERVE_NETWORK)
319
+ .option("--fund", "Immediately fund the new key with testnet XLM (Stellar only)", false)
195
320
  .addHelpText("after", `
196
321
  Examples:
197
322
  $ wasit wallet create --role mpp-charge --fund
198
323
  $ wasit wallet create --role mpp-channel
324
+ $ wasit wallet create --role x402 --network eip155:84532
325
+ $ wasit wallet create --role x402 --network solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1
199
326
 
200
327
  Testnet only. Prints the exact .env line(s) to paste — never writes to .env
201
328
  itself, so it can never silently overwrite something already there.
@@ -204,6 +331,18 @@ The generated secret is printed to stdout: do not run this on a screen you
204
331
  are recording, and never paste a pubnet key into these variables.`)
205
332
  .action(async (opts) => {
206
333
  const role = requireRole(opts.role, ROLES);
334
+ const network = requireNetwork(opts.network, role);
335
+ if (network !== DEFAULT_SERVE_NETWORK) {
336
+ if (opts.fund === true) {
337
+ console.error(`--fund is Stellar only (Friendbot). On ${SERVE_NETWORKS[network].name} the payer ` +
338
+ "needs USDC from https://faucet.circle.com and nothing else.");
339
+ process.exit(2);
340
+ }
341
+ for (const line of generatedKeyLines(network, paymentChainFor(network).generatePayerKey())) {
342
+ console.log(line);
343
+ }
344
+ return;
345
+ }
207
346
  if (role === "mpp-channel") {
208
347
  const key = generateCommitmentKey();
209
348
  console.log("Generated a new MPP commitment key (a signing key, not a funded account " +
@@ -244,6 +383,7 @@ are recording, and never paste a pubnet key into these variables.`)
244
383
  .command("fund")
245
384
  .description("Fund a configured payer role with testnet XLM or USDC")
246
385
  .requiredOption("--role <role>", `One of: ${ACCOUNT_ROLES.join(", ")}`)
386
+ .option("--network <network>", `Testnet: ${WALLET_NETWORKS.join(", ")}`, DEFAULT_SERVE_NETWORK)
247
387
  .option("--asset <asset>", "xlm or usdc", "xlm")
248
388
  .option("--amount <amount>", "USDC amount to request from the distributor account", "50")
249
389
  .addHelpText("after", `
@@ -256,9 +396,20 @@ Examples:
256
396
  actually receiving a balance needs either a manual visit to
257
397
  https://faucet.circle.com (paste the printed public key) or
258
398
  WASIT_USDC_DISTRIBUTOR_SECRET set in .env, naming an account you already
259
- funded that way once — there is no scriptable USDC faucet for Stellar.`)
399
+ funded that way once — there is no scriptable USDC faucet for Stellar.
400
+
401
+ On another network (--network) there is nothing to do on-chain first: it
402
+ prints where to get USDC for the configured x402 payer.`)
260
403
  .action(async (opts) => {
261
404
  const role = requireRole(opts.role, ACCOUNT_ROLES);
405
+ const network = requireNetwork(opts.network, role);
406
+ if (network !== DEFAULT_SERVE_NETWORK) {
407
+ const { address } = resolvePayer(network);
408
+ console.log(`No faucet can be called for ${SERVE_NETWORKS[network].name} from here.`);
409
+ for (const line of faucetLines(network, address))
410
+ console.log(line);
411
+ return;
412
+ }
262
413
  const { secret, publicKey } = resolvePublicKey(role);
263
414
  const asset = opts.asset;
264
415
  if (asset !== "xlm" && asset !== "usdc") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wasit-dev/cli",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "CLI for x402/MPP protocol-conformance testing on Stellar — verifies a service's payment flow settles on-chain per spec.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -41,7 +41,7 @@
41
41
  "typecheck": "tsc -p test/tsconfig.json"
42
42
  },
43
43
  "dependencies": {
44
- "@wasit-dev/core": "^0.6.0",
44
+ "@wasit-dev/core": "^0.7.0",
45
45
  "cfonts": "^3.3.1",
46
46
  "commander": "^15.0.0",
47
47
  "dotenv": "^17.4.2",