Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(x402-modal): export the version and document the discover entry point

nirholas124cc4ad616c
diff --git a/docs/ux-flows/09-x402-agent-commerce.md b/docs/ux-flows/09-x402-agent-commerce.md
index 4d1c93481..fadda2638 100644
--- a/docs/ux-flows/09-x402-agent-commerce.md
+++ b/docs/ux-flows/09-x402-agent-commerce.md
@@ -65,7 +65,7 @@ choreographed two-agent narrative driven by Server-Sent Events.
- **Entry point:** Directory of live x402-paid endpoints (merged across facilitators) as a card grid with filters.
- **Prerequisites / gates:** None to browse; a wallet only when paying ("Try it").
- **Steps (5 required + 2 optional):**
- 1. Page loads → `GET /api/bazaar/list` → renders endpoint cards.
+ 1. Page loads → `GET /api/bazaar/list` → renders endpoint cards. The handler merges every configured facilitator behind a 60s in-process catalog memo (`BAZAAR_CATALOG_TTL_MS`), returns at most `limit` rows (default 200) and reports the pre-cut match count as `total`.
2. (optional) Filter by type (HTTP/MCP), network (EVM/Solana), max price, extension, sort.
3. (optional) Search (`/api/bazaar/search?query=`) or scroll.
4. Click a card action: HTTP → **Try it** (pay flow); MCP tool → **Inspect tool** (details only — JSON-RPC, not auto-callable); **Details** → modal + `/api/bazaar/context?resource=`.
@@ -74,7 +74,7 @@ choreographed two-agent narrative driven by Server-Sent Events.
- **Decision points / branches:** HTTP vs MCP (MCP = inspect only); pay success/cancel/error → distinct receipt states; explorer chosen from endpoint network (Solscan/Basescan/Arbiscan/etc.).
- **External calls / dependencies:** `/api/bazaar/list|search|context`, `/x402.js`, merchant endpoint, multi-chain explorers.
- **Success state:** green receipt with tx hash + explorer link + result JSON; SR announcement "Payment succeeded for <service>".
-- **Empty / error states:** no results → "No matching services…"; catalog unreachable → "Couldn't reach the catalog… Retry"; modal load fail → "Payment module failed to load"; cancel → receipt hidden; error → red receipt.
+- **Empty / error states:** no results → "No matching services…"; catalog unreachable → "Couldn't reach the catalog… Retry" (every `/api/bazaar/*` handler answers `502 facilitator_error` when all facilitators fail, so a total outage never renders as an empty catalog); modal load fail → "Payment module failed to load"; cancel → receipt hidden; error → red receipt.
- **Step count:** 5 required (+2 optional).
### x402 Arbitrage — `/arbitrage`
@@ -100,7 +100,7 @@ choreographed two-agent narrative driven by Server-Sent Events.
- **Steps (2 required + 3 optional):**
1. Directory load → skeleton → `GET /api/bazaar/providers?limit=500` → provider cards (service count, median/min price, tags, networks).
2. (optional) Sort (most services / cheapest / most expensive / most networks); (optional) search by host/tag.
- 3. Click a card → `/providers?host=…` → profile fetch `GET /api/bazaar/providers?host=` → sidebar (metrics, "Visit site", "Open in catalog") + category/network charts + sorted services table.
+ 3. Click a card → `/providers?host=…` → profile fetch `GET /api/bazaar/providers?host=` → sidebar (metrics, "Visit site", "Open in catalog") + category/network charts + sorted services table. The listings array is capped at `limit` (default 200, max 1000) while `listingTotal` carries the provider's real count, so the heading reads "N listings (showing 200)" for the multi-thousand-listing hosts.
4. (optional) Click a listing row → `/bazaar?q=<service>`.
- **Decision points / branches:** directory vs profile keyed on `?host`; sort order; real-time search.
- **External calls / dependencies:** `/api/bazaar/providers` (list + single host), facilitator URLs, downstream explorers via `/bazaar`.
@@ -170,7 +170,7 @@ choreographed two-agent narrative driven by Server-Sent Events.
1. Load page → render cached data (or skeletons) → auto-poll `GET /api/agents/unstoppable-status` immediately, then every 60s (exponential backoff to 5 min on transient errors).
2. View data: `200` → hero balance + status + runway, 24h earnings/costs, lifetime net, activity feed (THINK/EARN/REFLECT/IDLE/…), latest reflection. `402` → payment notice + cached data + "Unlock live data — $0.01".
3. (optional, repeatable) Click **Donate $0.01** → `window.X402.pay({ endpoint: status, method:'GET', action:'Fund the … runway' })` → on success toast + fresh live data; each donation funds one live query and directly funds the agent.
-- **Decision points / branches:** cache present vs not; `200` (unlocked) vs `402` (paywalled); `5xx` → backoff + keep cache; donation low-balance → retry with link to `/pay`; donation cancel → no charge.
+- **Decision points / branches:** cache present vs not; `200` (unlocked) vs `402` (paywalled); `5xx` → backoff + keep cache; donation low-balance → retry with link to `/pay`; donation cancel → no charge. A caller holding the `x402:bypass` install scope is served the live reading for free and is deliberately NOT recorded as revenue, so the runway the page reports stays honest.
- **External calls / dependencies:** `/api/agents/unstoppable-status` (free 402 challenge + optional paid query), `/x402.js`, Base/Solana settlement.
- **Success state:** live hero + stats + non-empty activity feed + reflection + "Updated X ago".
- **Empty / error states:** initial skeleton "Fetching live data…"; `402` notice with cached data; no-cache `402` → zeroed state ("Pay $0.01 to see live data").
@@ -204,10 +204,10 @@ choreographed two-agent narrative driven by Server-Sent Events.
4. Click **Inscribe forever** → native `confirm()` showing estimated BTC cost + address ("payment is final once broadcast. Continue?").
5. `POST /api/forever/inscribe` `{ message, receiveAddress, feeRate }` → creates OrdinalsBot order → returns charge address, amount (sats), Lightning invoice, mempool URL; order persisted to `sessionStorage forever:order` → **pay view**.
6. Pay view: QR (BIP-21), amount, pay-to/Lightning/receive/order-id rows, "Open in wallet" / "View on mempool" / "Cancel". User sends BTC from their own wallet.
- 7. Auto-poll `GET /api/forever/status?id=<orderId>` every 6s → `waiting-payment → payment-received → inscribing → inscribed`.
+ 7. Auto-poll `GET /api/forever/status?id=<orderId>` every 6s → `waiting-payment → payment-received → inscribing → inscribed`. Once a reveal txid exists the response also carries `inscription.onchain` (confirmed, confirmations, block height and time) read keyless from Blockstream Esplora, so finality depth comes from the chain rather than from OrdinalsBot's order state; an Esplora outage degrades that field to `null` instead of failing the poll.
8. On `inscribed` → **win view**: large message, Inscription link (ordinals.com), reveal-tx link (mempool.space), receive address, "Bitcoin mainnet"; share to X / copy permalink / inscribe another.
- **Decision points / branches:** empty / > 1500 bytes / invalid Taproot / invalid fee rate → inline errors; confirm-dialog cancel → stays in compose; order-create `502/503` → "Inscription failed. Try again."; status `failed` → OrdinalsBot contact note; reload mid-payment → `resumeIfAny()` restores the pay view + resumes polling.
-- **External calls / dependencies:** `/api/forever/inscribe` + `/api/forever/status` → **OrdinalsBot** (`api.ordinalsbot.com`, Bitcoin mainnet Taproot inscription), CoinGecko (USD, best-effort), QR server, mempool.space + ordinals.com for verification.
+- **External calls / dependencies:** `/api/forever/inscribe` + `/api/forever/status` → **OrdinalsBot** (`api.ordinalsbot.com`, Bitcoin mainnet Taproot inscription), Blockstream Esplora (`api/_lib/esplora.js`, keyless reveal-tx confirmations, fail-soft), CoinGecko (USD, best-effort), QR server, mempool.space + ordinals.com for verification.
- **Success state:** win view with permanent inscription + reveal-tx links + share buttons.
- **Empty / error states:** compose validation errors; inscribe failure banner; pay-view polling states; order `failed` message with support info.
- **Step count:** 6 required (+6 optional).
@@ -334,4 +334,5 @@ choreographed two-agent narrative driven by Server-Sent Events.
- **Auto-play demos:** `/agent-exchange`, `/agent-trade`, `/agent-economy`, `/demo` need one user click to start, then auto-play. `/live` adds an auth gate for real settlement. `/play/arena` is fully autonomous (agents trade themselves; user only watches/moves/inspects) and uses **no x402** — real pre-funded Solana trades.
- **Forever** is the only **non-x402** payment in the cluster: native Bitcoin (or Lightning) to an OrdinalsBot charge address, inscribing a real Taproot text inscription on Bitcoin mainnet.
- **Adjacent economy surfaces (2026-08-01, not yet traced as full sections):** `/economy-lab` (Runway Lab, a live digital twin of the x402 payment rail; backend `api/x402/runway-lab.js`), `/pay-simulator` (Spend Policy Simulator: dry-run an agent spending policy against real x402 prices), `/flow` (Money Flow Map, see `docs/money-flow-map.md`), `/play/solver` (see `docs/economy-solver.md`), and `/conversions`.
+- **Inline handlers are gone:** every HTML response in this cluster ships a CSP whose `script-src` lists SHA-256 hashes of the inline scripts in the bytes actually sent, so no page here may carry an `onclick=`/`onerror=` attribute (not even inside a template literal). The card markup these flows render declares intent with `data-fallback`, `data-action="reload"` or `data-stop-propagation` and `public/inline-behaviors.js` delegates it; `scripts/audit-inline-handlers.mjs` fails the build if one comes back.
- **Source coverage:** all 17 routes located and traced from real source. `/tutor` resolves to `public/tutor.html` + `public/tutor.js` (served statically; no explicit vite map entry needed). No source was missing.
diff --git a/x402-modal-sdk/README.md b/x402-modal-sdk/README.md
index dea3a2038..90244f55a 100644
--- a/x402-modal-sdk/README.md
+++ b/x402-modal-sdk/README.md
@@ -164,6 +164,28 @@ Returns `{ ok: true, result, payment?, siwx?, response }`. `payment` is present
on a fresh payment (`{ network, payer, transaction }`); `siwx` is present when
the user re-entered via sign-in instead of paying.
+### `discover(options): Promise<PaymentChallenge>`
+
+Step 1 of `pay()` on its own: probe an endpoint and return its parsed `402`
+challenge without opening any UI. Takes `endpoint` (required), `method`, `body`
+and `headers`; touches no DOM and no wallet, so it also runs on a server, in a
+CLI, or inside an agent that has no modal at all.
+
+```js
+import { discover } from '@three-ws/x402-modal';
+
+const challenge = await discover({ endpoint: '/api/paid/summarize' });
+for (const a of challenge.accepts) {
+ console.log(a.network, a.amount, a.extra?.name); // eip155:8453 1000 USDC
+}
+```
+
+`accepts[]` comes back normalized (spec-canonical `maxAmountRequired` coerced to
+`amount`), read from the response body or the base64 `payment-required` header,
+whichever carries it. It rejects when the endpoint answers with no readable
+challenge, including a free `200`: pointing it at an unpaid route is an error,
+never a silent success.
+
### `configure(config): config` · `getConfig(): config`
Set global defaults once at startup. See [Configuration](#configuration).
diff --git a/x402-modal-sdk/docs/PROTOCOL.md b/x402-modal-sdk/docs/PROTOCOL.md
index 50e0036dd..da71c8514 100644
--- a/x402-modal-sdk/docs/PROTOCOL.md
+++ b/x402-modal-sdk/docs/PROTOCOL.md
@@ -17,6 +17,12 @@ when debugging an integration or building the server side.
│ accepts[] = [{ scheme, network, asset,
│ payTo, amount, extra… }, …]
▼
+ Step 1 is exported on its own as `discover({ endpoint, … })`: it runs
+ exactly this probe, returns the parsed envelope with `accepts[]`
+ normalized, and touches neither the DOM nor a wallet. Use it to price a
+ call, or to check which networks an endpoint takes, before opening the
+ modal (or from a server / CLI / agent that has no modal at all).
+ ▼
┌── 2. CONNECT ───────────────────────────────────────────────────────────┐
│ The modal picks accepts it can satisfy: │
│ • Solana (`solana:*`) → Phantom (`window.solana` / `window.phantom`) │
diff --git a/x402-modal-sdk/package.json b/x402-modal-sdk/package.json
index a959d1f11..4cf24a051 100644
--- a/x402-modal-sdk/package.json
+++ b/x402-modal-sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@three-ws/x402-modal",
- "version": "0.2.2",
+ "version": "0.3.0",
"description": "A drop-in, dependency-free payment modal for any x402 paid endpoint. One script tag turns a 402 challenge into a polished checkout: wallet connect (Phantom on Solana, MetaMask/EVM via EIP-3009), the 402 → sign → settle flow, SIWX re-entry, spending caps, and a receipt — vanilla JS, no bundler required. Powered by three.ws.",
"keywords": [
"x402",
diff --git a/x402-modal-sdk/src/global.js b/x402-modal-sdk/src/global.js
index 3cdb9a63c..7959ef74b 100644
--- a/x402-modal-sdk/src/global.js
+++ b/x402-modal-sdk/src/global.js
@@ -6,12 +6,12 @@
// a line of JS,
// 2. binds every `[data-x402-endpoint]` element and re-scans the DOM as
// merchants inject buttons,
-// 3. exposes `window.X402 = { pay, init, configure, version }`.
+// 3. exposes `window.X402 = { pay, discover, init, configure, version }`.
//
// For bundler / npm consumers, import the side-effect-free core instead:
// import { pay, configure } from '@three-ws/x402-modal';
-import { pay, init, configure, version } from './x402-modal.js';
+import { pay, discover, init, configure, version } from './x402-modal.js';
// Pull optional config off the script tag, e.g.
// <script src=".../x402.global.js"
@@ -58,7 +58,7 @@ if (typeof document !== 'undefined') {
// Expose to merchants' inline scripts.
if (typeof window !== 'undefined') {
- window.X402 = Object.freeze({ pay, init, configure, version });
+ window.X402 = Object.freeze({ pay, discover, init, configure, version });
}
-export { pay, init, configure, version };
+export { pay, discover, init, configure, version };
diff --git a/x402-modal-sdk/src/x402-modal.js b/x402-modal-sdk/src/x402-modal.js
index b6bcc7613..86fa1a840 100644
--- a/x402-modal-sdk/src/x402-modal.js
+++ b/x402-modal-sdk/src/x402-modal.js
@@ -1,8 +1,9 @@
// @three-ws/x402-modal — a drop-in payment modal for any x402 paid endpoint.
//
// This is the canonical, side-effect-free core. It exports the public API
-// (`pay`, `init`, `configure`, `getConfig`, `version`, `CheckoutModal`, and the
-// declarative helpers `bindElement` / `readOptsFrom`) but does NOT touch
+// (`pay`, `discover`, `init`, `configure`, `getConfig`, `version`,
+// `CheckoutModal`, and the declarative helpers `bindElement` /
+// `readOptsFrom`) but does NOT touch
// `window` or auto-bind anything on import — that lives in `global.js`, which is
// what the CDN <script> build ships.
//
@@ -37,7 +38,9 @@ import {
buildSiwxMessage,
} from './util.js';
-const VERSION = '0.2.0';
+// Kept byte-identical to package.json's `version`; test/configure.test.js pins
+// the two together so a release bump cannot leave the shipped string behind.
+const VERSION = '0.3.0';
// ─────────────────────────────────────────────────────────── configuration ───
// Everything the host wants to brand or repoint lives here. Defaults reproduce
@@ -1334,6 +1337,26 @@ async function postJson(url, body) {
return data;
}
+/**
+ * Probe an x402 endpoint and return its parsed payment challenge without
+ * opening any UI. Accepts HTTP 402 (standard x402) or HTTP 401 with a
+ * `payment-required` header (MCP 2025-06-18 spec), and reads the challenge from
+ * the response body or that header, whichever carries the `accepts` array.
+ *
+ * This is step 1 of the flow `pay()` runs, exported on its own because it is
+ * pure protocol: it touches no DOM and no wallet, so a server, a CLI, or an
+ * agent can price a paid call (or enumerate the networks it accepts) before
+ * deciding to open the modal at all.
+ *
+ * @param {{endpoint: string, method?: string, body?: unknown, headers?: Record<string,string>}} opts
+ * @returns {Promise<object>} the x402 PaymentRequired envelope, `accepts[]` normalized
+ * @throws {Error} when the endpoint does not answer with a readable challenge
+ */
+export async function discover(opts) {
+ if (!opts?.endpoint) throw new Error('X402.discover: endpoint is required');
+ return discoverChallenge(opts);
+}
+
// Probe the merchant endpoint with a benign request to extract the 402
// challenge. Accepts HTTP 402 (standard x402) or HTTP 401 with a
// `payment-required` header (MCP 2025-06-18 spec).
diff --git a/x402-modal-sdk/test/configure.test.js b/x402-modal-sdk/test/configure.test.js
index 9cf211497..9e717014c 100644
--- a/x402-modal-sdk/test/configure.test.js
+++ b/x402-modal-sdk/test/configure.test.js
@@ -1,14 +1,25 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { configure, getConfig, version, pay, init } from '../src/x402-modal.js';
+import { readFileSync } from 'node:fs';
+import { configure, getConfig, version, pay, discover, init } from '../src/x402-modal.js';
+
+const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
test('public API surface is intact', () => {
assert.equal(typeof pay, 'function');
+ assert.equal(typeof discover, 'function');
assert.equal(typeof init, 'function');
assert.equal(typeof configure, 'function');
assert.match(version, /^\d+\.\d+\.\d+$/);
});
+// The exported string is what merchants read in bug reports and what the
+// builder-code echo carries. It was hardcoded and drifted two patch releases
+// behind package.json; pin the two so a release bump cannot leave it behind.
+test('the exported version matches package.json', () => {
+ assert.equal(version, pkg.version);
+});
+
test('init() is a no-op without a document (does not throw in Node)', () => {
assert.doesNotThrow(() => init());
});
diff --git a/x402-modal-sdk/test/discover.test.js b/x402-modal-sdk/test/discover.test.js
new file mode 100644
index 000000000..d5060da2d
--- /dev/null
+++ b/x402-modal-sdk/test/discover.test.js
@@ -0,0 +1,161 @@
+// Core-path coverage for the protocol leg of the modal: step 1 of
+// `pay()` (discover the 402 challenge), exercised over a REAL HTTP server
+// speaking real x402 responses. Steps 2-4 (connect / authorize / verify) need a
+// wallet extension and a browser, so they are covered by the live demo page in
+// `examples/`; everything a merchant's server can get wrong about the challenge
+// itself is covered here.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { once } from 'node:events';
+import { discover } from '../src/x402-modal.js';
+
+// A real x402 v2 PaymentRequired envelope, shaped exactly as a merchant emits
+// it: two `accepts` entries (Solana + Base), spec-canonical `maxAmountRequired`
+// on one of them so the normalization is exercised end to end.
+const CHALLENGE = {
+ x402Version: 2,
+ error: 'X-PAYMENT header is required',
+ resource: { url: 'http://127.0.0.1/paid/echo', description: 'echo a string' },
+ accepts: [
+ {
+ scheme: 'exact',
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ asset: 'THREEsynthetic11111111111111111111111111111',
+ payTo: 'THREEsynthetic22222222222222222222222222222',
+ maxAmountRequired: '1000',
+ extra: { name: 'USDC', decimals: 6, feePayer: 'THREEsynthetic33333333333333333333333333333' },
+ },
+ {
+ scheme: 'exact',
+ network: 'eip155:8453',
+ asset: '0x0000000000000000000000000000000000000001',
+ payTo: '0x0000000000000000000000000000000000000002',
+ amount: '1000',
+ extra: { name: 'USDC', decimals: 6, version: '2' },
+ },
+ ],
+};
+
+const b64 = (obj) => Buffer.from(JSON.stringify(obj), 'utf8').toString('base64');
+
+// One server, several routes, each reproducing a challenge style seen in the
+// wild. Started once for the file and torn down at the end.
+async function startServer() {
+ const seen = [];
+ const server = createServer(async (req, res) => {
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ seen.push({
+ method: req.method,
+ url: req.url,
+ contentType: req.headers['content-type'],
+ auth: req.headers.authorization,
+ body: Buffer.concat(chunks).toString('utf8'),
+ });
+
+ if (req.url === '/paid/echo') {
+ res.writeHead(402, { 'content-type': 'application/json' });
+ return res.end(JSON.stringify(CHALLENGE));
+ }
+ // MCP 2025-06-18: 401 carrying the whole envelope in a base64 header.
+ if (req.url === '/mcp/echo') {
+ res.writeHead(401, { 'payment-required': b64(CHALLENGE), 'content-type': 'application/json' });
+ return res.end(JSON.stringify({ error: 'payment required' }));
+ }
+ // 402 whose body carries only an error string; the envelope is header-side.
+ if (req.url === '/header-only') {
+ res.writeHead(402, { 'payment-required': b64(CHALLENGE), 'content-type': 'application/json' });
+ return res.end(JSON.stringify({ error: 'payment required' }));
+ }
+ // 402 with a body that parses but advertises nothing payable.
+ if (req.url === '/empty-accepts') {
+ res.writeHead(402, { 'content-type': 'application/json' });
+ return res.end(JSON.stringify({ x402Version: 2, accepts: [] }));
+ }
+ // A free route: pointing the modal here must be a loud error, not a silent pass.
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ ok: true, free: true }));
+ });
+ server.listen(0, '127.0.0.1');
+ await once(server, 'listening');
+ const { port } = server.address();
+ return { origin: `http://127.0.0.1:${port}`, seen, close: () => server.close() };
+}
+
+test('discover() parses a real 402 challenge and normalizes maxAmountRequired', async (t) => {
+ const srv = await startServer();
+ t.after(srv.close);
+
+ const challenge = await discover({ endpoint: `${srv.origin}/paid/echo` });
+
+ assert.equal(challenge.x402Version, 2);
+ assert.equal(challenge.accepts.length, 2);
+ // Spec-canonical maxAmountRequired coerced to the `amount` everything downstream reads.
+ assert.equal(challenge.accepts[0].amount, '1000');
+ assert.equal(challenge.accepts[0].network, CHALLENGE.accepts[0].network);
+ // An entry that already carried `amount` is passed through untouched.
+ assert.equal(challenge.accepts[1].amount, '1000');
+ assert.equal(challenge.accepts[1].network, 'eip155:8453');
+});
+
+test('discover() reads the MCP 401 + payment-required header envelope', async (t) => {
+ const srv = await startServer();
+ t.after(srv.close);
+
+ const challenge = await discover({ endpoint: `${srv.origin}/mcp/echo` });
+ assert.equal(challenge.accepts.length, 2);
+ assert.equal(challenge.accepts[0].amount, '1000');
+});
+
+test('discover() falls back to the header envelope when the 402 body has no accepts', async (t) => {
+ const srv = await startServer();
+ t.after(srv.close);
+
+ const challenge = await discover({ endpoint: `${srv.origin}/header-only` });
+ assert.equal(challenge.accepts.length, 2);
+});
+
+test('discover() forwards method, body and headers to the merchant', async (t) => {
+ const srv = await startServer();
+ t.after(srv.close);
+
+ await discover({
+ endpoint: `${srv.origin}/paid/echo`,
+ method: 'POST',
+ body: { text: 'hello world' },
+ headers: { authorization: 'Bearer merchant-token' },
+ });
+
+ const req = srv.seen.at(-1);
+ assert.equal(req.method, 'POST');
+ assert.equal(req.auth, 'Bearer merchant-token');
+ // An object body is JSON-encoded and content-type is set for the caller.
+ assert.equal(req.contentType, 'application/json');
+ assert.deepEqual(JSON.parse(req.body), { text: 'hello world' });
+});
+
+test('discover() rejects a free endpoint instead of silently succeeding', async (t) => {
+ const srv = await startServer();
+ t.after(srv.close);
+
+ await assert.rejects(
+ () => discover({ endpoint: `${srv.origin}/free` }),
+ /did not return 402 \(got 200\)/,
+ );
+});
+
+test('discover() rejects a 402 that advertises nothing payable', async (t) => {
+ const srv = await startServer();
+ t.after(srv.close);
+
+ await assert.rejects(
+ () => discover({ endpoint: `${srv.origin}/empty-accepts` }),
+ /no `accepts` array could be found/,
+ );
+});
+
+test('discover() requires an endpoint', async () => {
+ await assert.rejects(() => discover({}), /endpoint is required/);
+});
diff --git a/x402-modal-sdk/types/index.d.ts b/x402-modal-sdk/types/index.d.ts
index 773b91ae3..5ac0be316 100644
--- a/x402-modal-sdk/types/index.d.ts
+++ b/x402-modal-sdk/types/index.d.ts
@@ -112,6 +112,28 @@ export function getConfig(): Required<X402Config>;
*/
export function pay(opts: PayOptions): Promise<PayResult>;
+/** What {@link discover} needs to probe an endpoint: everything but the UI options. */
+export type DiscoverOptions = Pick<PayOptions, 'endpoint' | 'method' | 'body' | 'headers'>;
+
+/** An x402 v2 PaymentRequired envelope, with `accepts[]` normalized. */
+export interface PaymentChallenge {
+ x402Version?: number;
+ error?: string;
+ resource?: { url?: string; description?: string; mimeType?: string };
+ accepts: Array<Record<string, unknown> & { network: NetworkId; amount?: string }>;
+ extensions?: Record<string, unknown>;
+ [k: string]: unknown;
+}
+
+/**
+ * Probe an x402 endpoint and return its parsed payment challenge without
+ * opening any UI. Step 1 of {@link pay}, exported on its own: it touches no DOM
+ * and no wallet, so a server, CLI, or agent can price a paid call before
+ * deciding to pay it. Rejects when the endpoint answers with no readable
+ * challenge (including a free `200`).
+ */
+export function discover(opts: DiscoverOptions): Promise<PaymentChallenge>;
+
/** Scan the document and bind every `[data-x402-endpoint]` element. Idempotent. */
export function init(): void;
@@ -136,6 +158,7 @@ declare global {
interface Window {
X402?: {
pay: typeof pay;
+ discover: typeof discover;
init: typeof init;
configure: typeof configure;
version: string;
diff --git a/x402-payment-modal/docs/api-reference.md b/x402-payment-modal/docs/api-reference.md
index 6db78fb49..0c199cfca 100644
--- a/x402-payment-modal/docs/api-reference.md
+++ b/x402-payment-modal/docs/api-reference.md
@@ -136,7 +136,7 @@ The package version string.
```js
import { version } from '@three-ws/x402-payment-modal';
-console.log(version); // "1.1.0"
+console.log(version); // matches the `version` field in package.json
```
---
diff --git a/x402-payment-modal/src/index.js b/x402-payment-modal/src/index.js
index 860a24c6b..abef448ae 100644
--- a/x402-payment-modal/src/index.js
+++ b/x402-payment-modal/src/index.js
@@ -37,7 +37,10 @@
// is configurable via `configure({...})` or `data-*` attributes on the script
// tag — see CONFIG / configure() below and docs/api-reference.md.
-const VERSION = '1.2.0';
+const VERSION = '1.2.1';
+
+/** Library version. Kept in lockstep with package.json (see test/client.test.js). */
+export const version = VERSION;
// ─────────────────────────────────────────────────────────── configuration ───
// All host-specific knobs live here so the modal runs unchanged on any site.
@@ -124,21 +127,22 @@ function checkoutBase() {
// an endpoint re-enter it by signing a challenge instead of paying again. The
// server advertises support by including `extensions['sign-in-with-x']` in the
// 402 body; clients submit signed proofs via the `SIGN-IN-WITH-X` header. See
-// prompts/siwx/PLAN.md for the full architecture.
+// docs/siwx.md for the full architecture.
const SIWX_HEADER = 'SIGN-IN-WITH-X';
const SIWX_EXTENSION_KEY = 'sign-in-with-x';
const ORIGIN = (() => {
- // Resolve the origin that hosts this script — used as the API origin for
+ // Resolve the origin that hosts this script, used as the API origin for
// the prepare/encode helpers. Falls back to the merchant origin in same-
- // origin mode.
+ // origin mode, and to '' off-browser: importing this module during SSR (or
+ // in a test runner) must never throw, so every DOM/location read is guarded.
try {
const script = document.currentScript;
if (script?.src) return new URL(script.src).origin;
const found = document.querySelector('script[src*="/x402.js"]');
if (found?.src) return new URL(found.src).origin;
} catch (_) {}
- return location.origin;
+ return typeof location !== 'undefined' ? location.origin : '';
})();
// USDC EIP-3009 typed-data sig works against Base USDC at this address. The
diff --git a/x402-payment-modal/test/client.test.js b/x402-payment-modal/test/client.test.js
new file mode 100644
index 000000000..421893327
--- /dev/null
+++ b/x402-payment-modal/test/client.test.js
@@ -0,0 +1,171 @@
+// Core-path tests for the browser entry point (src/index.js) and the built
+// bundle it produces.
+//
+// Two layers:
+// 1. Off-browser import. The module is imported by bundlers and by SSR
+// frameworks (Next.js renders the React wrapper's tree on the server), so
+// `import`ing it outside a browser must not throw and must expose the
+// documented exports. Before 1.2.1 it threw `ReferenceError: location is
+// not defined` at module evaluation.
+// 2. Real browser. A real HTTP server answers a real x402 402 challenge,
+// Chromium loads the real bundle, and a real click drives the modal to the
+// price it read off the wire. No stubs, no fake wallet: the flow is
+// asserted up to the point where a wallet signature would be required.
+// Skipped (not failed) when Playwright is unavailable, so the package
+// still tests standalone.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { readFile } from 'node:fs/promises';
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { solanaAccept } from '../server/checkout.js';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const root = join(here, '..');
+const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
+
+// Clearly-synthetic placeholder address (valid base58, 32-44 chars).
+const ADDR = 'So11111111111111111111111111111111111111112';
+
+test('the client entry imports off-browser and exposes the documented API', async () => {
+ assert.equal(typeof globalThis.window, 'undefined', 'this test must run without a DOM');
+ const mod = await import('../src/index.js');
+ for (const name of ['pay', 'configure', 'init', 'version', 'USDC_MINT_SOLANA', 'THREE_MINT', 'KNOWN_SOLANA_TOKENS']) {
+ assert.ok(name in mod, `missing export: ${name}`);
+ }
+ assert.equal(typeof mod.pay, 'function');
+ assert.equal(typeof mod.configure, 'function');
+ assert.equal(typeof mod.init, 'function');
+});
+
+test('the exported version tracks package.json', async () => {
+ const { version } = await import('../src/index.js');
+ assert.equal(version, pkg.version);
+});
+
+test('configure shallow-merges nested config and returns the resolved config', async () => {
+ const { configure } = await import('../src/index.js');
+ const cfg = configure({ checkoutOrigin: 'https://pay.example.com', brand: { name: 'Example' } });
+ assert.equal(cfg.checkoutOrigin, 'https://pay.example.com');
+ assert.equal(cfg.brand.name, 'Example');
+ // The untouched half of `brand` survives the merge.
+ assert.equal(cfg.brand.url, 'https://three.ws');
+ // Restore the defaults for any later test in this process.
+ configure({ checkoutOrigin: null, brand: { name: 'three.ws', url: 'https://three.ws' } });
+});
+
+test('pay rejects without an endpoint', async () => {
+ const { pay } = await import('../src/index.js');
+ await assert.rejects(() => pay({}), /endpoint is required/);
+});
+
+test('the client and server agree on the well-known Solana mints', async () => {
+ const client = await import('../src/index.js');
+ const server = await import('../server/checkout.js');
+ assert.equal(client.THREE_MINT, server.THREE_MINT);
+ assert.equal(client.USDC_MINT_SOLANA, server.USDC_MINT_SOLANA);
+});
+
+// ── Real-browser core path ───────────────────────────────────────────────────
+
+async function loadChromium() {
+ try {
+ const { chromium } = await import('playwright');
+ return chromium;
+ } catch {
+ return null;
+ }
+}
+
+// Prefer the built bundle so this also proves the build output runs in a
+// browser; fall back to source when `npm run build` has not been run yet.
+function bundlePath() {
+ const min = join(root, 'dist/x402.min.js');
+ return existsSync(min) ? min : join(root, 'src/index.js');
+}
+
+const PAGE = `<!doctype html>
+<html><head><meta charset="utf-8"><title>x402 core path</title></head>
+<body>
+<button id="buy"
+ data-x402-endpoint="/api/paid/hello"
+ data-x402-merchant="Core Path"
+ data-x402-action="Say hello">Pay &amp; Run</button>
+<script type="module" src="/x402.js"></script>
+</body></html>`;
+
+test('a real 402 challenge drives the modal to its price in a browser', async (t) => {
+ const chromium = await loadChromium();
+ if (!chromium) return t.skip('playwright is not installed');
+
+ const bundle = await readFile(bundlePath(), 'utf8');
+ const challenge = {
+ x402Version: 2,
+ error: 'Payment required',
+ resource: { url: 'http://127.0.0.1/api/paid/hello', description: 'A friendly hello.', mimeType: 'application/json' },
+ accepts: [solanaAccept({ token: 'usdc', uiAmount: 0.25, payTo: ADDR, feePayer: ADDR, maxTimeoutSeconds: 60 })],
+ };
+
+ const server = createServer((req, res) => {
+ const url = new URL(req.url, 'http://127.0.0.1');
+ if (url.pathname === '/x402.js') {
+ res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' });
+ return res.end(bundle);
+ }
+ if (url.pathname === '/api/paid/hello') {
+ res.writeHead(402, { 'content-type': 'application/json' });
+ return res.end(JSON.stringify(challenge));
+ }
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
+ res.end(PAGE);
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const base = `http://127.0.0.1:${server.address().port}`;
+
+ const browser = await chromium.launch();
+ try {
+ const page = await browser.newPage();
+ const consoleErrors = [];
+ page.on('pageerror', (err) => consoleErrors.push(String(err)));
+ await page.goto(`${base}/`, { waitUntil: 'load' });
+
+ // The module exposes itself for inline scripts and auto-binds the button.
+ await page.waitForFunction(() => Boolean(window.X402));
+ const api = await page.evaluate(() => ({
+ version: window.X402.version,
+ keys: Object.keys(window.X402).sort(),
+ usdc: window.X402.tokens.USDC_MINT_SOLANA,
+ bound: document.getElementById('buy').dataset.x402Bound,
+ }));
+ assert.equal(api.version, pkg.version);
+ assert.deepEqual(api.keys, ['configure', 'init', 'pay', 'tokens', 'version']);
+ assert.equal(api.usdc, challenge.accepts[0].asset, 'the bundle disagrees with the server on the USDC mint');
+ assert.equal(api.bound, '1', 'the auto-binder did not bind the button');
+
+ // Click: the modal mounts, fetches the endpoint, and renders what the
+ // real 402 said. 0.25 USDC at 6 decimals is 250000 atomic units.
+ await page.click('#buy');
+ const dialog = page.locator('.x402-overlay [role="dialog"]');
+ await dialog.waitFor({ state: 'visible', timeout: 10_000 });
+ await page.waitForFunction(() => document.querySelector('[data-price]')?.textContent?.includes('0.25'), null, { timeout: 10_000 });
+
+ assert.match(await page.locator('[data-price]').innerText(), /0\.25/);
+ assert.match(await page.locator('[data-price]').innerText(), /USDC/);
+ assert.match(await page.locator('[data-network]').innerText(), /Solana/i);
+ assert.equal(await page.locator('[data-action]').innerText(), 'Say hello');
+ // textContent, not innerText: the header uppercases the merchant in CSS.
+ assert.equal(await page.locator('[data-merchant]').textContent(), 'Core Path');
+
+ // Esc closes the modal, which is how `pay()` reports a cancellation.
+ await page.keyboard.press('Escape');
+ await dialog.waitFor({ state: 'detached', timeout: 10_000 });
+
+ assert.deepEqual(consoleErrors, [], 'the page threw');
+ } finally {
+ await browser.close();
+ await new Promise((resolve) => server.close(resolve));
+ }
+});