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.

Restore package sources to prior state

qbdzac004307f8f8
diff --git a/packages/ibm-x402-mcp/CATALOG.md b/packages/ibm-x402-mcp/CATALOG.md
index 34dbab78a..48f68ef3e 100644
--- a/packages/ibm-x402-mcp/CATALOG.md
+++ b/packages/ibm-x402-mcp/CATALOG.md
@@ -1,38 +1,36 @@
# IBM Cloud / watsonx Orchestrate catalog listing
-A ready-to-paste template for listing this server in the IBM Cloud / watsonx Orchestrate
-MCP catalog. Replace the operator-specific fields (application name/id, support contacts,
-and — if you publish a hosted HTTP endpoint — the endpoint URL) with your own values.
-Keep the tool names, prices, and descriptions in sync with `server.json`, `README.md`,
-and the tool sources in `src/tools/`.
+Field values for the **MCP Server** entry: *x402 MCP - Pay-per-Use AI Agent Payments by three.ws*.
+Source of truth for the published listing — keep in sync with `server.json`, `README.md`, and the tool sources in `src/tools/`.
| Field | Value |
|---|---|
-| Name | `ibm-x402-mcp` |
-| Display name | `IBM Granite via x402 — Pay-per-Use AI over MCP` |
+| Name | `three-ws-x402-mcp` |
+| Display name | `x402 MCP - Pay-per-Use AI Agent Payments by three.ws` |
| Short description (tagline) | `Pay-per-call IBM Granite AI over MCP. x402 agentic payments let any AI agent call Granite chat, code, embeddings, document analysis, and time-series forecasting — settled per call in USDC on Solana, no IBM Cloud account required.` |
| Summary | `x402 pay-per-use IBM Granite AI — chat, code, embeddings, document analysis, and time-series forecasting. Pay USDC on Solana per call. No IBM Cloud account required.` |
-| Version | `1.1.0` |
-| Change log | `See repository releases` |
+| Version | `1.0.0` |
+| Change log | `Initial release` |
| Domain tags (max 3) | Software development · Data & analytics · Productivity |
| Language support | English (Granite 3 models also process German, Spanish, French, Portuguese, Japanese, Korean, Italian, Dutch, Chinese, Arabic, Czech) |
-| Application ID | `ibm-x402-mcp` (operator-defined) |
-| Application Name | your organization (operator-defined) |
-| Application icon | a square SVG/PNG you supply (<200kb) |
-| Transport | stdio (`npx @three-ws/ibm-x402-mcp`) · Streamable HTTP (remote) if you self-host one |
-| Server end-point URL | your hosted Streamable HTTP endpoint, if you publish one (see note below) |
+| Application ID | `three-ws-x402-mcp` |
+| Application Name | `three.ws` |
+| Application icon | `public/pwa-icon.svg` (square, <200kb) |
+| Transport | Streamable HTTP (remote) · stdio (`npx @three-ws/ibm-x402-mcp`) |
+| Server end-point URL | `https://three.ws/api/ibm-mcp` (Streamable HTTP, MCP 2025-06-18 — the 5 Granite tools; see note below) |
## Related links
- npm: https://www.npmjs.com/package/@three-ws/ibm-x402-mcp
-- Source: https://github.com/nirholas/ibm-x402-mcp
+- Source: https://github.com/nirholas/three.ws/tree/main/packages/ibm-x402-mcp
- MCP registry name: `io.github.nirholas/ibm-x402-mcp`
-- Issues / support: https://github.com/nirholas/ibm-x402-mcp/issues
+- Homepage: https://three.ws
+- Support: https://three.ws/support
- x402 protocol: https://x402.org
## Description
-This MCP server turns IBM Granite foundation models into pay-per-use tools any AI agent or MCP client (Claude Desktop, Claude Code, Cursor, watsonx Orchestrate) can call. Every call is settled in USDC on Solana via the open x402 payment protocol — end users need no IBM Cloud account and no subscription. The server operator supplies IBM watsonx.ai credentials and a receiving wallet; callers pay only for what they use. When a tool is called without payment, the server returns an x402 PaymentRequired envelope quoting the exact USDC price; x402-capable clients pay and retry automatically.
+three.ws x402 MCP turns IBM Granite foundation models into pay-per-use tools any AI agent or MCP client (Claude Desktop, Claude Code, Cursor, watsonx Orchestrate) can call. Every call is settled in USDC on Solana via the open x402 payment protocol — end users need no IBM Cloud account and no subscription. The server operator supplies IBM watsonx.ai credentials and a receiving wallet; callers pay only for what they use. When a tool is called without payment, the server returns an x402 PaymentRequired envelope quoting the exact USDC price; x402-capable clients pay and retry automatically.
Six tools — one free entry point plus five independently-priced inference tools:
@@ -48,7 +46,7 @@ Six tools — one free entry point plus five independently-priced inference tool
5. **ibm_granite_forecast — Time-series forecasting ($0.05/call).** Zero-shot numeric forecasting via IBM Granite TTM (Tiny Time Mixer) — no training required. Provide 64–1024 ISO-8601 timestamps and aligned numeric values at a uniform cadence; receive a forecast horizon as timestamped points. Parameters: timestamps, values (equal length), freq (pandas-style, e.g. 1h/1D/1W), optional prediction_length (1–96), optional label. Use for revenue, traffic, demand, sensor, energy, and financial series.
-Models: IBM Granite 3 8B Instruct (chat/code/analyze), IBM Granite Embedding 278M Multilingual (embed), and IBM Granite TTM (forecast) — all served by IBM watsonx.ai, region-configurable (us-south default; eu-de, eu-gb, jp-tok, au-syd, ca-tor). Open source (Apache-2.0). Independent project integrating IBM Granite via watsonx.ai; not an IBM product. Granite, watsonx, and watsonx.ai are trademarks of IBM.
+Models: IBM Granite 3 8B Instruct (chat/code/analyze), IBM Granite Embedding 278M Multilingual (embed), and IBM Granite TTM (forecast) — all served by IBM watsonx.ai, region-configurable (us-south default; eu-de, eu-gb, jp-tok, au-syd, ca-tor). Open source (Apache-2.0) by three.ws. Independent project integrating IBM Granite via watsonx.ai; not an IBM product. Granite, watsonx, and watsonx.ai are trademarks of IBM.
## Pricing tab
@@ -74,18 +72,20 @@ Per-call prices (source of truth — keep in sync with Description and `src/tool
| Field | Value |
|---|---|
-| Support provider | `Third party` (the operator/maintainer publishing the listing) |
+| Support provider | `Third party` (three.ws — single accountable maintainer with private email + security triage) |
| Statement of support | See below — keep in sync with `SUPPORT.md` |
| Support languages | English |
-**Statement of support** (adapt the contact links to your deployment, then paste verbatim):
+**Statement of support** (paste verbatim into the required field):
-> x402 MCP for IBM Granite is an independent, open-source product. It integrates IBM Granite via watsonx.ai but is not an IBM product and is not supported by IBM.
+> x402 MCP (three-ws-x402-mcp) is an independent, open-source product built and maintained by three.ws. It integrates IBM Granite via watsonx.ai but is not an IBM product and is not supported by IBM.
>
> Where to get help:
-> • GitHub Issues — bugs, crashes, unexpected tool output, feature requests: https://github.com/nirholas/ibm-x402-mcp/issues
-> • GitHub Discussions — setup and integration "how do I…" questions: https://github.com/nirholas/ibm-x402-mcp/discussions
-> • Security — report vulnerabilities privately via a GitHub security advisory; please do not open a public issue: https://github.com/nirholas/ibm-x402-mcp/security
+> • GitHub Issues — bugs, crashes, unexpected tool output, feature requests: https://github.com/nirholas/three.ws/issues/new
+> • GitHub Discussions — setup and integration "how do I…" questions: https://github.com/nirholas/three.ws/discussions
+> • Email — private or account-specific issues: [email protected]
+> • Security — report vulnerabilities privately; please do not open a public issue: [email protected]
+> • All channels in one place: https://three.ws/support
>
> What we support:
> • Installing, configuring, and running the MCP server.
@@ -98,16 +98,16 @@ Per-call prices (source of truth — keep in sync with Description and `src/tool
>
> Granite, watsonx, and watsonx.ai are trademarks of IBM.
-## Note on transports and the endpoint URL
+## Note on the endpoint URL
-The five Granite tools ship over stdio out of the box, and can also be exposed over a Streamable HTTP endpoint if you self-host one:
+The five Granite tools ship over two transports backed by one tool suite:
-- **stdio** — the `@three-ws/ibm-x402-mcp` npm package (`npx @three-ws/ibm-x402-mcp`), for local MCP hosts (Claude Desktop, Claude Code, Cursor). Payment: per-call USDC on Solana via the x402 envelope. This is all most catalog listings need.
-- **Streamable HTTP (remote)** — the watsonx Orchestrate catalog requires a remote endpoint URL. If you run a hosted deployment, wrap this server's tool suite behind your own MCP 2025-06-18 HTTP endpoint and list that URL here. Keep tool schemas, prices, and output shapes identical to the npm package.
+- **stdio** — the `@three-ws/ibm-x402-mcp` npm package (`npx @three-ws/ibm-x402-mcp`), for local MCP hosts (Claude Desktop, Claude Code, Cursor). Payment: per-call USDC on Solana via the x402 envelope.
+- **Streamable HTTP (remote)** — `https://three.ws/api/ibm-mcp` (MCP 2025-06-18), the endpoint the watsonx Orchestrate catalog requires. Source: [`api/ibm-mcp.js`](https://github.com/nirholas/three.ws/blob/main/api/ibm-mcp.js) + [`api/_mcpibm/`](https://github.com/nirholas/three.ws/tree/main/api/_mcpibm). It reuses the platform's server-side watsonx client (`api/_lib/watsonx.js`, `api/_lib/watsonx-forecast.js`) and the standard x402 settlement infra (`api/_lib/x402-spec.js`), and is registered as `io.github.nirholas/ibm-x402-mcp-remote` (see `server-ibm.json`). Tool schemas, prices, and output shapes are kept identical to the npm package.
-Because watsonx Orchestrate is not x402-capable, a hosted endpoint typically runs dual-mode:
+**Access on the remote endpoint** is dual-mode, which resolves the Orchestrate constraint (watsonx Orchestrate is not x402-capable):
-- **Anonymous callers pay per call** in USDC. An unpaid `tools/call` returns a 402 quoting the exact per-tool price (chat $0.02, code $0.025, embed $0.005, analyze $0.04, forecast $0.05); x402-capable clients pay and retry automatically. Settlement runs after the tool succeeds.
-- **Authenticated principals (Bearer / OAuth) call without per-call payment** — the operator-funded path. A watsonx Orchestrate connection supplies a Bearer credential, so the tools are effectively included-in-connection rather than billed per USDC call.
+- **Anonymous callers pay per call** in USDC. An unpaid `tools/call` returns a 402 quoting the exact per-tool price (chat $0.02, code $0.025, embed $0.005, analyze $0.04, forecast $0.05), advertised on Base and Solana mainnet; x402-capable clients pay and retry automatically. Settlement runs after the tool succeeds.
+- **Authenticated three.ws principals (Bearer / OAuth) call without per-call payment** — the operator-funded path. A watsonx Orchestrate connection supplies a Bearer credential here, so the tools are effectively included-in-connection rather than billed per USDC call.
-The operator funds inference by setting `WATSONX_API_KEY` + `WATSONX_PROJECT_ID` (and the `MCP_SVM_PAYMENT_ADDRESS` receiving wallet) in the deployment environment; end users still need no IBM Cloud account.
+The operator funds inference by setting `WATSONX_API_KEY` + `WATSONX_PROJECT_ID` (and the platform's `X402_PAY_TO_*` receiving wallets) in the deployment environment; end users still need no IBM Cloud account.
diff --git a/packages/ibm-x402-mcp/README.md b/packages/ibm-x402-mcp/README.md
index e0477c777..485556a5c 100644
--- a/packages/ibm-x402-mcp/README.md
+++ b/packages/ibm-x402-mcp/README.md
@@ -1,3 +1,7 @@
+<p align="center">
+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" alt="three.ws" width="88" height="88"></a>
+</p>
+
<h1 align="center">@three-ws/ibm-x402-mcp</h1>
<p align="center"><strong>Pay-per-use IBM Granite AI over MCP — chat, code, embeddings, analysis, and forecasting, billed in USDC on Solana. No IBM account required.</strong></p>
@@ -8,6 +12,7 @@
<img alt="license" src="https://img.shields.io/npm/l/@three-ws/ibm-x402-mcp?color=3b82f6">
<img alt="node" src="https://img.shields.io/node/v/@three-ws/ibm-x402-mcp?color=339933&logo=node.js">
<a href="https://registry.modelcontextprotocol.io/?q=io.github.nirholas"><img alt="MCP Registry" src="https://img.shields.io/badge/MCP%20Registry-io.github.nirholas%2Fibm--x402--mcp-6e56cf"></a>
+ <a href="https://three.ws"><img alt="three.ws" src="https://img.shields.io/badge/built%20by-three.ws-000"></a>
</p>
<p align="center">
@@ -15,14 +20,15 @@
<a href="#quick-start">Quick start</a> ·
<a href="#tools">Tools</a> ·
<a href="#payment-flow">Payment flow</a> ·
- <a href="#requirements">Requirements</a>
+ <a href="#requirements">Requirements</a> ·
+ <a href="https://three.ws">three.ws</a>
</p>
---
> A [Model Context Protocol](https://modelcontextprotocol.io) server that exposes IBM Granite foundation models as pay-per-use tools via the [x402](https://x402.org) payment protocol. End users pay **USDC on Solana** per call — no IBM Cloud account of their own. The server operator supplies IBM credentials (`WATSONX_*`) and a receiving Solana wallet (`MCP_SVM_PAYMENT_ADDRESS`); callers supply only USDC. One free tool (`ibm_granite_getting_started`) explains prices and the flow before any payment.
-> Community-built and not affiliated with IBM.
+> Built by [three.ws](https://three.ws). Community-built and not affiliated with IBM.
## How it works
@@ -180,17 +186,27 @@ ibm-x402-mcp (stdio MCP server)
| `WATSONX_URL` | no | `https://us-south.ml.cloud.ibm.com` |
| `WATSONX_MODEL_ID` | no | `ibm/granite-3-8b-instruct` |
| `WATSONX_EMBED_MODEL_ID` | no | `ibm/granite-embedding-278m-multilingual` |
-| `X402_FEE_PAYER_SOLANA` | no | unset (facilitator sponsors fees) |
+| `X402_FEE_PAYER_SOLANA` | no | three.ws fee payer |
| `X402_FACILITATOR_URL` | no | `https://facilitator.payai.network` |
-The free `ibm_granite_getting_started` tool surfaces project links (homepage, source, support). These default to this package's repository and are overridable via `IBM_X402_MCP_HOMEPAGE_URL`, `IBM_X402_MCP_SOURCE_URL`, and `IBM_X402_MCP_SUPPORT_URL` if you run a branded deployment.
-
Regional hosts: `us-south`, `eu-de`, `eu-gb`, `jp-tok`, `au-syd`, `ca-tor` — e.g. `https://eu-de.ml.cloud.ibm.com`.
+## Related
+
+- [`@three-ws/ibm-watsonx-mcp`](https://www.npmjs.com/package/@three-ws/ibm-watsonx-mcp) — the same IBM Granite tools driven by your own IBM Cloud credentials (no x402, no per-call payment).
+
## Links
-- npm: https://www.npmjs.com/package/@three-ws/ibm-x402-mcp
-- Source & issues: https://github.com/nirholas/ibm-x402-mcp
-- MCP registry name: `io.github.nirholas/ibm-x402-mcp`
-- x402 protocol: https://x402.org
+- Homepage: https://three.ws
+- Changelog: https://three.ws/changelog
+- Issues: https://github.com/nirholas/three.ws/issues
- License: Apache-2.0 — see [LICENSE](./LICENSE)
+
+---
+
+<p align="center">
+ <sub>
+ Part of the <a href="https://three.ws">three.ws</a> SDK suite — 3D AI agents, on-chain identity, and agent payments.<br/>
+ <a href="https://three.ws">Website</a> · <a href="https://three.ws/changelog">Changelog</a> · <a href="https://github.com/nirholas/three.ws">GitHub</a>
+ </sub>
+</p>
diff --git a/packages/ibm-x402-mcp/SUPPORT.md b/packages/ibm-x402-mcp/SUPPORT.md
index cedbbe80b..6f3080569 100644
--- a/packages/ibm-x402-mcp/SUPPORT.md
+++ b/packages/ibm-x402-mcp/SUPPORT.md
@@ -1,16 +1,18 @@
# Support
-Support for **`@three-ws/ibm-x402-mcp`** — the x402 pay-per-use MCP server for IBM Granite — is community-maintained on GitHub. This document is the single source of truth for how to get help, where to report problems, and what to expect back.
+Support for **`@three-ws/ibm-x402-mcp`** — the x402 pay-per-use MCP server for IBM Granite — is provided by **three.ws**. This document is the single source of truth for how to get help, where to report problems, and what to expect back.
## Where to get help
| Channel | Use it for | Link |
|---|---|---|
-| **GitHub Issues** | Bugs, crashes, unexpected tool output, feature requests | https://github.com/nirholas/ibm-x402-mcp/issues |
-| **GitHub Discussions** | Setup questions, integration help, "how do I…" | https://github.com/nirholas/ibm-x402-mcp/discussions |
-| **Security** | Vulnerabilities — please open a [private security advisory](https://github.com/nirholas/ibm-x402-mcp/security/advisories/new) rather than a public issue | https://github.com/nirholas/ibm-x402-mcp/security |
+| **GitHub Issues** | Bugs, crashes, unexpected tool output, feature requests | https://github.com/nirholas/three.ws/issues/new |
+| **GitHub Discussions** | Setup questions, integration help, "how do I…" | https://github.com/nirholas/three.ws/discussions |
+| **Email** | Private or account-specific support | [email protected] |
+| **Security** | Vulnerabilities — please do **not** open a public issue | [email protected] |
+| **Support page** | All channels in one place | https://three.ws/support |
-For anything that exposes a key, wallet, or transaction signature, use the private security advisory rather than a public issue.
+For anything that exposes a key, wallet, or transaction signature, use email rather than a public issue.
## Before you open an issue
@@ -38,7 +40,7 @@ A few minutes here usually gets you an answer in one round-trip instead of three
This server settles each call in **USDC on Solana** via the [x402 protocol](https://x402.org) through the [PayAI facilitator](https://facilitator.payai.network). Payment issues split into two layers:
-- **Wallet / settlement** (you got charged but no result, or a `402` loop): include the Solana transaction signature (public) and the tool name. Use a [private security advisory](https://github.com/nirholas/ibm-x402-mcp/security/advisories/new) if the report contains anything sensitive.
+- **Wallet / settlement** (you got charged but no result, or a `402` loop): include the Solana transaction signature (public) and the tool name. Email these to [email protected] rather than posting publicly.
- **IBM inference** (the payment cleared but watsonx.ai errored): this is usually a credential, region, or model-id problem — see the README configuration table.
End users calling the tools never need an IBM Cloud account; only the **server operator** supplies `WATSONX_*` credentials and a receiving Solana wallet.
@@ -52,7 +54,7 @@ End users calling the tools never need an IBM Cloud account; only the **server o
## Response expectations
-This is a community-supported open-source project. We triage GitHub issues on a best-effort basis, typically within a few business days. Security advisories are prioritized.
+This is a community-supported open-source project maintained by three.ws. We triage GitHub issues and support email on a best-effort basis, typically within a few business days. Security reports sent to [email protected] are prioritized.
## Languages
@@ -60,4 +62,4 @@ Support is provided in **English**.
---
-Apache-2.0. This is an independent project that integrates IBM Granite via watsonx.ai; it is not an IBM product and is not supported by IBM. *Granite*, *watsonx*, and *watsonx.ai* are trademarks of IBM.
+Built by [three.ws](https://three.ws) · Apache-2.0. This is an independent project that integrates IBM Granite via watsonx.ai; it is not an IBM product and is not supported by IBM. *Granite*, *watsonx*, and *watsonx.ai* are trademarks of IBM.
diff --git a/packages/ibm-x402-mcp/package.json b/packages/ibm-x402-mcp/package.json
index 434cf1c1a..4663b7989 100644
--- a/packages/ibm-x402-mcp/package.json
+++ b/packages/ibm-x402-mcp/package.json
@@ -5,14 +5,15 @@
"type": "module",
"author": "nirholas",
"license": "Apache-2.0",
- "homepage": "https://github.com/nirholas/ibm-x402-mcp",
+ "homepage": "https://three.ws",
"mcpName": "io.github.nirholas/ibm-x402-mcp",
"repository": {
"type": "git",
- "url": "git+https://github.com/nirholas/ibm-x402-mcp.git"
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "packages/ibm-x402-mcp"
},
"bugs": {
- "url": "https://github.com/nirholas/ibm-x402-mcp/issues"
+ "url": "https://github.com/nirholas/three.ws/issues"
},
"keywords": [
"mcp",
@@ -26,6 +27,7 @@
"solana",
"pay-per-use",
"ai-agent",
+ "three.ws",
"foundation-models",
"embeddings",
"time-series"
diff --git a/packages/ibm-x402-mcp/server.json b/packages/ibm-x402-mcp/server.json
index b56bf428d..6b66c5643 100644
--- a/packages/ibm-x402-mcp/server.json
+++ b/packages/ibm-x402-mcp/server.json
@@ -3,10 +3,20 @@
"name": "io.github.nirholas/ibm-x402-mcp",
"title": "IBM Granite via x402",
"description": "x402 pay-per-use IBM Granite AI: chat, code, embeddings, analysis, forecasting. Pay USDC per call.",
- "websiteUrl": "https://github.com/nirholas/ibm-x402-mcp",
+ "websiteUrl": "https://three.ws",
+ "icons": [
+ {
+ "src": "https://three.ws/three-ws-mcp-icon.svg",
+ "mimeType": "image/svg+xml",
+ "sizes": [
+ "any"
+ ]
+ }
+ ],
"repository": {
- "url": "https://github.com/nirholas/ibm-x402-mcp",
- "source": "github"
+ "url": "https://github.com/nirholas/three.ws",
+ "source": "github",
+ "subfolder": "packages/ibm-x402-mcp"
},
"version": "1.1.0",
"packages": [
@@ -65,7 +75,7 @@
},
{
"name": "X402_FEE_PAYER_SOLANA",
- "description": "Optional Solana account that sponsors transaction fees for x402 payments. Leave unset to let the facilitator sponsor fees.",
+ "description": "Solana account that sponsors transaction fees for x402 payments. Defaults to the three.ws fee payer.",
"isRequired": false,
"format": "string"
},
diff --git a/packages/ibm-x402-mcp/src/index.js b/packages/ibm-x402-mcp/src/index.js
index 8e58308a0..34bca3681 100755
--- a/packages/ibm-x402-mcp/src/index.js
+++ b/packages/ibm-x402-mcp/src/index.js
@@ -1,7 +1,7 @@
#!/usr/bin/env node
// @three-ws/ibm-x402-mcp — stdio MCP server: IBM Granite AI tools gated by x402 USDC payments.
//
-// An x402-enabled MCP server for IBM Granite foundation models.
+// The world's first x402-enabled MCP server on IBM Cloud.
// End users pay USDC on Solana per call — no IBM Cloud account needed.
// Server operators supply WATSONX_* credentials and MCP_SVM_PAYMENT_ADDRESS.
//
@@ -36,7 +36,7 @@ const require = createRequire(import.meta.url);
const SERVER_VERSION = require('../package.json').version;
const SERVER_INSTRUCTIONS =
- 'x402 pay-per-use IBM Granite AI tools over MCP. Each tool lists its USDC price. ' +
+ 'x402 pay-per-use IBM Granite AI tools from three.ws. Each tool lists its USDC price. ' +
'New here? Call ibm_granite_getting_started (free, no payment) for an overview, prices, and the payment flow. ' +
'Tool calls without an x402 payment payload in _meta return a PaymentRequired envelope ' +
'(v2 MCP transport spec). ' +
diff --git a/packages/ibm-x402-mcp/src/payments.js b/packages/ibm-x402-mcp/src/payments.js
index 52ef11740..3a2c7e818 100644
--- a/packages/ibm-x402-mcp/src/payments.js
+++ b/packages/ibm-x402-mcp/src/payments.js
@@ -11,7 +11,7 @@
// MCP_SVM_PAYMENT_ADDRESS — Solana wallet that receives USDC (required)
// X402_PAY_TO_SOLANA — fallback alias
// X402_PAY_TO — fallback alias
-// X402_FEE_PAYER_SOLANA — Solana fee payer for settlement (optional; unset lets the facilitator sponsor fees)
+// X402_FEE_PAYER_SOLANA — transaction fee payer (optional, defaults to three.ws fee payer)
// X402_FACILITATOR_URL — PayAI facilitator URL (optional)
// X402_FACILITATOR_TOKEN — Bearer token for facilitator (optional)
// X402_ASSET_MINT_SOLANA — USDC mint override (optional)
@@ -43,11 +43,8 @@ export function assertPaymentEnv() {
requireSvmPayTo();
}
-// Optional Solana fee payer. When unset the facilitator sponsors transaction
-// fees, so the server has no vendor-specific default — operators that run their
-// own sponsor set X402_FEE_PAYER_SOLANA to their account.
function svmFeePayer() {
- return env('X402_FEE_PAYER_SOLANA');
+ return env('X402_FEE_PAYER_SOLANA', '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4');
}
function buildFacilitator() {
@@ -85,7 +82,6 @@ export function getLastFacilitatorInitError() {
}
async function buildAccepts({ resourceServer, priceUsd, resourceUrl }) {
- const feePayer = svmFeePayer();
return resourceServer.buildPaymentRequirementsFromOptions(
[
{
@@ -98,7 +94,7 @@ async function buildAccepts({ resourceServer, priceUsd, resourceUrl }) {
name: 'USDC',
decimals: 6,
asset: env('X402_ASSET_MINT_SOLANA', DEFAULT_SOLANA_USDC),
- ...(feePayer ? { feePayer } : {}),
+ feePayer: svmFeePayer(),
},
},
],
diff --git a/packages/ibm-x402-mcp/src/tools/getting-started.js b/packages/ibm-x402-mcp/src/tools/getting-started.js
index 6a8160a20..2808c596f 100644
--- a/packages/ibm-x402-mcp/src/tools/getting-started.js
+++ b/packages/ibm-x402-mcp/src/tools/getting-started.js
@@ -83,20 +83,11 @@ const SETUP = {
},
};
-// Project links. Defaults point at the standalone repo so the server is usable
-// with no operator-specific branding; each is overridable via env so an operator
-// can surface their own homepage/support without forking.
-const env = (key, fallback) => {
- const v = process.env[key];
- return v && v.trim() ? v.trim() : fallback;
-};
-
-const REPO_URL = 'https://github.com/nirholas/ibm-x402-mcp';
const LINKS = {
- homepage: env('IBM_X402_MCP_HOMEPAGE_URL', REPO_URL),
+ homepage: 'https://three.ws',
npm: 'https://www.npmjs.com/package/@three-ws/ibm-x402-mcp',
- source: env('IBM_X402_MCP_SOURCE_URL', REPO_URL),
- support: env('IBM_X402_MCP_SUPPORT_URL', `${REPO_URL}/issues`),
+ source: 'https://github.com/nirholas/three.ws/tree/main/packages/ibm-x402-mcp',
+ support: 'https://three.ws/support',
x402: 'https://x402.org',
};
diff --git a/packages/vscode-x402/CHANGELOG.md b/packages/vscode-x402/CHANGELOG.md
index f66bf43bd..16272e25c 100644
--- a/packages/vscode-x402/CHANGELOG.md
+++ b/packages/vscode-x402/CHANGELOG.md
@@ -4,13 +4,9 @@
Initial release.
-- Bazaar sidebar with live discovery, filters, and full-text search against any
- configurable bazaar discovery API (`x402.bazaarUrl`). Empty by default;
- discovery is optional.
-- Inspect command: decode any endpoint's 402 payment challenge — no bazaar or
- account required.
-- Pay & call any paid x402 endpoint with USDC, with a spending cap, pre-payment
- confirmation, and inline settlement receipts. No bazaar or account required.
+- Bazaar sidebar with live discovery, filters, and full-text search.
+- Inspect command: decode any endpoint's 402 payment challenge.
+- Pay & call paid x402 endpoints with USDC via `@three-ws/x402-fetch`, with a
+ spending cap, pre-payment confirmation, and inline settlement receipts.
- Secure EVM wallet key storage in VS Code SecretStorage; wallet status bar.
-- Scaffold a self-contained paid endpoint using the standard `x402-express`
- paywall middleware.
+- Scaffold a paid endpoint following the repo's `paidEndpoint()` pattern.
diff --git a/packages/vscode-x402/README.md b/packages/vscode-x402/README.md
index c8c60ef52..7b0769268 100644
--- a/packages/vscode-x402/README.md
+++ b/packages/vscode-x402/README.md
@@ -1,86 +1,57 @@
-# x402 — Bazaar & Pay for VS Code
+# three.ws — x402 for VS Code
-Browse any [x402](https://x402.org) bazaar, decode `402 Payment Required`
+Browse the [x402](https://three.ws/x402.md) bazaar, decode `402 Payment Required`
challenges, and pay-per-call paid APIs and MCP tools with USDC — without leaving
-your editor.
-
-x402 is a protocol for developers and agents, not end users — so this is
-genuinely editor-native: the people wiring up paid endpoints and calling them
-live in VS Code.
-
-## What it does without any setup
-
-You do **not** need an account, a bazaar, or any service-specific configuration
-to use the core features against an arbitrary endpoint:
-
-- **Inspect an endpoint** — run **x402: Inspect Endpoint** and paste any URL.
- It decodes the 402 challenge: every accepted network, asset, scheme, price (in
- USD), and `payTo`, flagging the one your wallet can actually satisfy.
-- **Pay & call** — run **x402: Pay & Call Endpoint** with any URL. The exact USD
- amount is shown and confirmed before signing; a spending cap blocks anything
- above your limit. The response body and on-chain settlement receipt (tx hash)
- are rendered inline.
-
-Both paths work against **any** x402-compatible endpoint. The only requirement
-for paying is a funded EVM wallet key (see below).
-
-## Optional: browse a bazaar
-
-To populate the **x402 Bazaar** sidebar, point the extension at a discovery API
-by setting **`x402.bazaarUrl`** (run **x402: Set Bazaar Discovery URL**). The
-extension calls `<bazaarUrl>/api/bazaar/list` and `<bazaarUrl>/api/bazaar/search`
-and renders the merged, normalised results. Filter by type, price, and tag, or
-full-text search. Leave the setting empty to disable discovery — inspect/pay
-still work.
-
-Any service that exposes that discovery shape works. For example,
-`https://three.ws` is a public bazaar you can use as the value.
-
-## Scaffold a paid endpoint
-
-Run **x402: Scaffold a Paid Endpoint** to generate a self-contained Express
-server that puts an x402 paywall in front of a route using the standard
-[`x402-express`](https://www.npmjs.com/package/x402-express) middleware:
-
-```bash
-npm i express x402-express
-PAY_TO=0xYourReceivingAddress node summarize.js
-```
-
-The handler runs only after the buyer's USDC payment settles, and works with any
-x402 client — including this extension's **Pay & call**.
-
-## Setup (for paying)
+your editor. Powered by [three.ws](https://three.ws).
+
+x402 is a protocol for developers and agents, not end users — so unlike a 3D
+viewer, this is genuinely editor-native: the people wiring up paid endpoints and
+calling them live in VS Code.
+
+## Features
+
+- **Bazaar sidebar** — live list of paid x402 HTTP APIs and MCP tools, merged
+ across every facilitator via the three.ws discovery proxy
+ (`/api/bazaar/list`, `/api/bazaar/search`). Filter by type, price, and tag;
+ full-text search.
+- **Inspect an endpoint** — paste any URL and decode its 402 challenge: every
+ accepted network, asset, scheme, price (in USD), and `payTo`, with the one
+ this wallet can actually satisfy flagged.
+- **Pay & call** — make a real paid request with
+ [`@three-ws/x402-fetch`](../x402-fetch). The exact USD amount is shown and
+ confirmed before signing; a spending cap blocks anything above your limit.
+ The response body and on-chain settlement receipt (tx hash) are rendered
+ inline.
+- **Secure wallet** — your EVM private key lives only in VS Code SecretStorage
+ (the OS keychain). Never in settings, never on disk in plaintext. The status
+ bar shows the derived address.
+- **Scaffold a paid endpoint** — generate a working `api/x402/<slug>.js` that
+ follows the repo's canonical `paidEndpoint()` pattern, wired end-to-end from
+ the first deploy.
+
+## Setup
1. Install the extension and open the **x402 Bazaar** view in the activity bar.
2. Run **x402: Set Wallet Key** and paste a funded Base USDC private key
(`0x` + 64 hex). It is stored in your OS keychain.
-3. Inspect or pay any endpoint, or set `x402.bazaarUrl` and browse a bazaar.
+3. Browse or search the bazaar, open a service, and **Pay & call**.
## Settings
| Setting | Default | Purpose |
|---|---|---|
-| `x402.bazaarUrl` | `""` | Base URL of a bazaar discovery API. Empty disables discovery. |
-| `x402.maxPaymentUsd` | `0.10` | Per-request spending cap, in USD. |
-| `x402.confirmEachPayment` | `true` | Confirm the exact amount before signing. |
-| `x402.network` | `eip155:8453` | Preferred CAIP-2 network (Base mainnet). |
-| `x402.filters` | `{ "type": "http" }` | Default bazaar filters. |
+| `threewsX402.origin` | `https://three.ws` | Host of the bazaar discovery API. |
+| `threewsX402.maxPaymentUsd` | `0.10` | Per-request spending cap, in USD. |
+| `threewsX402.confirmEachPayment` | `true` | Confirm the exact amount before signing. |
+| `threewsX402.network` | `eip155:8453` | Preferred CAIP-2 network (Base mainnet). |
+| `threewsX402.filters` | `{ "type": "http" }` | Default bazaar filters. |
## How payment works
-The bundled wrapper signs a USDC **EIP-3009** `transferWithAuthorization` and
-retries the request with the `X-PAYMENT` proof. The merchant verifies/settles
-on-chain and returns the work plus a settlement receipt. Services that only
-accept assets this EVM signer can't satisfy (e.g. Solana-only) still appear when
-browsing a bazaar, but are flagged as not payable here. USDC on an EVM network
-is the default and best-supported asset.
-
-## Security
-
-Your EVM private key lives only in VS Code SecretStorage (the OS keychain) —
-never in settings, never on disk in plaintext. The status bar shows the derived
-address.
+The wrapper signs a USDC-on-Base **EIP-3009** `transferWithAuthorization` and
+retries the request with the `X-PAYMENT` proof. The merchant settles on-chain
+and returns the work plus a settlement receipt. Solana-only services appear in
+the bazaar but are flagged as not payable by this EVM signer.
## Development
@@ -92,4 +63,4 @@ npm run watch # rebuild on change
Press <kbd>F5</kbd> in VS Code to launch an Extension Development Host.
-Apache-2.0.
+Apache-2.0 · part of the [three.ws](https://three.ws) monorepo.
diff --git a/packages/vscode-x402/build.mjs b/packages/vscode-x402/build.mjs
index 672d2bfe4..5ed24465b 100644
--- a/packages/vscode-x402/build.mjs
+++ b/packages/vscode-x402/build.mjs
@@ -1,4 +1,4 @@
-// Bundle the extension (and the bundled x402-fetch payment source) into a
+// Bundle the extension (and the bundled @three-ws/x402-fetch source) into a
// single CJS file VS Code can require. `vscode` is provided by the host and must
// stay external.
import esbuild from 'esbuild';
diff --git a/packages/vscode-x402/package.json b/packages/vscode-x402/package.json
index bfcba2a3b..1ce25a35d 100644
--- a/packages/vscode-x402/package.json
+++ b/packages/vscode-x402/package.json
@@ -1,11 +1,11 @@
{
"name": "@three-ws/vscode-x402",
- "displayName": "x402 — Bazaar & Pay",
- "description": "Browse any x402 bazaar, decode 402 payment challenges, and pay-per-call paid APIs and MCP tools with USDC — without leaving VS Code.",
+ "displayName": "three.ws — x402",
+ "description": "Browse the x402 bazaar, decode 402 payment challenges, and pay-per-call paid APIs with USDC — without leaving VS Code. Powered by three.ws.",
"version": "0.1.0",
"publisher": "three-ws",
"license": "Apache-2.0",
- "homepage": "https://github.com/nirholas/three.ws/tree/main/packages/vscode-x402",
+ "homepage": "https://three.ws",
"repository": {
"type": "git",
"url": "git+https://github.com/nirholas/three.ws.git",
@@ -36,16 +36,16 @@
"viewsContainers": {
"activitybar": [
{
- "id": "x402Bazaar",
+ "id": "threewsX402",
"title": "x402 Bazaar",
"icon": "media/x402.svg"
}
]
},
"views": {
- "x402Bazaar": [
+ "threewsX402": [
{
- "id": "x402.bazaar",
+ "id": "threewsX402.bazaar",
"name": "Services",
"icon": "media/x402.svg"
}
@@ -53,105 +53,101 @@
},
"viewsWelcome": [
{
- "view": "x402.bazaar",
- "contents": "Browse paid x402 APIs and MCP tools from any bazaar.\n\nPoint the extension at a discovery endpoint by setting `x402.bazaarUrl`, then refresh.\n[Set bazaar URL](command:x402.setBazaarUrl)\n[Refresh services](command:x402.refresh)\n[Set filters](command:x402.setFilters)\n\nNo bazaar needed to inspect or pay a single endpoint — just run **x402: Inspect Endpoint** or **x402: Pay & Call Endpoint** with any URL.\n\nTo pay for a service you'll need an EVM wallet key.\n[Set wallet key](command:x402.setWalletKey)"
+ "view": "threewsX402.bazaar",
+ "contents": "Browse paid x402 APIs and MCP tools from across the bazaar.\n[Refresh services](command:threewsX402.refresh)\n[Set filters](command:threewsX402.setFilters)\n\nTo pay for a service you'll need an EVM wallet key.\n[Set wallet key](command:threewsX402.setWalletKey)"
}
],
"commands": [
{
- "command": "x402.refresh",
+ "command": "threewsX402.refresh",
"title": "x402: Refresh Bazaar",
"icon": "$(refresh)"
},
{
- "command": "x402.search",
+ "command": "threewsX402.search",
"title": "x402: Search Bazaar",
"icon": "$(search)"
},
{
- "command": "x402.setFilters",
+ "command": "threewsX402.setFilters",
"title": "x402: Set Bazaar Filters",
"icon": "$(filter)"
},
{
- "command": "x402.setBazaarUrl",
- "title": "x402: Set Bazaar Discovery URL"
- },
- {
- "command": "x402.inspect",
+ "command": "threewsX402.inspect",
"title": "x402: Inspect Endpoint (decode 402 challenge)"
},
{
- "command": "x402.openService",
+ "command": "threewsX402.openService",
"title": "x402: Open Service Details"
},
{
- "command": "x402.pay",
+ "command": "threewsX402.pay",
"title": "x402: Pay & Call Endpoint"
},
{
- "command": "x402.setWalletKey",
+ "command": "threewsX402.setWalletKey",
"title": "x402: Set Wallet Key"
},
{
- "command": "x402.clearWalletKey",
+ "command": "threewsX402.clearWalletKey",
"title": "x402: Clear Wallet Key"
},
{
- "command": "x402.scaffoldEndpoint",
+ "command": "threewsX402.scaffoldEndpoint",
"title": "x402: Scaffold a Paid Endpoint"
}
],
"menus": {
"view/title": [
{
- "command": "x402.search",
- "when": "view == x402.bazaar",
+ "command": "threewsX402.search",
+ "when": "view == threewsX402.bazaar",
"group": "navigation@1"
},
{
- "command": "x402.setFilters",
- "when": "view == x402.bazaar",
+ "command": "threewsX402.setFilters",
+ "when": "view == threewsX402.bazaar",
"group": "navigation@2"
},
{
- "command": "x402.refresh",
- "when": "view == x402.bazaar",
+ "command": "threewsX402.refresh",
+ "when": "view == threewsX402.bazaar",
"group": "navigation@3"
}
],
"view/item/context": [
{
- "command": "x402.pay",
- "when": "view == x402.bazaar && viewItem == x402service",
+ "command": "threewsX402.pay",
+ "when": "view == threewsX402.bazaar && viewItem == x402service",
"group": "inline"
}
]
},
"configuration": {
- "title": "x402",
+ "title": "three.ws x402",
"properties": {
- "x402.bazaarUrl": {
+ "threewsX402.origin": {
"type": "string",
- "default": "",
- "markdownDescription": "Base URL of the x402 bazaar discovery API. The extension calls `<bazaarUrl>/api/bazaar/list` and `<bazaarUrl>/api/bazaar/search`. Leave empty to disable discovery (you can still inspect and pay any endpoint URL directly). Example: `https://three.ws`."
+ "default": "https://three.ws",
+ "description": "Origin that hosts the bazaar discovery API (/api/bazaar/list, /api/bazaar/search)."
},
- "x402.maxPaymentUsd": {
+ "threewsX402.maxPaymentUsd": {
"type": "number",
"default": 0.1,
"description": "Spending cap per request, in USD. Any auto-payment above this is refused before signing."
},
- "x402.confirmEachPayment": {
+ "threewsX402.confirmEachPayment": {
"type": "boolean",
"default": true,
"description": "Show a confirmation dialog with the exact USD amount before signing each payment."
},
- "x402.network": {
+ "threewsX402.network": {
"type": "string",
"default": "eip155:8453",
"description": "Preferred CAIP-2 network for payment when an endpoint accepts several (default: Base mainnet)."
},
- "x402.filters": {
+ "threewsX402.filters": {
"type": "object",
"default": {
"type": "http"
diff --git a/packages/vscode-x402/src/bazaar.js b/packages/vscode-x402/src/bazaar.js
index b4fcc5a5f..974e187bb 100644
--- a/packages/vscode-x402/src/bazaar.js
+++ b/packages/vscode-x402/src/bazaar.js
@@ -1,32 +1,17 @@
-// Buyer-side discovery client. Talks to an x402 bazaar discovery API
-// (<bazaarUrl>/api/bazaar/list, <bazaarUrl>/api/bazaar/search) that merges +
-// normalises results across the facilitators it indexes. The base URL is
-// configured via the `x402.bazaarUrl` setting — there is no hardcoded host, so
-// the extension works against any compatible bazaar. Runs in the extension host
-// (Node global fetch).
+// Buyer-side discovery client. Talks to the three.ws bazaar proxy
+// (/api/bazaar/list, /api/bazaar/search), which merges + normalises results
+// across every configured x402 facilitator. Mirrors public/x402-discover.js but
+// runs in the extension host (Node global fetch).
import * as vscode from 'vscode';
-/** Configured bazaar base URL, or '' if the user hasn't set one. */
-export function bazaarUrl() {
+function origin() {
return vscode.workspace
- .getConfiguration('x402')
- .get('bazaarUrl', '')
- .trim()
+ .getConfiguration('threewsX402')
+ .get('origin', 'https://three.ws')
.replace(/\/+$/, '');
}
-/** Thrown when a discovery action runs but no bazaar URL is configured. */
-export class NoBazaarConfigured extends Error {
- constructor() {
- super(
- 'No x402 bazaar configured. Set "x402.bazaarUrl" to a discovery API base URL ' +
- '(e.g. https://three.ws) to browse and search services.',
- );
- this.name = 'NoBazaarConfigured';
- }
-}
-
function applyFilters(url, filters = {}) {
const set = (k, v) => v != null && v !== '' && url.searchParams.set(k, String(v));
set('type', filters.type || 'http');
@@ -51,18 +36,14 @@ async function call(url) {
/** List bazaar services. Returns { type, count, items[], sources, errors }. */
export async function list(filters = {}) {
- const base = bazaarUrl();
- if (!base) throw new NoBazaarConfigured();
- const url = new URL(`${base}/api/bazaar/list`);
+ const url = new URL(`${origin()}/api/bazaar/list`);
applyFilters(url, filters);
return call(url);
}
/** Full-text search across the bazaar. Same envelope as list(). */
export async function search(query, filters = {}) {
- const base = bazaarUrl();
- if (!base) throw new NoBazaarConfigured();
- const url = new URL(`${base}/api/bazaar/search`);
+ const url = new URL(`${origin()}/api/bazaar/search`);
if (query) url.searchParams.set('query', query);
applyFilters(url, filters);
return call(url);
diff --git a/packages/vscode-x402/src/extension.js b/packages/vscode-x402/src/extension.js
index eadfd40c3..171fc45bb 100644
--- a/packages/vscode-x402/src/extension.js
+++ b/packages/vscode-x402/src/extension.js
@@ -1,8 +1,7 @@
-// x402 for VS Code — extension entry. Registers the bazaar tree, the
+// three.ws x402 — VS Code extension entry. Registers the bazaar tree, the
// inspect/pay/scaffold commands, the wallet status bar, and secret-storage
-// wallet management. Payments use the bundled x402-fetch wrapper; discovery
-// talks to whatever bazaar URL the user configures (x402.bazaarUrl). Inspecting
-// and paying a single endpoint URL works with no bazaar configured. No mocks.
+// wallet management. All payments use @three-ws/x402-fetch; all discovery uses
+// the live three.ws bazaar proxy. No mocks.
import * as vscode from 'vscode';
import { BazaarProvider } from './tree.js';
@@ -17,43 +16,19 @@ let statusBar;
export function activate(context) {
output = vscode.window.createOutputChannel('x402');
const provider = new BazaarProvider();
- const tree = vscode.window.createTreeView('x402.bazaar', { treeDataProvider: provider });
+ const tree = vscode.window.createTreeView('threewsX402.bazaar', { treeDataProvider: provider });
statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
- statusBar.command = 'x402.setWalletKey';
+ statusBar.command = 'threewsX402.setWalletKey';
context.subscriptions.push(output, tree, statusBar);
refreshStatusBar(context);
- // Re-render the tree when the bazaar URL (or filters) change.
- context.subscriptions.push(
- vscode.workspace.onDidChangeConfiguration((e) => {
- if (e.affectsConfiguration('x402.bazaarUrl') || e.affectsConfiguration('x402.filters')) {
- provider.refresh();
- }
- }),
- );
-
const reg = (id, fn) =>
context.subscriptions.push(vscode.commands.registerCommand(id, fn));
- reg('x402.refresh', () => provider.refresh());
-
- reg('x402.setBazaarUrl', async () => {
- const cfg = vscode.workspace.getConfiguration('x402');
- const current = cfg.get('bazaarUrl', '');
- const url = await vscode.window.showInputBox({
- title: 'x402 — Bazaar Discovery URL',
- prompt: 'Base URL of an x402 bazaar (calls <url>/api/bazaar/list & /search). Blank to disable.',
- placeHolder: 'https://your-bazaar.example.com',
- value: current,
- validateInput: (v) => (!v.trim() || isUrl(v.trim()) ? null : 'Enter a valid http(s) URL or leave blank'),
- });
- if (url === undefined) return;
- await cfg.update('bazaarUrl', url.trim(), vscode.ConfigurationTarget.Global);
- provider.refresh();
- });
+ reg('threewsX402.refresh', () => provider.refresh());
- reg('x402.search', async () => {
+ reg('threewsX402.search', async () => {
const q = await vscode.window.showInputBox({
title: 'Search the x402 bazaar',
prompt: 'Keywords (empty to list everything)',
@@ -62,27 +37,27 @@ export function activate(context) {
provider.setQuery(q.trim());
});
- reg('x402.setFilters', () => setFilters());
+ reg('threewsX402.setFilters', () => setFilters());
- reg('x402.inspect', async (preset) => {
+ reg('threewsX402.inspect', async (preset) => {
const url =
typeof preset === 'string'
? preset
: await vscode.window.showInputBox({
title: 'Inspect x402 endpoint',
prompt: 'Endpoint URL — decodes its 402 payment challenge',
- placeHolder: 'https://your-api.example.com/x402/…',
+ placeHolder: 'https://three.ws/api/…',
validateInput: (v) => (isUrl(v) ? null : 'Enter a valid http(s) URL'),
});
if (!url) return;
await runInspect(url);
});
- reg('x402.openService', (item) => {
+ reg('threewsX402.openService', (item) => {
if (item) showService(context, item);
});
- reg('x402.pay', async (node) => {
+ reg('threewsX402.pay', async (node) => {
// Invoked from the tree inline action (node.command.arguments[0]) or palette.
const item = node?.command?.arguments?.[0] || node;
if (item?.resource) {
@@ -91,14 +66,13 @@ export function activate(context) {
const url = await vscode.window.showInputBox({
title: 'Pay & call x402 endpoint',
prompt: 'Endpoint URL',
- placeHolder: 'https://your-api.example.com/x402/…',
validateInput: (v) => (isUrl(v) ? null : 'Enter a valid http(s) URL'),
});
if (url) showService(context, syntheticItem(url));
}
});
- reg('x402.setWalletKey', async () => {
+ reg('threewsX402.setWalletKey', async () => {
const address = await setKey(context);
if (address) {
vscode.window.showInformationMessage(`x402 wallet set: ${address}`);
@@ -106,13 +80,13 @@ export function activate(context) {
}
});
- reg('x402.clearWalletKey', async () => {
+ reg('threewsX402.clearWalletKey', async () => {
await clearKey(context);
vscode.window.showInformationMessage('x402 wallet key cleared.');
refreshStatusBar(context);
});
- reg('x402.scaffoldEndpoint', () => scaffoldEndpoint());
+ reg('threewsX402.scaffoldEndpoint', () => scaffoldEndpoint());
provider.refresh();
}
@@ -133,7 +107,7 @@ async function runInspect(url) {
output.clear();
output.show(true);
output.appendLine(`Inspecting ${url}`);
- const network = vscode.workspace.getConfiguration('x402').get('network');
+ const network = vscode.workspace.getConfiguration('threewsX402').get('network');
try {
const result = await inspectEndpoint(url, { preferNetwork: network });
summarize(result).forEach((l) => output.appendLine(l));
@@ -143,7 +117,7 @@ async function runInspect(url) {
}
async function setFilters() {
- const cfg = vscode.workspace.getConfiguration('x402');
+ const cfg = vscode.workspace.getConfiguration('threewsX402');
const current = cfg.get('filters', { type: 'http' });
const type = await vscode.window.showQuickPick(
@@ -172,7 +146,7 @@ async function setFilters() {
if (maxPrice) next.maxPrice = Number(maxPrice);
if (tag.trim()) next.tag = tag.trim();
await cfg.update('filters', next, vscode.ConfigurationTarget.Global);
- vscode.commands.executeCommand('x402.refresh');
+ vscode.commands.executeCommand('threewsX402.refresh');
}
function syntheticItem(url) {
diff --git a/packages/vscode-x402/src/inspect.js b/packages/vscode-x402/src/inspect.js
index 9a13da544..d9a5549aa 100644
--- a/packages/vscode-x402/src/inspect.js
+++ b/packages/vscode-x402/src/inspect.js
@@ -16,7 +16,7 @@ export async function inspectEndpoint(url, { method = 'GET', preferNetwork } = {
method,
headers: { accept: 'application/json' },
// MCP endpoints expect a body; for inspection a HEAD-ish GET is enough to
- // trigger the 402 challenge on most x402 merchants.
+ // trigger the 402 on three.ws + CDP merchants.
});
if (res.status !== 402) {
diff --git a/packages/vscode-x402/src/panel.js b/packages/vscode-x402/src/panel.js
index d51085443..24888942b 100644
--- a/packages/vscode-x402/src/panel.js
+++ b/packages/vscode-x402/src/panel.js
@@ -10,7 +10,7 @@ let panel = null;
export function showService(context, item) {
if (!panel) {
panel = vscode.window.createWebviewPanel(
- 'x402.service',
+ 'threewsX402.service',
'x402 Service',
vscode.ViewColumn.Active,
{ enableScripts: true, retainContextWhenHidden: true },
diff --git a/packages/vscode-x402/src/pay.js b/packages/vscode-x402/src/pay.js
index 2b00f1aef..269b26b63 100644
--- a/packages/vscode-x402/src/pay.js
+++ b/packages/vscode-x402/src/pay.js
@@ -1,6 +1,6 @@
// Pay-per-call flow. Pre-checks the 402 to show the exact USD amount, asks for
// confirmation (honouring the spend cap), then performs the real paid request
-// with the bundled x402-fetch wrapper and surfaces the settlement receipt.
+// with @three-ws/x402-fetch and surfaces the settlement receipt.
import * as vscode from 'vscode';
import { withX402, privateKeyToWallet } from '../../x402-fetch/src/index.js';
@@ -9,7 +9,7 @@ import { getKey, setKey } from './wallet.js';
import { inspectEndpoint } from './inspect.js';
function config() {
- const c = vscode.workspace.getConfiguration('x402');
+ const c = vscode.workspace.getConfiguration('threewsX402');
return {
maxPaymentUsd: c.get('maxPaymentUsd', 0.1),
confirmEachPayment: c.get('confirmEachPayment', true),
diff --git a/packages/vscode-x402/src/scaffold.js b/packages/vscode-x402/src/scaffold.js
index f7f3a8e4c..f09cb2d30 100644
--- a/packages/vscode-x402/src/scaffold.js
+++ b/packages/vscode-x402/src/scaffold.js
@@ -1,75 +1,66 @@
-// Scaffold a new paid x402 endpoint. Generates a self-contained Express server
-// that puts an x402 paywall in front of a route using the standard `x402-express`
-// middleware, then opens it. The output is framework-neutral and runs anywhere —
-// no platform-specific helpers, no monorepo imports.
+// Scaffold a new paid x402 endpoint that follows the repo's canonical
+// paidEndpoint() pattern (api/_lib/x402-paid-endpoint.js). Generates a working
+// handler file in the open workspace and opens it.
import * as vscode from 'vscode';
-function template({ slug, priceUsd, description, network, payTo, resourceUrl }) {
- const price = Number(priceUsd).toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
- return `// ${slug} — paid x402 endpoint.
+function template({ slug, fnName, priceUsd, description }) {
+ const priceAtomics = Math.round(Number(priceUsd) * 1e6);
+ return `// ${slug} — paid x402 endpoint. Buyers pay USDC; the call runs only after
+// settlement. Wired to the shared paidEndpoint() x402 dance.
//
-// Buyers pay USDC; the handler runs only after the payment settles. The paywall
-// is provided by the standard \`x402-express\` middleware, so this works with any
-// x402-compatible client (including this VS Code extension's "Pay & call").
-//
-// POST /x402/${slug}
-//
-// Install: npm i express x402-express
-// Run: PAY_TO=0xYourReceivingAddress node ${slug}.js
-//
-// Required env:
-// PAY_TO EVM address that receives the USDC payments.
-
-import express from 'express';
-import { paymentMiddleware } from 'x402-express';
-
-const PORT = Number(process.env.PORT || 4021);
-const NETWORK = process.env.X402_NETWORK || ${JSON.stringify(network)};
-const PAY_TO = process.env.PAY_TO || ${JSON.stringify(payTo)};
+// GET|POST /api/x402/${slug}
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+
+const RESOURCE_URL = 'https://three.ws/api/x402/${slug}';
+
+const paid = paidEndpoint({
+ route: '/api/x402/${slug}',
+ method: 'POST',
+ // $${Number(priceUsd).toFixed(6)} in USDC atomics (6 decimals).
+ priceAtomics: ${priceAtomics},
+ networks: ['base'],
+ description: ${JSON.stringify(description)},
+ service: withService({
+ serviceName: ${JSON.stringify(slug)},
+ tags: ['x402', 'paid'],
+ }),
+ bazaar: {
+ description: ${JSON.stringify(description)},
+ useCases: ['x402 paid api'],
+ input: { type: 'json', example: {}, schema: { type: 'object', additionalProperties: true } },
+ output: { type: 'json', example: {} },
+ schema: buildBazaarSchema({ method: 'POST', bodySchema: { type: 'object', additionalProperties: true } }),
+ resource: RESOURCE_URL,
+ },
+ resourceUrlBuilder: () => RESOURCE_URL,
+
+ // Runs ONLY after the buyer's USDC settles. Return JSON; throw an Error with
+ // a .status for handled failures.
+ async handler({ req }) {
+ const body = await readJson(req);
+ // Replace this echo with the real work. It returns the validated request
+ // so the endpoint is wired end-to-end from the first deploy.
+ return {
+ ok: true,
+ service: ${JSON.stringify(slug)},
+ received: body,
+ };
+ },
+});
-if (!PAY_TO || PAY_TO.startsWith('0xYour')) {
- throw new Error('Set PAY_TO to the EVM address that should receive payments.');
+async function readJson(req) {
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ const raw = Buffer.concat(chunks).toString('utf8');
+ return raw ? JSON.parse(raw) : {};
}
-const app = express();
-app.use(express.json());
-
-// Put a paywall in front of POST /x402/${slug}. The middleware answers an
-// unpaid request with a real 402 challenge and only calls the route once the
-// buyer's USDC payment is verified/settled.
-app.use(
- paymentMiddleware(
- PAY_TO,
- {
- 'POST /x402/${slug}': {
- price: '$${price}',
- network: NETWORK,
- config: {
- description: ${JSON.stringify(description)},
- // Where buyers can read about this resource.
- resource: ${JSON.stringify(resourceUrl)},
- },
- },
- },
- // Optional: pass a facilitator URL here to settle on a hosted facilitator.
- ),
-);
-
-app.post('/x402/${slug}', (req, res) => {
- // Runs ONLY after the buyer's USDC payment settles. Replace this echo with
- // the real work; it returns the validated request so the endpoint is wired
- // end-to-end from the first run.
- res.json({
- ok: true,
- service: ${JSON.stringify(slug)},
- received: req.body ?? null,
- });
-});
-
-app.listen(PORT, () => {
- console.log('${slug} paid endpoint listening on http://localhost:' + PORT + '/x402/${slug}');
-});
+export default paid;
+export const config = { api: { bodyParser: false } };
`;
}
@@ -82,7 +73,7 @@ export async function scaffoldEndpoint() {
const slug = await vscode.window.showInputBox({
title: 'Scaffold paid endpoint — slug',
- prompt: 'URL slug, e.g. "summarize" → /x402/summarize',
+ prompt: 'URL slug, e.g. "summarize" → /api/x402/summarize',
validateInput: (v) =>
/^[a-z0-9][a-z0-9-]*$/.test((v || '').trim()) ? null : 'lowercase letters, digits, hyphens',
});
@@ -97,30 +88,25 @@ export async function scaffoldEndpoint() {
const description = await vscode.window.showInputBox({
title: 'Description',
- prompt: 'What does this endpoint do? (shown to buyers)',
+ prompt: 'What does this endpoint do? (shown in the bazaar)',
value: `${slug} service`,
});
if (description == null) return;
- const cfg = vscode.workspace.getConfiguration('x402');
- const network = networkSlug(cfg.get('network', 'eip155:8453'));
-
const cleanSlug = slug.trim();
const content = template({
slug: cleanSlug,
+ fnName: cleanSlug.replace(/-([a-z])/g, (_, c) => c.toUpperCase()),
priceUsd,
description,
- network,
- payTo: '0xYourReceivingAddress',
- resourceUrl: `https://your-api.example.com/x402/${cleanSlug}`,
});
const root = folders[0].uri;
- const target = vscode.Uri.joinPath(root, `${cleanSlug}.js`);
+ const target = vscode.Uri.joinPath(root, 'api', 'x402', `${cleanSlug}.js`);
try {
await vscode.workspace.fs.stat(target);
const ow = await vscode.window.showWarningMessage(
- `${cleanSlug}.js already exists. Overwrite?`,
+ `api/x402/${cleanSlug}.js already exists. Overwrite?`,
'Overwrite',
'Cancel',
);
@@ -133,18 +119,6 @@ export async function scaffoldEndpoint() {
const doc = await vscode.workspace.openTextDocument(target);
await vscode.window.showTextDocument(doc);
vscode.window.showInformationMessage(
- `Scaffolded /x402/${cleanSlug} (${cleanSlug}.js). Run "npm i express x402-express", set PAY_TO, then "node ${cleanSlug}.js".`,
+ `Scaffolded /api/x402/${cleanSlug} — it returns a wired echo response; replace the handler body with real work.`,
);
}
-
-// Map a CAIP-2 id to the x402 network slug used by x402-express. Defaults to
-// "base" for anything unrecognised so the scaffold stays runnable.
-function networkSlug(caip2) {
- const map = {
- 'eip155:8453': 'base',
- 'eip155:84532': 'base-sepolia',
- 'eip155:43114': 'avalanche',
- 'eip155:43113': 'avalanche-fuji',
- };
- return map[String(caip2 || '').trim()] || 'base';
-}
diff --git a/packages/vscode-x402/src/tree.js b/packages/vscode-x402/src/tree.js
index db3a7fa77..081496af4 100644
--- a/packages/vscode-x402/src/tree.js
+++ b/packages/vscode-x402/src/tree.js
@@ -5,7 +5,7 @@
import * as vscode from 'vscode';
import * as bazaar from './bazaar.js';
-const STATE = { loading: 'loading', error: 'error', ready: 'ready', unconfigured: 'unconfigured' };
+const STATE = { loading: 'loading', error: 'error', ready: 'ready' };
export class BazaarProvider {
constructor() {
@@ -18,7 +18,7 @@ export class BazaarProvider {
}
filters() {
- return vscode.workspace.getConfiguration('x402').get('filters', { type: 'http' });
+ return vscode.workspace.getConfiguration('threewsX402').get('filters', { type: 'http' });
}
setQuery(query) {
@@ -27,12 +27,6 @@ export class BazaarProvider {
}
async refresh() {
- if (!bazaar.bazaarUrl()) {
- this._state = STATE.unconfigured;
- this._items = [];
- this._emitter.fire();
- return;
- }
this._state = STATE.loading;
this._emitter.fire();
try {
@@ -55,14 +49,6 @@ export class BazaarProvider {
}
getChildren(node) {
- if (this._state === STATE.unconfigured) {
- const node = infoNode('Set x402.bazaarUrl to browse a bazaar', new vscode.ThemeIcon('gear'));
- node.command = {
- command: 'x402.setBazaarUrl',
- title: 'Set Bazaar Discovery URL',
- };
- return [node];
- }
if (this._state === STATE.loading) {
return [infoNode('Loading services…', new vscode.ThemeIcon('loading~spin'))];
}
@@ -113,7 +99,7 @@ function serviceNode(item) {
node.iconPath = new vscode.ThemeIcon(item.type === 'mcp' ? 'plug' : 'globe');
node.contextValue = 'x402service';
node.command = {
- command: 'x402.openService',
+ command: 'threewsX402.openService',
title: 'Open Service Details',
arguments: [item],
};
diff --git a/packages/vscode-x402/src/wallet.js b/packages/vscode-x402/src/wallet.js
index 2e3631cf7..04c081269 100644
--- a/packages/vscode-x402/src/wallet.js
+++ b/packages/vscode-x402/src/wallet.js
@@ -6,7 +6,7 @@
import * as vscode from 'vscode';
import { privateKeyToWallet } from '../../x402-fetch/src/index.js';
-const SECRET_KEY = 'x402.walletPrivateKey';
+const SECRET_KEY = 'threewsX402.walletPrivateKey';
function normalizePk(raw) {
const pk = raw.trim();
diff --git a/packages/x402-fetch/README.md b/packages/x402-fetch/README.md
index d018b070e..1a5da2c07 100644
--- a/packages/x402-fetch/README.md
+++ b/packages/x402-fetch/README.md
@@ -1,8 +1,8 @@
# @three-ws/x402-fetch
A drop-in `fetch` that silently answers [x402](https://x402.org) payment
-challenges. Wrap a wallet once, then call any paid x402 endpoint — CDP-x402 or
-any compatible merchant — as if it were free.
+challenges. Wrap a wallet once, then call any paid [three.ws](https://three.ws)
+(or CDP-x402 / agentic.market) endpoint as if it were free.
```bash
npm install @three-ws/x402-fetch
@@ -10,8 +10,8 @@ npm install @three-ws/x402-fetch
- **Zero production dependencies.** The secp256k1 / keccak256 / EIP-712 signing
stack is inlined — no `viem`, `ethers`, or `@wagmi/core` pulled into your bundle.
-- **Works in the browser and Node.** MetaMask / EIP-1193 providers, a pre-built
- signer (e.g. a viem account), or a raw private key all work.
+- **Works in the browser and Node.** MetaMask / EIP-1193 providers, the three.ws
+ agent SDK wallet, or a raw private key all work.
- **Safe by default.** A `maxPaymentUsd` guard refuses to auto-pay more than you
authorize. Descriptive errors instead of silent failures.
- **USDC on Base.** Signs EIP-3009 `transferWithAuthorization` — the same payload
@@ -25,7 +25,7 @@ import { withX402 } from '@three-ws/x402-fetch';
// Browser: pass the injected wallet provider.
const pay = withX402(window.ethereum, { maxPaymentUsd: 0.1 });
-const res = await pay('https://api.example.com/paid', {
+const res = await pay('https://three.ws/api/mcp', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
@@ -55,7 +55,7 @@ import { privateKeyToWallet } from '@three-ws/x402-fetch/wallet';
const pay = withX402(privateKeyToWallet(process.env.WALLET_PRIVATE_KEY));
```
-**Pre-built signer (any object exposing `{ address, signTypedData }`, e.g. a viem account):**
+**Pre-built signer (three.ws agent SDK / viem account):**
```js
withX402({ address, signTypedData });
@@ -96,4 +96,4 @@ const pay = wrapFetchWithPayment(fetch, wallet);
## License
-MIT
+MIT © three.ws
diff --git a/packages/x402-fetch/package.json b/packages/x402-fetch/package.json
index d33d993a3..1a0b3c607 100644
--- a/packages/x402-fetch/package.json
+++ b/packages/x402-fetch/package.json
@@ -40,10 +40,8 @@
"usdc",
"base",
"eip-3009",
- "eip-712",
- "micropayments",
- "402",
- "agent"
+ "agent",
+ "three.ws"
],
"author": "nirholas <[email protected]>",
"homepage": "https://three.ws",
diff --git a/packages/x402-fetch/src/client.js b/packages/x402-fetch/src/client.js
index 822fed3ad..b9a5f11a4 100644
--- a/packages/x402-fetch/src/client.js
+++ b/packages/x402-fetch/src/client.js
@@ -1,6 +1,8 @@
// Payment client — turns a selected 402 requirement + a wallet into a signed
-// X-PAYMENT header, mirroring the wire shape an x402 v2 facilitator verifies:
-// an EIP-3009 transferWithAuthorization signature wrapped in a v2 PaymentPayload.
+// X-PAYMENT header, mirroring the wire shape the three.ws server verifies
+// (api/_lib/x402-spec.js) and the in-repo browser paywall builds
+// (public/x402-pay-core.js): an EIP-3009 transferWithAuthorization signature
+// wrapped in a v2 PaymentPayload.
import { isEvmNetwork } from './parse-challenge.js';
diff --git a/packages/x402-fetch/src/index.d.ts b/packages/x402-fetch/src/index.d.ts
index eff0be290..b8f83e7d8 100644
--- a/packages/x402-fetch/src/index.d.ts
+++ b/packages/x402-fetch/src/index.d.ts
@@ -14,7 +14,7 @@ export interface TypedDataSigner {
* A wallet accepted by `withX402`. One of:
* - a 0x-prefixed private key string (Node),
* - an EIP-1193 provider (browser `window.ethereum`),
- * - a pre-built signer object `{ address, signTypedData }` (e.g. a viem account).
+ * - a pre-built signer object `{ address, signTypedData }` (three.ws SDK / viem account).
*/
export type Wallet = string | EIP1193Provider | TypedDataSigner;
diff --git a/packages/x402-fetch/src/index.js b/packages/x402-fetch/src/index.js
index cf894c421..dd068782c 100644
--- a/packages/x402-fetch/src/index.js
+++ b/packages/x402-fetch/src/index.js
@@ -1,12 +1,11 @@
// @three-ws/x402-fetch — a drop-in `fetch` that silently answers x402 payment
-// challenges. Wrap a wallet once, then call any paid x402 endpoint (CDP-x402 or
-// any compatible merchant) as if it were free: on a 402 the wrapper parses the
-// challenge, signs a USDC-on-Base EIP-3009 authorization, and retries with the
-// X-PAYMENT proof.
+// challenges. Wrap a wallet once, then call any paid three.ws (or CDP-x402)
+// endpoint as if it were free: on a 402 the wrapper parses the challenge, signs
+// a USDC-on-Base EIP-3009 authorization, and retries with the X-PAYMENT proof.
//
// import { withX402 } from '@three-ws/x402-fetch';
// const pay = withX402(wallet, { maxPaymentUsd: 0.10 });
-// const res = await pay('https://api.example.com/paid', { method: 'POST', body });
+// const res = await pay('https://three.ws/api/mcp', { method: 'POST', body });
//
// Zero production dependencies — the secp256k1 / keccak256 / EIP-712 stack is
// inlined (src/crypto/*). See README for wallet forms and options.
@@ -18,8 +17,8 @@ import { createPaymentHeader } from './client.js';
const DEFAULT_MAX_PAYMENT_USD = 0.1;
const DEFAULT_TIMEOUT_MS = 15000;
-// The package supports three call conventions so both the wallet-first snippets
-// and the upstream x402-fetch (fetch-first) signature work:
+// The package supports three call conventions so the generated snippets across
+// three.ws (wallet-first) and the upstream x402-fetch (fetch-first) both work:
// withX402(wallet, options?)
// withX402(fetch, wallet) // upstream wrapFetchWithPayment shape
// withX402(fetch, { wallet, ...options })
diff --git a/packages/x402-fetch/src/parse-challenge.js b/packages/x402-fetch/src/parse-challenge.js
index c9a67efd4..06a483cd2 100644
--- a/packages/x402-fetch/src/parse-challenge.js
+++ b/packages/x402-fetch/src/parse-challenge.js
@@ -1,6 +1,6 @@
// Parse a 402 Payment Required response into a normalised list of payment
-// requirements. CDP-x402 and compatible merchants emit the v2 envelope both as
-// the JSON body and as the base64 `PAYMENT-REQUIRED` response
+// requirements. three.ws (and every CDP-x402 / agentic.market merchant) emits the
+// v2 envelope both as the JSON body and as the base64 `PAYMENT-REQUIRED` response
// header; we read the header first (it survives an already-consumed body and a
// non-JSON content-type) and fall back to the body.
//
diff --git a/packages/x402-fetch/src/wallet.js b/packages/x402-fetch/src/wallet.js
index 515b5b29a..4280daa7b 100644
--- a/packages/x402-fetch/src/wallet.js
+++ b/packages/x402-fetch/src/wallet.js
@@ -5,7 +5,7 @@
// Accepted inputs:
// 1. EIP-1193 provider (window.ethereum / any object with `.request`) — browser.
// 2. A pre-built wallet object `{ address, signTypedData(typedData) }` —
-// viem LocalAccounts and any compatible signer satisfy this.
+// the three.ws agent SDK and viem LocalAccounts both satisfy this.
// 3. A private key (0x-hex string) via `privateKeyToWallet(pk)` — Node.
import { eip712Digest } from './crypto/eip712.js';
@@ -47,7 +47,7 @@ async function resolveAddress(wallet) {
if (!addr) throw new Error('x402: wallet returned no account');
return addr;
}
- // Pre-built wallet object (viem LocalAccount / viem WalletClient / compatible signer).
+ // Pre-built wallet object (three.ws SDK / viem LocalAccount / viem WalletClient).
const addr = wallet?.address || wallet?.account?.address;
if (!addr) throw new Error('x402: wallet object must expose an `address`');
return addr;
@@ -81,8 +81,8 @@ export function adaptWallet(wallet) {
});
}
if (typeof wallet.signTypedData === 'function') {
- // viem accounts take the typed-data object directly; any compatible
- // signer uses the same shape. Both resolve to a hex signature.
+ // viem accounts take the typed-data object directly; the three.ws SDK
+ // wallet uses the same shape. Both resolve to a hex signature.
return await wallet.signTypedData(typedData);
}
throw new Error('x402: wallet does not support signTypedData');
diff --git a/packages/x402-mcp/README.md b/packages/x402-mcp/README.md
index ee20d593c..c8d35dca8 100644
--- a/packages/x402-mcp/README.md
+++ b/packages/x402-mcp/README.md
@@ -1,18 +1,24 @@
-<h1 align="center">x402-mcp</h1>
+<p align="center">
+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" alt="three.ws" width="88" height="88"></a>
+</p>
+
+<h1 align="center">@three-ws/x402-mcp</h1>
-<p align="center"><strong>Give any AI agent a self-custodial x402 wallet — inspect, discover, and pay any paid endpoint in USDC from your own Solana key.</strong></p>
+<p align="center"><strong>Give any AI agent a self-custodial x402 wallet — discover, inspect, and pay any paid service in USDC from your own Solana key.</strong></p>
<p align="center">
<a href="https://www.npmjs.com/package/@three-ws/x402-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/x402-mcp?logo=npm&color=cb3837"></a>
<img alt="license" src="https://img.shields.io/npm/l/@three-ws/x402-mcp?color=3b82f6">
<img alt="node" src="https://img.shields.io/node/v/@three-ws/x402-mcp?color=339933&logo=node.js">
+ <a href="https://registry.modelcontextprotocol.io/?q=io.github.nirholas"><img alt="MCP Registry" src="https://img.shields.io/badge/MCP%20Registry-io.github.nirholas-0ea5e9"></a>
+ <a href="https://three.ws"><img alt="three.ws" src="https://img.shields.io/badge/built%20by-three.ws-000"></a>
</p>
---
-> A [Model Context Protocol](https://modelcontextprotocol.io) server that turns any AI assistant into an autonomous economic agent on the [x402](https://x402.org) network. Read an endpoint's price **before** committing money, then `pay_and_call` any x402 endpoint in USDC — settled on Solana with **your own key**, never a custodial wallet.
+> A [Model Context Protocol](https://modelcontextprotocol.io) server that turns any AI assistant into an autonomous economic agent on the [x402](https://x402.org) network. Search the live bazaar for paid services, read an endpoint's price **before** committing money, and `pay_and_call` any x402 service in USDC — settled on Solana with **your own key**, never a custodial wallet.
-The core flow needs nothing but a Solana RPC and a key. The payment dance and Solana `exact`-scheme signing are handled by the real `@x402/*` libraries — nothing is mocked.
+This is the *buyer* side of the three.ws agent economy. The payment dance and Solana `exact`-scheme signing are handled by the real `@x402/*` libraries — nothing is mocked.
## Install
@@ -52,15 +58,15 @@ claude mcp add x402 --env SOLANA_SECRET_KEY=<base58> -- npx -y @three-ws/x402-mc
}
```
-`SOLANA_SECRET_KEY` is only needed to **spend** (`pay_and_call`, and `x402_wallet` defaulting to your wallet). `inspect_endpoint` works with no key. `find_services` additionally needs `X402_API_BASE` (a discovery endpoint).
+`SOLANA_SECRET_KEY` is only needed to **spend** (`pay_and_call`, and `x402_wallet` defaulting to your wallet). `find_services` and `inspect_endpoint` work with no key.
## Tools
| Tool | Type | What it does |
| ------------------ | ------------- | -------------------------------------------------------------------------------------------------------- |
| `x402_wallet` | read-only | A wallet's address + live SOL/USDC balance. Defaults to your signer wallet — confirm funds before paying. |
+| `find_services` | read-only | Search the live x402 bazaar (PayAI + Coinbase CDP) for paid HTTP/MCP services with prices. |
| `inspect_endpoint` | read-only | Read any endpoint's 402 payment requirements (scheme, network, asset, price, pay-to) **without paying**. |
-| `find_services` | read-only | Search an x402 bazaar / discovery API for paid HTTP/MCP services with prices. Requires `X402_API_BASE`. |
| `pay_and_call` | **execution** | Pay an x402 endpoint in USDC from your Solana key and return its result. Bounded by `MAX_PAY_USD`. |
### Safety
@@ -71,19 +77,17 @@ claude mcp add x402 --env SOLANA_SECRET_KEY=<base58> -- npx -y @three-ws/x402-mc
**`x402_wallet`** — `address` (optional base58; defaults to the signer wallet).
-**`inspect_endpoint`** — `url` (required), `method` (`GET` | `POST`), `body` (object).
-
**`find_services`** — `query` (required), `type` (`http` | `mcp`, default `http`), `network` (CAIP-2 filter), `max_price_usdc`, `limit` (1–100).
-**`pay_and_call`** — `url` (required), `method` (`GET` | `POST`), `body` (object), `token` (`usdc` default, or `three` when the endpoint advertises it), `max_usd` (lowers the cap for this call), `secret` (per-call signer override), `confirm` (must be `true` when `REQUIRE_CONFIRM` is on), `session_token` (optional; routes through a hosted wallet service set via `X402_API_BASE`).
+**`inspect_endpoint`** — `url` (required), `method` (`GET` | `POST`), `body` (object).
-## Example
+**`pay_and_call`** — `url` (required), `method` (`GET` | `POST`), `body` (object), `max_usd` (lowers the cap for this call), `secret` (per-call signer override), `confirm` (must be `true` when `REQUIRE_CONFIRM` is on).
-Self-custodial USDC against any x402 endpoint — no account, no discovery service, just a Solana key:
+## Example
```jsonc
-// inspect_endpoint — what does it cost? (no payment, no key)
-> { "url": "https://api.example.com/x402/quote" }
+// inspect_endpoint — what does it cost? (no payment)
+> { "url": "https://three.ws/api/x402/vanity?prefix=ab" }
{
"ok": true, "paid": true,
"accepts": [
@@ -92,41 +96,40 @@ Self-custodial USDC against any x402 endpoint — no account, no discovery servi
"payable_with_this_wallet": true
}
-// pay_and_call — settle in USDC; confirm:true required by default
-> { "url": "https://api.example.com/x402/quote", "confirm": true }
-{ "ok": true, "paid": true, "payer": "Gx5E…", "token": "usdc", "price_usd": 0.05, "settlement": { … }, "result": { … } }
-```
-
-### Optional: discovery and alternate tokens
-
-`find_services` searches an x402 bazaar / discovery API. Point `X402_API_BASE` at any compatible endpoint — for example [three.ws](https://three.ws), which merges the public PayAI and Coinbase CDP facilitator feeds:
-
-```bash
-X402_API_BASE=https://three.ws SOLANA_SECRET_KEY=<base58> npx @three-ws/x402-mcp
+// pay_and_call — confirm:true required by default
+> { "url": "https://three.ws/api/x402/vanity?prefix=ab", "confirm": true }
+{ "ok": true, "paid": true, "payer": "Gx5E…", "price_usd": 0.05, "settlement": { … }, "result": { … } }
```
-When an endpoint advertises a non-USDC token (e.g. `$THREE`, Solana mint `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`), pay in it with `token: "three"`. USDC remains the default and works everywhere.
-
## Requirements
- **Node.js >= 20.**
- A Solana mainnet RPC endpoint (`https`; only `http://localhost` is allowed for dev). Public cluster works for reads; bring your own for payment traffic.
- To pay: a Solana wallet holding USDC, as a base58 `SOLANA_SECRET_KEY` (or per-call `secret`).
-- For `find_services` / `session_token`: `X402_API_BASE` pointing at an x402 bazaar / discovery API.
### Environment variables
-| Variable | Required | Default |
-| --------------------- | --------------- | ------------------------------------- |
-| `SOLANA_SECRET_KEY` | to pay only | — |
-| `SOLANA_RPC_URL` | no | `https://api.mainnet-beta.solana.com` |
-| `MAX_PAY_USD` | no | `1` |
-| `REQUIRE_CONFIRM` | no | `true` |
-| `X402_HTTP_TIMEOUT_MS`| no | `60000` |
-| `X402_API_BASE` | for discovery | — (e.g. `https://three.ws`) |
+| Variable | Required | Default |
+| ------------------- | ------------ | ------------------------------------- |
+| `SOLANA_SECRET_KEY` | to pay only | — |
+| `SOLANA_RPC_URL` | no | `https://api.mainnet-beta.solana.com` |
+| `MAX_PAY_USD` | no | `1` |
+| `REQUIRE_CONFIRM` | no | `true` |
+| `THREE_WS_BASE` | no | `https://three.ws` |
-> Legacy names `THREE_WS_BASE` and `THREE_WS_TIMEOUT_MS` are still honoured as fallbacks for `X402_API_BASE` and `X402_HTTP_TIMEOUT_MS`.
+## Links
-## License
+- Homepage: https://three.ws
+- MCP catalog: https://three.ws/docs/mcp
+- Changelog: https://three.ws/changelog
+- Issues: https://github.com/nirholas/three.ws/issues
+- License: Apache-2.0 — see [LICENSE](./LICENSE)
-Apache-2.0 — see [LICENSE](./LICENSE).
+---
+
+<p align="center">
+ <sub>
+ Part of the <a href="https://three.ws">three.ws</a> SDK suite — 3D AI agents, on-chain identity, and agent payments.<br/>
+ <a href="https://three.ws">Website</a> · <a href="https://three.ws/changelog">Changelog</a> · <a href="https://github.com/nirholas/three.ws">GitHub</a>
+ </sub>
+</p>
diff --git a/packages/x402-mcp/package.json b/packages/x402-mcp/package.json
index 2a26dc647..167effd10 100644
--- a/packages/x402-mcp/package.json
+++ b/packages/x402-mcp/package.json
@@ -2,7 +2,7 @@
"name": "@three-ws/x402-mcp",
"version": "0.2.0",
"mcpName": "io.github.nirholas/x402-mcp",
- "description": "Give any AI agent a self-custodial x402 wallet. Inspect an endpoint's price without paying, discover services on any x402 bazaar, and pay_and_call any x402 endpoint in USDC from your own Solana key — real @x402 settlement, bounded by spend caps. No custodial wallet, no account.",
+ "description": "Give any AI agent a self-custodial x402 wallet. Search the live bazaar, inspect an endpoint's price without paying, and pay_and_call any x402 service in USDC or $THREE from your own Solana key — real @x402 settlement, bounded by spend caps. No custodial wallet, no account.",
"type": "module",
"author": "nirholas <[email protected]>",
"license": "Apache-2.0",
@@ -18,9 +18,11 @@
"keywords": [
"mcp",
"model-context-protocol",
+ "three.ws",
"x402",
"solana",
"usdc",
+ "three",
"payments",
"agent-payments",
"bazaar",
diff --git a/packages/x402-mcp/server.json b/packages/x402-mcp/server.json
index 0cc1f8db4..35968c99c 100644
--- a/packages/x402-mcp/server.json
+++ b/packages/x402-mcp/server.json
@@ -2,7 +2,7 @@
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
"name": "io.github.nirholas/x402-mcp",
"title": "x402 Wallet",
- "description": "Self-custodial x402 wallet for AI agents: inspect, discover, and pay any x402 endpoint in USDC from your own Solana key.",
+ "description": "Self-custodial x402 wallet for AI agents: pay any service in USDC or $THREE from your own key.",
"websiteUrl": "https://three.ws",
"icons": [
{
@@ -31,7 +31,7 @@
"environmentVariables": [
{
"name": "SOLANA_SECRET_KEY",
- "description": "Base58 (or JSON byte-array) Solana secret key that signs payments and holds the USDC. Not needed for inspect_endpoint or x402_wallet with an explicit address. Treat like cash.",
+ "description": "Base58 (or JSON byte-array) Solana secret key that signs payments and holds the USDC. Not needed for the read tools (find_services, inspect_endpoint, or x402_wallet with an explicit address). Treat like cash.",
"format": "string",
"isRequired": false,
"isSecret": true
@@ -58,10 +58,11 @@
"default": "true"
},
{
- "name": "X402_API_BASE",
- "description": "Base URL of an x402 bazaar / discovery API that serves /api/bazaar/search for find_services and (optionally) /api/pay/execute for session-governed payments. No default — required only for find_services and session_token mode. Example: https://three.ws.",
+ "name": "THREE_WS_BASE",
+ "description": "Base URL of the three.ws API that serves /api/bazaar/search for find_services. Override only when self-hosting.",
"format": "string",
- "isRequired": false
+ "isRequired": false,
+ "default": "https://three.ws"
}
]
}
diff --git a/packages/x402-mcp/src/config.js b/packages/x402-mcp/src/config.js
index b204fb56a..748accd5f 100644
--- a/packages/x402-mcp/src/config.js
+++ b/packages/x402-mcp/src/config.js
@@ -2,43 +2,25 @@
//
// This server is user-keyed: outgoing payments are signed by a Solana keypair
// the operator supplies (SOLANA_SECRET_KEY) or a per-call `secret` overrides.
-// We never bake in a key. The core self-custodial pay_and_call works with only a
-// Solana RPC + key — no external API base required. inspect_endpoint and the
-// explicit-address x402_wallet need no key either. Only find_services and the
-// optional session-governed pay path need X402_API_BASE (a discovery endpoint).
+// We never bake in a key. The read tools (x402_wallet with an explicit address,
+// find_services, inspect_endpoint) work with no key at all — only pay_and_call
+// (and x402_wallet defaulting to the signer) needs one.
export function env(key, fallback) {
const v = process.env[key];
return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;
}
-// Optional base URL of an x402 discovery / bazaar API. Powers find_services
-// (GET /api/bazaar/search) and the optional session-governed pay path. There is
-// NO default — the core self-custodial pay_and_call needs only a Solana RPC + key.
-// Set X402_API_BASE to any compatible discovery endpoint (e.g. https://three.ws).
-// The legacy THREE_WS_BASE name is still honoured as a fallback.
-export const X402_API_BASE = env('X402_API_BASE', env('THREE_WS_BASE', '')).replace(/\/+$/, '');
-
-/** Throw a clear, actionable error when a feature needs X402_API_BASE but it's unset. */
-export function requireApiBase(feature) {
- if (!X402_API_BASE) {
- throw Object.assign(
- new Error(
- `${feature} needs a discovery endpoint — set X402_API_BASE to an x402 bazaar/discovery URL (e.g. https://three.ws).`,
- ),
- { code: 'no_api_base' },
- );
- }
- return X402_API_BASE;
-}
+// Base URL of the three.ws API (serves /api/bazaar/search for find_services).
+export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws').replace(/\/+$/, '');
// Per-request timeout (ms). Paid calls settle on-chain, so the default is roomy.
export const HTTP_TIMEOUT_MS = (() => {
- const raw = env('X402_HTTP_TIMEOUT_MS', env('THREE_WS_TIMEOUT_MS'));
+ const raw = env('THREE_WS_TIMEOUT_MS');
if (raw === undefined) return 60000;
const n = Number(raw);
if (!Number.isFinite(n) || n <= 0) {
- throw Object.assign(new Error(`X402_HTTP_TIMEOUT_MS must be a positive number (got "${raw}")`), {
+ throw Object.assign(new Error(`THREE_WS_TIMEOUT_MS must be a positive number (got "${raw}")`), {
code: 'bad_config',
});
}
@@ -94,4 +76,4 @@ export const REQUIRE_CONFIRM = (() => {
// Canonical Solana mainnet USDC mint (6 decimals) — for balance reads.
export const USDC_MAINNET_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
-export const USER_AGENT = 'x402-mcp';
+export const USER_AGENT = '@three-ws/x402-mcp';
diff --git a/packages/x402-mcp/src/index.js b/packages/x402-mcp/src/index.js
index 6751017c6..ddcba382e 100755
--- a/packages/x402-mcp/src/index.js
+++ b/packages/x402-mcp/src/index.js
@@ -1,19 +1,18 @@
#!/usr/bin/env node
-// x402-mcp — MCP server entry point.
+// @three-ws/x402-mcp — MCP server entry point.
//
// Gives any AI assistant a self-custodial x402 wallet over stdio:
// • x402_wallet — the wallet's address + SOL/USDC balance (read-only)
-// • find_services — search an x402 bazaar/discovery API for paid services (read-only)
+// • find_services — search the live x402 bazaar for paid services (read-only)
// • inspect_endpoint— read an endpoint's price/requirements without paying (read-only)
// • pay_and_call — pay an x402 endpoint in USDC and return its result (execution)
//
// Self-custodial: payments are signed by YOUR Solana key (SOLANA_SECRET_KEY),
-// not a custodial wallet. inspect_endpoint and explicit-address x402_wallet work
-// with no key; find_services needs X402_API_BASE. Real @x402/* libs do the 402
-// dance + Solana `exact` settlement — nothing is mocked.
+// not a custodial wallet. The read tools work with no key. Real @x402/* libs do
+// the 402 dance + Solana `exact` settlement — nothing is mocked.
//
// Run standalone:
-// SOLANA_SECRET_KEY=<base58> node src/index.js
+// SOLANA_SECRET_KEY=<base58> node packages/x402-mcp/src/index.js
//
// Or wire into Claude Code / Cursor — see README.md.
@@ -48,10 +47,10 @@ export function buildServer() {
capabilities: { tools: {} },
instructions:
'x402 buyer MCP — give the agent a self-custodial wallet that can pay for anything on the x402 ' +
- 'network. inspect_endpoint reads any endpoint\'s price/requirements WITHOUT paying. find_services ' +
- 'searches an x402 bazaar/discovery API (set X402_API_BASE). x402_wallet shows the signer wallet\'s ' +
- 'address and SOL/USDC balance. pay_and_call is an EXECUTION ACTION: it pays an x402 endpoint in USDC ' +
- 'from your Solana key (SOLANA_SECRET_KEY or a per-call `secret`) and returns the result, bounded by ' +
+ 'network. find_services searches the live bazaar (PayAI + Coinbase CDP). inspect_endpoint reads ' +
+ "any endpoint's price/requirements WITHOUT paying. x402_wallet shows the signer wallet's address " +
+ 'and SOL/USDC balance. pay_and_call is an EXECUTION ACTION: it pays an x402 endpoint in USDC from ' +
+ 'your Solana key (SOLANA_SECRET_KEY or a per-call `secret`) and returns the result, bounded by ' +
'MAX_PAY_USD and gated by REQUIRE_CONFIRM. Settlement is the Solana `exact` scheme via the real ' +
'@x402 libraries — never a wallet you do not control.',
},
diff --git a/packages/x402-mcp/src/lib/api.js b/packages/x402-mcp/src/lib/api.js
index 517a9744e..b3ba420d5 100644
--- a/packages/x402-mcp/src/lib/api.js
+++ b/packages/x402-mcp/src/lib/api.js
@@ -1,11 +1,10 @@
-// Plain HTTP access to a configured x402 discovery API (used by find_services).
-// Real network only — no mocks. Errors normalized into one shape. The base URL
-// must be supplied via X402_API_BASE; callers pass the resolved base in.
+// Plain HTTP access to the three.ws API (used by find_services). Real network
+// only — no mocks. Errors normalized into one shape.
-import { HTTP_TIMEOUT_MS, USER_AGENT } from '../config.js';
+import { THREE_WS_BASE, HTTP_TIMEOUT_MS, USER_AGENT } from '../config.js';
-export async function apiRequest(base, path, { method = 'GET', query, body } = {}) {
- const url = new URL(`${base}${path}`);
+export async function apiRequest(path, { method = 'GET', query, body } = {}) {
+ const url = new URL(`${THREE_WS_BASE}${path}`);
if (query) {
for (const [key, value] of Object.entries(query)) {
if (value === undefined || value === null || value === '') continue;
@@ -29,9 +28,9 @@ export async function apiRequest(base, path, { method = 'GET', query, body } = {
} catch (err) {
clearTimeout(timer);
if (err?.name === 'AbortError') {
- throw Object.assign(new Error(`${path} timed out after ${HTTP_TIMEOUT_MS}ms`), { code: 'timeout' });
+ throw Object.assign(new Error(`three.ws ${path} timed out after ${HTTP_TIMEOUT_MS}ms`), { code: 'timeout' });
}
- throw Object.assign(new Error(`${path} request failed: ${err?.message || err}`), { code: 'network_error' });
+ throw Object.assign(new Error(`three.ws ${path} request failed: ${err?.message || err}`), { code: 'network_error' });
}
clearTimeout(timer);
const text = await res.text();
@@ -42,7 +41,7 @@ export async function apiRequest(base, path, { method = 'GET', query, body } = {
data = { raw: text };
}
if (!res.ok) {
- const message = data?.message || data?.error || `${path} returned HTTP ${res.status}`;
+ const message = data?.message || data?.error || `three.ws ${path} returned HTTP ${res.status}`;
throw Object.assign(new Error(message), { code: 'upstream_error', status: res.status, body: data });
}
return data;
diff --git a/packages/x402-mcp/src/lib/x402-buyer.js b/packages/x402-mcp/src/lib/x402-buyer.js
index 6e91b7f47..1cbcabca1 100644
--- a/packages/x402-mcp/src/lib/x402-buyer.js
+++ b/packages/x402-mcp/src/lib/x402-buyer.js
@@ -1,6 +1,7 @@
// x402 buyer wiring — pay any x402 endpoint from a local Solana keypair.
//
-// Fully self-custodial standalone: the signer is YOUR key (SOLANA_SECRET_KEY or a
+// Mirrors the canonical three.ws buyer (api/_lib/x402-user-payer.js) but for a
+// self-custodial standalone: the signer is YOUR key (SOLANA_SECRET_KEY or a
// per-call `secret`), not a custodial wallet. Real `@x402/*` libraries do the
// 402 dance and sign the Solana `exact`-scheme payment — nothing is mocked.
//
@@ -13,9 +14,9 @@ import bs58 from 'bs58';
import { SOLANA_DEFAULT_SECRET } from '../config.js';
-// Supported x402 assets. USDC is the always-available default (canonical on
-// Solana + Base). $THREE is a supported optional SPL token (Solana). Used to pick
-// which advertised accept to settle when the caller prefers a specific token.
+// The two main x402 assets. $THREE is the three.ws platform token (Solana SPL);
+// USDC is canonical on Solana + Base. Used to pick which advertised accept to
+// settle when the caller prefers a specific token.
const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
const USDC_MINTS = new Set([
'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // Solana
diff --git a/packages/x402-mcp/src/tools/find-services.js b/packages/x402-mcp/src/tools/find-services.js
index eabebd0a9..0c3e2804e 100644
--- a/packages/x402-mcp/src/tools/find-services.js
+++ b/packages/x402-mcp/src/tools/find-services.js
@@ -1,21 +1,19 @@
-// `find_services` — search an x402 bazaar / discovery API for paid services.
-// Read-only.
+// `find_services` — search the live x402 bazaar for paid services. Read-only.
//
-// Wraps GET /api/bazaar/search on whatever discovery endpoint you point
-// X402_API_BASE at (e.g. https://three.ws, or your own bazaar that merges the
-// public facilitator feeds). Feed a returned `resource` into pay_and_call to use it.
+// Wraps GET /api/bazaar/search, which merges the public facilitator discovery
+// feeds (PayAI + CDP) and ranks them against your query. Feed a returned
+// `resource` into pay_and_call to actually use it.
import { z } from 'zod';
import { apiRequest } from '../lib/api.js';
-import { requireApiBase } from '../config.js';
export const def = {
name: 'find_services',
title: 'Find paid x402 services the agent can call',
annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },
description:
- 'Search a configured x402 bazaar / discovery API for paid services — HTTP APIs and MCP tools. Returns each match with its price, networks, and resource URL. Pass a resource into pay_and_call to use it. Requires X402_API_BASE to point at a discovery endpoint (e.g. https://three.ws). Read-only.',
+ 'Search the live x402 facilitator network (PayAI + Coinbase CDP bazaar) for paid services — HTTP APIs and MCP tools. Returns each match with its price, networks, and resource URL. Pass a resource into pay_and_call to use it. Read-only.',
inputSchema: {
query: z.string().min(1).describe('What you need, e.g. "weather", "image upscale", "token intel".'),
type: z.enum(['http', 'mcp']).default('http').describe('Service kind to search.'),
@@ -24,12 +22,11 @@ export const def = {
limit: z.number().int().min(1).max(100).optional().describe('Max results (default 25).'),
},
async handler(args) {
- const base = requireApiBase('find_services');
const query = String(args?.query ?? '').trim();
const type = args?.type === 'mcp' ? 'mcp' : 'http';
const maxPrice =
args?.max_price_usdc != null ? String(Math.round(Number(args.max_price_usdc) * 1_000_000)) : undefined;
- const data = await apiRequest(base, '/api/bazaar/search', {
+ const data = await apiRequest('/api/bazaar/search', {
query: {
query,
type,
diff --git a/packages/x402-mcp/src/tools/pay-and-call.js b/packages/x402-mcp/src/tools/pay-and-call.js
index ef5f911ea..7454a2eb2 100644
--- a/packages/x402-mcp/src/tools/pay-and-call.js
+++ b/packages/x402-mcp/src/tools/pay-and-call.js
@@ -3,11 +3,9 @@
//
// Two payment modes:
// 1. Self-custodial (default): signs with SOLANA_SECRET_KEY / `secret` arg.
-// Needs only a Solana RPC + key — no external API base.
-// 2. Session-governed (optional): when `session_token` is supplied, routes
-// through a hosted /api/pay/execute endpoint (set X402_API_BASE) — a hosted
-// wallet signs, and the session's budget/allowlist/per-tx policy is enforced
-// remotely. No local key needed. Requires X402_API_BASE.
+// 2. Session-governed: when `session_token` is supplied, routes through the
+// three.ws /api/pay/execute endpoint — the platform wallet signs, and the
+// session's budget/allowlist/per-tx policy is enforced. No key needed.
//
// Guards before any payment: probe the 402 to read the Solana price, refuse if it
// exceeds max_usd or MAX_PAY_USD, and (when REQUIRE_CONFIRM is on) require an
@@ -16,7 +14,7 @@
import { z } from 'zod';
import { buildPayingFetch, decodeSettlement, probeChallenge, isThreeAccept, isUsdcAccept } from '../lib/x402-buyer.js';
-import { MAX_PAY_USD, REQUIRE_CONFIRM, SOLANA_DEFAULT_SECRET, requireApiBase, HTTP_TIMEOUT_MS } from '../config.js';
+import { MAX_PAY_USD, REQUIRE_CONFIRM, SOLANA_DEFAULT_SECRET, THREE_WS_BASE, HTTP_TIMEOUT_MS } from '../config.js';
// Split a challenge's Solana accepts into the two main assets so we can price
// and pay in the caller's chosen token.
@@ -26,7 +24,7 @@ function pickSolanaAccepts(accepts) {
}
// USD value of a USDC accept (6-decimal atomic, or a "$x" string). Returns null
-// when unknown — a non-USD token accept has no USD price (its amount is a token count).
+// when unknown — $THREE accepts have no USD price (their amount is a token count).
function usdFromAccept(a) {
if (!a) return null;
const raw = a.price ?? a.maxAmountRequired ?? a.amount;
@@ -42,7 +40,7 @@ export const def = {
// Moves real funds — irreversible transfer.
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
description:
- 'Call a paid x402 endpoint and settle the payment automatically, then return the result.\n\nTwo modes:\n• Self-custodial (default): signs with SOLANA_SECRET_KEY or `secret` arg — you hold the key. Needs only a Solana RPC + key.\n• Session-governed (optional): pass `session_token` (a Payment Session token from a hosted x402 wallet service) — that service signs on your behalf and enforces the session\'s budget, allowlist, and per-tx cap. No private key required. Requires X402_API_BASE to point at the hosting service. Supports Solana USDC and Base USDC sessions.\n\nPay in USDC (default) or, when the endpoint advertises it, in another supported token such as $THREE (set token:"three"). Bounded by max_usd and the MAX_PAY_USD cap; refuses before any money moves if the price is over the cap. With REQUIRE_CONFIRM on, the call refuses until re-issued with confirm:true.',
+ 'Call a paid x402 endpoint and settle the payment automatically, then return the result.\n\nTwo modes:\n• Self-custodial (default): signs with SOLANA_SECRET_KEY or `secret` arg — you hold the key.\n• Session-governed: pass `session_token` (a three.ws Payment Session token) — the platform wallet signs on your behalf; the session\'s budget, allowlist, and per-tx cap are enforced by the platform. No private key required. Supports Solana USDC and Base USDC sessions.\n\nPay in USDC (default) or, when the endpoint advertises it, in $THREE (set token:"three"). Bounded by max_usd and the MAX_PAY_USD cap; refuses before any money moves if the price is over the cap. With REQUIRE_CONFIRM on, the call refuses until re-issued with confirm:true.',
inputSchema: {
url: z.string().url().describe('The x402 endpoint to pay and call.'),
method: z.enum(['GET', 'POST']).default('GET').describe('HTTP method.'),
@@ -50,11 +48,11 @@ export const def = {
session_token: z
.string()
.optional()
- .describe('Payment Session token from a hosted x402 wallet service. When provided, that service pays — no local key needed. Requires X402_API_BASE. Overrides `secret`.'),
+ .describe('three.ws Payment Session token (pss_…). When provided, the platform wallet pays — no local key needed. Overrides `secret`.'),
token: z
.enum(['usdc', 'three'])
.default('usdc')
- .describe('Settlement token. "usdc" (default) or "three" — the $THREE token; the endpoint must advertise it. Ignored when session_token is set.'),
+ .describe('Settlement token. "usdc" (default) or "three" — the $THREE platform token; the endpoint must advertise it. Ignored when session_token is set.'),
max_usd: z
.number()
.positive()
@@ -68,13 +66,12 @@ export const def = {
const url = String(args?.url ?? '').trim();
const method = args?.method === 'POST' ? 'POST' : 'GET';
- // ── Session-governed mode (optional) ────────────────────────────────
- // When a session_token is provided, delegate everything to a hosted
- // /api/pay/execute endpoint (X402_API_BASE): probing, governance, signing,
- // and settlement. No local wallet needed. Requires X402_API_BASE.
+ // ── Session-governed mode ───────────────────────────────────────────
+ // When a session_token is provided, delegate everything to the three.ws
+ // /api/pay/execute endpoint: probing, governance, signing, and settlement.
+ // No local wallet needed.
const sessionToken = args?.session_token || process.env.PAYMENT_SESSION_TOKEN || '';
if (sessionToken) {
- const apiBase = requireApiBase('Session-governed pay_and_call (session_token)');
const ceiling = Math.min(MAX_PAY_USD, args?.max_usd ?? Infinity);
if (REQUIRE_CONFIRM && args?.confirm !== true) {
@@ -92,7 +89,7 @@ export const def = {
const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);
let res, text;
try {
- res = await fetch(`${apiBase}/api/pay/execute`, {
+ res = await fetch(`${THREE_WS_BASE}/api/pay/execute`, {
method: 'POST',
signal: controller.signal,
headers: { 'content-type': 'application/json', accept: 'application/json' },
diff --git a/packages/x402-mcp/test/registration.test.mjs b/packages/x402-mcp/test/registration.test.mjs
index b52cdc5af..4df5c90fd 100644
--- a/packages/x402-mcp/test/registration.test.mjs
+++ b/packages/x402-mcp/test/registration.test.mjs
@@ -1,4 +1,4 @@
-// Tool-surface invariants for x402-mcp.
+// Tool-surface invariants for @three-ws/x402-mcp.
//
// Importing src/index.js is side-effect-free: the stdio transport only connects
// when the file is the process entry point, and buildServer() needs no signer.
diff --git a/packages/x402-mcp/test/token-select.test.mjs b/packages/x402-mcp/test/token-select.test.mjs
index 5886147c7..cd9f58564 100644
--- a/packages/x402-mcp/test/token-select.test.mjs
+++ b/packages/x402-mcp/test/token-select.test.mjs
@@ -10,7 +10,7 @@ import { filterAcceptsByToken, isThreeAccept, isUsdcAccept } from '../src/lib/x4
const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
const USDC_SOL = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
-// A USDC + $THREE Solana challenge, USDC-first.
+// A USDC + $THREE Solana challenge, USDC-first (the platform's ordering).
const ACCEPTS = [
{ network: 'solana:mainnet', asset: USDC_SOL, amount: '10000', extra: { name: 'USDC', decimals: 6 } },
{ network: 'solana:mainnet', asset: THREE_MINT, amount: '10000000', extra: { name: 'THREE', decimals: 6 } },
diff --git a/packages/x402-server/README.md b/packages/x402-server/README.md
index 85c5c8884..2c2136248 100644
--- a/packages/x402-server/README.md
+++ b/packages/x402-server/README.md
@@ -1,6 +1,10 @@
+<p align="center">
+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>
+</p>
+
<h1 align="center">@three-ws/x402-server</h1>
-<p align="center"><strong>The merchant side of <a href="https://x402.org">x402</a> — turn any HTTP endpoint into a paid one in a few lines. Issue the 402, price the work, verify and settle the payment, optionally take a fee.</strong></p>
+<p align="center"><strong>The merchant side of <a href="https://x402.org">x402</a> — turn any HTTP endpoint into a paid one in a few lines. Issue the 402, price the work, verify and settle the payment, take your fee.</strong></p>
<p align="center">
<a href="https://www.npmjs.com/package/@three-ws/x402-server"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/x402-server?logo=npm&color=cb3837"></a>
@@ -14,7 +18,8 @@
<a href="#quick-start">Quick start</a> ·
<a href="#api">API</a> ·
<a href="#how-it-works">How it works</a> ·
- <a href="#payment">Payment</a>
+ <a href="#payment">Payment</a> ·
+ <a href="https://three.ws">three.ws</a>
</p>
---
@@ -25,39 +30,43 @@
> listing what it `accepts` (asset · amount · network · pay-to) — then, on the
> retry that carries an `X-PAYMENT` header, it verifies the payment, runs your
> handler, settles on-chain, and returns the result with an `X-PAYMENT-RESPONSE`
-> receipt. It speaks two lanes out of the box: **Solana** (facilitator-settled
-> SPL `transferChecked`) and **EVM / Base** (gasless
-> [EIP-3009](https://eips.ethereum.org/EIPS/eip-3009)
-> `transferWithAuthorization`). It is the server twin of any buyer-side x402
-> fetch wrapper — they pay; this charges.
+> receipt. It speaks the two lanes the three.ws rails already run in production:
+> **Solana** (facilitator-settled SPL `transferChecked`) and **EVM / Base**
+> (gasless [EIP-3009](https://eips.ethereum.org/EIPS/eip-3009)
+> `transferWithAuthorization`). It is the server twin of the buyer-side
+> [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch)
+> and [`@three-ws/x402-modal`](https://www.npmjs.com/package/@three-ws/x402-modal) —
+> they pay; this charges.
## Why
x402 revives HTTP `402 Payment Required` as a real payment rail: a server
answers a request with a `402` whose body lists its `accepts[]`, the client
pays, and re-sends the request with an `X-PAYMENT` header. The buyer side is a
-solved problem — drop in a fetch wrapper and it pays. **The seller side is where
-everyone reinvents the same machinery:** build the challenge envelope in the
-exact v2 shape, advertise the right asset/fee-payer per chain, parse the
-`X-PAYMENT` header, call a facilitator's `/verify`, run the work *only after*
-verification, settle *only after* the work succeeds, emit the receipt, and
-(optionally) skim a fee out of the price without double-charging the buyer.
-
-This package is that machinery, done once:
-
-- **One wrapper, a paid route.** `paid({ price, payTo })` emits the 402 and
- gates your handler behind a verified payment. USDC is the default asset — no
- extra config.
+solved problem — drop in a fetch wrapper or the modal and it pays. **The seller
+side is where everyone reinvents the same machinery:** build the challenge
+envelope in the exact v2 shape, advertise the right asset/fee-payer per chain,
+parse the `X-PAYMENT` header, call a facilitator's `/verify`, run the work
+*only after* verification, settle *only after* the work succeeds, emit the
+receipt, and skim a platform fee out of the price without double-charging the
+buyer.
+
+This package is that machinery, done once, the way the three.ws merchant rails
+do it:
+
+- **One wrapper, a paid route.** `paid({ price, asset, payTo })` emits the 402
+ and gates your handler behind a verified payment.
- **Two lanes, one API.** Solana and Base/EVM accepts come from the same config;
the challenge advertises both and the buyer picks.
- **Settle after the work, never before.** Verification gates the handler;
settlement runs after it returns `200`. A failed call moves no funds, so a
retry can't double-charge.
-- **Optional fee without surprise-billing.** A fee is split out of the listed
+- **Fee without surprise-billing.** A platform fee is split out of the listed
price — the buyer's total is never marked up, and the fee ships inert (rate
- `0`, no recipient) until you turn it on.
-- **Optional second asset.** Settle plain USDC, or advertise an additional
- Solana SPL token alongside it (e.g. `$THREE`) so a wallet can choose.
+ `0`, no treasury) until you turn it on.
+
+This is the same flow that powers paid MCP tools and hosted checkout SKUs on
+[three.ws](https://three.ws); the package is its standalone, embeddable home.
## Install
@@ -65,22 +74,22 @@ This package is that machinery, done once:
npm install @three-ws/x402-server
```
-Node 18+ (uses the global `fetch`). Framework-agnostic: works as Express/Connect
-middleware, a Fastify hook, or a bare `(req, res)` handler on Vercel / Node
-`http`.
+Node 18+ (uses the global `fetch` and Web Crypto). Framework-agnostic: works as
+Express/Connect middleware, a Fastify hook, or a bare `(req, res)` handler on
+Vercel / Node `http`. For the buyer side of a test, pair with
+[`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch).
## Quick start
### The one-liner — `paid()`
-Wrap a handler. Unpaid requests get a `402`; paid ones run the handler. USDC is
-the default settlement asset, so you only need a `price` and a `payTo`:
+Wrap a handler. Unpaid requests get a `402`; paid ones run the handler:
```js
import { paid } from '@three-ws/x402-server';
export default paid(
- { price: '10000', payTo: { base: '0xYourPayoutAddress' }, network: ['base'] },
+ { price: '10000', asset: 'usdc', payTo: { solana: 'THREEsynthetic1111…' } },
async (req, res) => {
res.json({ summary: await summarize(req.body.text) });
},
@@ -92,10 +101,6 @@ USDC. The first unpaid `GET`/`POST` returns the challenge; the buyer pays and
re-sends with `X-PAYMENT`; your handler runs once, settlement lands, and the
response carries the on-chain receipt.
-> **Solana note.** A Solana accept also needs a `feePayer` — the facilitator's
-> sponsor account that co-signs the SPL transfer so the buyer pays no SOL gas.
-> Pass it as `feePayer: '<sponsor account>'`. Base/EVM accepts don't need one.
-
### A fuller route — both lanes, a fee, a receipt
```js
@@ -104,15 +109,14 @@ import { paid } from '@three-ws/x402-server';
export default paid(
{
price: '50000', // $0.05 USDC (6-decimal atomics)
- asset: 'usdc', // default — shown here for clarity
+ asset: 'usdc',
payTo: {
- solana: 'YourSolanaPayoutAddress', // SPL pay-to
- base: '0xYourPayoutAddress', // EVM pay-to
+ solana: 'THREEsynthetic1111…', // SPL pay-to
+ base: '0xPlatformPayoutAddress…', // EVM pay-to
},
network: ['solana', 'base'], // advertise both accepts; buyer chooses
- feePayer: 'FacilitatorSponsorAccount', // required for the Solana accept
- feeBps: 250, // optional 2.5% fee, split out of the price
- feeTo: 'YourFeeRecipient',
+ feeBps: 250, // 2.5% platform fee, split out of the price
+ feeTo: 'TREASURYsynthetic1111…',
description: 'Document summarization',
serviceName: 'Acme Summarize',
},
@@ -124,32 +128,6 @@ export default paid(
);
```
-### Optionally advertise a second SPL token ($THREE)
-
-Settlement is USDC by default. If you also want to accept an SPL token on
-Solana, set `acceptThree: true` to add a second Solana accept after the USDC one
-— wallets surface both and the buyer chooses, while a first-accept client still
-settles USDC:
-
-```js
-import { paid } from '@three-ws/x402-server';
-
-export default paid(
- {
- price: '50000', // USDC atomic amount
- payTo: { solana: 'YourSolanaPayoutAddress' },
- feePayer: 'FacilitatorSponsorAccount',
- acceptThree: true, // add a $THREE Solana accept alongside USDC
- threeAmount: '50000000', // optional: distinct $THREE atomic amount (else reuses `price`)
- },
- async (req, res, payment) => res.json({ ok: true, billedTo: payment.payer }),
-);
-```
-
-`$THREE` is an SPL mint, so it's Solana-only — `asset: 'three'` or
-`acceptThree: true` on an EVM-only route throws. To settle *only* $THREE on
-Solana, pass `asset: 'three'` instead of `acceptThree`.
-
### Under the hood — the raw 402 → sign → settle flow
`paid()` wraps four primitives you can drive directly when you don't want the
@@ -165,15 +143,13 @@ import {
export default async function handler(req, res) {
const accepts = [
- { scheme: 'exact', network: 'eip155:8453',
- asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // Base USDC
- payTo: '0xYourPayoutAddress', amount: '50000',
- maxTimeoutSeconds: 60, extra: { name: 'USD Coin', version: '2', decimals: 6 } },
+ { scheme: 'exact', network: 'solana:5eykt…', asset: 'EPjF…USDC', payTo, amount: '50000',
+ maxTimeoutSeconds: 60, extra: { name: 'USDC', decimals: 6, feePayer } },
];
const header = req.headers['x-payment'];
if (!header) {
- // 1 — challenge. Body + base64 PAYMENT-REQUIRED header.
+ // 1 — challenge. Body + base64 PAYMENT-REQUIRED header (Bazaar reads both).
const body = buildChallenge({ resourceUrl: req.url, accepts });
res.statusCode = 402;
res.setHeader('PAYMENT-REQUIRED', Buffer.from(JSON.stringify(body)).toString('base64'));
@@ -194,8 +170,8 @@ export default async function handler(req, res) {
}
```
-The order is fixed: **verify → dispatch → settle**. Settlement is the last step,
-so a handler that throws never charges.
+This is exactly the order the three.ws rails enforce: **verify → dispatch →
+settle**. Settlement is the last step, so a handler that throws never charges.
## API
@@ -203,26 +179,22 @@ so a handler that throws never charges.
Wrap a request handler so it requires payment. Returns a standard `(req, res)`
function — mount it as Express/Connect middleware, a Vercel function, or a Node
-`http` handler. Pass `adapter: fetchAdapter` for a fetch-style
-`(request) => Response` runtime (Workers, Deno, Bun, Next.js route handlers).
+`http` handler.
**Options**
| Option | Type | Default | Notes |
|---|---|---|---|
| `price` | `string` | — (**required**) | Amount in **atomic units** of the asset (`'10000'` = `$0.01` of 6-decimal USDC). |
-| `asset` | `'usdc' \| 'three' \| { solana?, base? }` | `'usdc'` | Settlement asset. `'usdc'` (default) resolves the canonical USDC mint/contract per chain; `'three'` pins the optional `$THREE` SPL mint (Solana-only); an object pins explicit addresses. |
+| `asset` | `'usdc' \| { solana?, base? }` | `'usdc'` | Settlement asset. A string resolves the canonical USDC mint/contract per chain; an object pins explicit addresses. |
| `payTo` | `{ solana?, base? }` | — (**required**) | Pay-to address per lane. At least one chain is required. |
-| `network` | `('solana' \| 'base' \| 'base-sepolia')[]` | from `payTo` | Which accepts to advertise. Solana leads when both are present. |
-| `feePayer` | `string` | — | Facilitator sponsor account that co-signs the Solana transfer. **Required for any Solana accept.** |
-| `acceptThree` | `boolean` | `false` | Also advertise `$THREE` on the Solana lane (a second accept after USDC). |
-| `threeAmount` | `string` | `price` | Atomic `$THREE` amount for the `acceptThree` entry. Omit to reuse `price`. |
-| `feeBps` | `number` | `0` | Optional fee in basis points, **split out of `price`** (≤ `1000` / 10%). `0` = no fee. |
+| `network` | `('solana' \| 'base')[]` | from `payTo` | Which accepts to advertise. Solana leads when both are present. |
+| `feeBps` | `number` | `0` | Platform fee in basis points, **split out of `price`** (≤ `1000` / 10%). `0` = no fee. |
| `feeTo` | `string` | — | Fee recipient. Required when `feeBps > 0` — no recipient, no fee. |
-| `facilitator` | `string` | public default | Override the x402 facilitator base URL used for `/verify` + `/settle`. |
+| `facilitator` | `string` | platform default | Override the x402 facilitator base URL used for `/verify` + `/settle`. |
| `maxTimeoutSeconds` | `number` | `60` | How long the buyer has to land the signed payment. |
-| `description` | `string` | — | Human label for the `resource` in the challenge (shown in wallets). |
-| `serviceName` / `tags` / `iconUrl` | `string` / `string[]` / `string` | — | Discovery metadata echoed into the challenge. |
+| `description` | `string` | — | Human label for the `resource` in the challenge (shown in wallets/the modal). |
+| `serviceName` / `tags` / `iconUrl` | `string` / `string[]` / `string` | — | Bazaar discovery metadata echoed into the challenge. |
| `onSettled` | `(receipt) => void` | — | Fired after a successful settlement — record the call, fire a webhook. |
**Handler** — `(req, res, payment) => unknown`. `payment` is present only on a
@@ -233,8 +205,7 @@ returns its error to the buyer and **skips settlement** — no funds move.
Build the v2 `402` envelope. Returns `{ x402Version, error, resource, accepts,
extensions }`; the same object is what you base64 into the `PAYMENT-REQUIRED`
-header. Accepts the ergonomic `{ price, asset, payTo, ... }` shape above, or a
-pre-built `accepts[]` in the canonical shape:
+header. Accepts the canonical accept shape:
```ts
{ scheme: 'exact', network, asset, payTo, amount, maxTimeoutSeconds,
@@ -256,24 +227,11 @@ returned object is what you base64 into the `X-PAYMENT-RESPONSE` header.
### `feeSplit(priceAtomics, bps, recipient) → { net, fee, recipient } | null`
-Split an optional fee out of the listed price: `fee = floor(price × bps /
+Split a platform fee out of the listed price: `fee = floor(price × bps /
10_000)`, `net = price − fee`. Returns `null` when no fee applies (rate `0`, no
recipient, or a sub-atomic fee) so the buyer is charged the full price and the
creator receives all of it. `bps` is clamped to `[0, 1000]`.
-### `createX402Server(options) → client`
-
-Create a client bound to a facilitator URL / fetch / auth headers, exposing the
-same `buildChallenge` / `verifyPayment` / `settlePayment` / `paid` methods. Use
-it to reuse a facilitator override or a custom `fetch` across many routes:
-
-```js
-import { createX402Server } from '@three-ws/x402-server';
-
-const server = createX402Server({ facilitator: 'https://your-facilitator.example' });
-export default server.paid({ price: '10000', payTo: { base: '0xPayout' }, network: ['base'] }, handler);
-```
-
## How it works
```
@@ -313,17 +271,14 @@ of at least the expected amount, with a confirmation floor against reorgs.
| Base Sepolia | `eip155:84532` | `exact` (EIP-3009) | same | facilitator pays |
Solana leads the `accepts[]` so first-accept clients settle there; advertise
-`network: ['base']` (or both) to lead with EVM.
-
-The default facilitator is PayAI's public x402 facilitator. Override it
-per-route with the `facilitator` option, or globally via the
-`X402_FACILITATOR_URL` environment variable.
+`network: ['base']` (or both) to lead with EVM. The challenge also carries a
+`bazaar` discovery extension so the endpoint is findable in the x402 bazaar.
## Payment
Prices are quoted and charged in **atomic units** of the settlement asset — USDC
is 6-decimal, so `1_000_000` = `$1.00`. The buyer's total is exactly `price`;
-the optional fee is carved *out* of it:
+the platform fee is carved *out* of it:
| `feeBps` | On a `$1.00` (`1000000`) call | Creator nets | Fee |
|---|---|---|---|
@@ -332,19 +287,12 @@ the optional fee is carved *out* of it:
| `1000` (10%, max) | buyer pays `$1.00` | `$0.90` | `$0.10` |
The fee applies **only** when both `feeBps > 0` **and** `feeTo` is set, so an
-unconfigured server charges no fee — the fee feature ships inert and never
+unconfigured server charges nothing — the fee feature ships inert and never
surprise-bills on deploy. On Solana the fee is an extra `transferChecked` in the
*same* transaction the buyer signs (one signature, no custody, atomic); the
-buyer sees and signs it.
-
-### Settlement assets
-
-USDC is the default and needs no extra config. You can additionally advertise an
-SPL token on Solana — this package ships `$THREE`
-(`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) as a built-in option via
-`acceptThree: true` or `asset: 'three'`. Any other mint can be pinned with
-`asset: { solana: '<mint>' }`. SPL tokens are Solana-only; advertising one on an
-EVM lane throws rather than silently falling back to USDC.
+buyer sees and signs it. The only coin this platform promotes is
+[$THREE](https://three.ws) — settlement runs in USDC, and any mint your server
+names is supplied by you at config time.
## Errors & edge cases
@@ -355,22 +303,20 @@ payment, and `paid()` maps every state to the right HTTP status:
|---|---|---|---|
| `payment_required` | 402 | No `X-PAYMENT`, or the header failed `/verify`. | A fresh challenge — pay and retry. |
| `invalid_payment` | 402 | The signed tx doesn't pay the declared amount/asset/recipient. | Re-sign against the advertised accept. |
-| `missing_fee_payer` | 422 | A Solana accept omitted `extra.feePayer`. | Server misconfig — set the `feePayer`. |
+| `missing_fee_payer` | 422 | A Solana accept omitted `extra.feePayer`. | Server misconfig — set `X402_FEE_PAYER_SOLANA`. |
| `unsupported_network` | 400 | Buyer paid a network the route doesn't advertise. | Pick an advertised accept. |
| `facilitator_unreachable` | 502 | The facilitator `/verify` or `/settle` is down. | **No funds moved** — safe to retry. |
| `settle_uncertain` | 502 | Verified + work ran, but settlement status is unknown. | Check on-chain before retrying to avoid double-pay. |
+| `pending` | — | EVM tx not yet mined / below the confirmation floor. | Confirm again shortly. |
Two invariants make these safe: verification runs **before** your handler (a bad
payment never triggers the work), and settlement runs **after** it (a failed
handler never charges). A `429` from your upstream can be retried with the
*same* signed payment, because settlement only happens once the work succeeds.
-All thrown errors are instances of the exported `X402Error` class, carrying a
-stable `.code` and HTTP `.status`.
-
## Examples
-**Express — meter an existing API (USDC on Base)**
+**Express — meter an existing API**
```js
import express from 'express';
@@ -380,7 +326,7 @@ const app = express();
app.use(express.json());
app.post('/v1/embed', paid(
- { price: '2000', payTo: { base: '0xYourPayoutAddress' }, network: ['base'] },
+ { price: '2000', asset: 'usdc', payTo: { solana: 'THREEsynthetic1111…' } },
async (req, res) => res.json({ vector: await embed(req.body.text) }),
));
@@ -393,34 +339,20 @@ app.listen(3000);
import { paid } from '@three-ws/x402-server';
export default paid(
- { price: '100000', payTo: { base: '0xYourPayoutAddress' }, network: ['base'] },
+ { price: '100000', asset: 'usdc', payTo: { base: '0xPayout…' }, network: ['base'] },
async (req, res, payment) => {
res.json({ report: await generate(req.body.topic), billedTo: payment.payer });
},
);
```
-**Fetch-style runtime — Workers / Deno / Next.js route handler**
-
-```js
-import { paid, fetchAdapter } from '@three-ws/x402-server';
-
-export const POST = paid(
- { price: '5000', payTo: { base: '0xYourPayoutAddress' }, network: ['base'], adapter: fetchAdapter },
- async (request, payment) => {
- const body = await request.json();
- return Response.json({ result: await run(body), billedTo: payment.payer });
- },
-);
-```
-
-**Record every paid call**
+**Agent economy — sell a tool, record every call**
```js
export default paid(
{
- price: '5000',
- payTo: { base: '0xYourPayoutAddress' }, network: ['base'],
+ price: '5000', asset: 'usdc',
+ payTo: { solana: 'THREEsynthetic1111…' },
serviceName: 'Pose seeds', tags: ['3d', 'animation'],
onSettled: (receipt) => recordCall(receipt), // feed your dashboard / webhook
},
@@ -428,10 +360,17 @@ export default paid(
);
```
-A buyer running any x402-aware `fetch` wrapper calls any of these with a plain
-`fetch` — the `402` is paid automatically and the result comes back as if the
-endpoint were free.
+A buyer running [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch)
+calls any of these with a plain `fetch` — the `402` is paid automatically and the
+result comes back as if the endpoint were free.
+
+## Related
-## License
+- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — **buyer side.** A `fetch` wrapper that auto-pays the `402` your server here emits.
+- [`@three-ws/x402-modal`](https://www.npmjs.com/package/@three-ws/x402-modal) — **buyer side.** A drop-in browser checkout modal for the same `402`.
+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — a real paid endpoint built on these rails (text/image → 3D GLB).
+- [three.ws merchant console](https://three.ws) — hosted SKUs, storefronts, and settlement dashboards over the same primitives.
+
+---
-MIT
+<p align="center">Built by <a href="https://three.ws">three.ws</a> · The only coin is <a href="https://three.ws">$THREE</a></p>
diff --git a/packages/x402-server/package.json b/packages/x402-server/package.json
index 78cf06226..4bbcc1031 100644
--- a/packages/x402-server/package.json
+++ b/packages/x402-server/package.json
@@ -1,7 +1,7 @@
{
"name": "@three-ws/x402-server",
"version": "0.1.0",
- "description": "The merchant side of x402 — turn any HTTP endpoint into a paid one. Issue 402 challenges, price SKUs, verify and settle the X-PAYMENT header on Solana and Base, and optionally take a fee. Settles USDC by default; advertise an optional SPL token ($THREE) alongside it.",
+ "description": "The merchant side of x402 — turn any HTTP endpoint into a paid one. Issue 402 challenges, price SKUs, verify and settle the X-PAYMENT header on Solana and Base, and take a platform fee. Advertise the two main assets — USDC and $THREE — in one challenge.",
"type": "module",
"main": "./src/index.js",
"module": "./src/index.js",
diff --git a/packages/x402-server/src/http.js b/packages/x402-server/src/http.js
index 9f1a0b23e..6398a3e53 100644
--- a/packages/x402-server/src/http.js
+++ b/packages/x402-server/src/http.js
@@ -1,14 +1,15 @@
-// Zero-dependency HTTP core: resolves the base URL, attaches auth, and maps a
-// JSON error envelope onto typed errors. No external dependencies, so the
-// package runs anywhere fetch exists.
+// Zero-dependency HTTP core shared across the @three-ws/* SDK family.
+// Copied verbatim into each package so every SDK stays dependency-free while
+// resolving the base URL, attaching auth, and mapping the platform's JSON error
+// envelope onto typed errors the same way everywhere.
-export const DEFAULT_BASE_URL = 'https://facilitator.payai.network';
+export const DEFAULT_BASE_URL = 'https://three.ws';
-/** Base error for the x402-server SDK. Carries a stable `code` + HTTP `status`. */
-export class X402Error extends Error {
+/** Base error for every @three-ws/* SDK. Carries a stable `code` + HTTP `status`. */
+export class ThreeWsError extends Error {
constructor(message, { code = 'error', status = null, detail = null, retryAfter = null, body = null } = {}) {
super(message);
- this.name = 'X402Error';
+ this.name = 'ThreeWsError';
this.code = code;
this.status = status;
if (detail) this.detail = detail;
@@ -20,10 +21,10 @@ export class X402Error extends Error {
/**
* Thrown on HTTP 402. The endpoint wants payment before it will do the work.
* `accepts` is the x402 challenge (asset/amount/network/payTo) when present —
- * pass a payment-aware `fetch` (an x402 buyer-side fetch wrapper) to settle it
+ * pass a payment-aware `fetch` (e.g. @three-ws/x402-fetch) to settle it
* automatically, or read `accepts` and pay it yourself.
*/
-export class PaymentRequiredError extends X402Error {
+export class PaymentRequiredError extends ThreeWsError {
constructor(message, opts = {}) {
super(message, { ...opts, code: opts.code || 'payment_required', status: opts.status ?? 402 });
this.name = 'PaymentRequiredError';
@@ -31,9 +32,9 @@ export class PaymentRequiredError extends X402Error {
}
}
-/** Resolve the API origin: explicit option → X402_FACILITATOR_URL env → default. */
+/** Resolve the API origin: explicit option → THREE_WS_BASE_URL env → default. */
export function resolveBaseUrl(baseUrl) {
- const env = typeof process !== 'undefined' && process.env ? process.env.X402_FACILITATOR_URL : null;
+ const env = typeof process !== 'undefined' && process.env ? process.env.THREE_WS_BASE_URL : null;
return String(baseUrl || env || DEFAULT_BASE_URL).replace(/\/+$/, '');
}
@@ -53,7 +54,7 @@ function buildUrl(baseUrl, path, query) {
* Returns parsed JSON on success; throws a typed error on any non-2xx.
*
* @param {object} [opts]
- * @param {string} [opts.baseUrl] API origin (default the public facilitator).
+ * @param {string} [opts.baseUrl] API origin (default https://three.ws).
* @param {typeof fetch} [opts.fetch] fetch implementation (default globalThis.fetch).
* @param {string} [opts.apiKey] bearer token attached as Authorization.
* @param {Record<string,string>} [opts.headers] default headers on every call.
@@ -62,7 +63,7 @@ export function createHttp(opts = {}) {
const baseUrl = resolveBaseUrl(opts.baseUrl);
const fetchImpl = opts.fetch || (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined);
if (typeof fetchImpl !== 'function') {
- throw new X402Error('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });
+ throw new ThreeWsError('No fetch implementation available — run on Node 18+ or pass { fetch }.', { code: 'no_fetch' });
}
const baseHeaders = { accept: 'application/json', ...(opts.headers || {}) };
if (opts.apiKey) baseHeaders.authorization = `Bearer ${opts.apiKey}`;
@@ -80,7 +81,7 @@ export function createHttp(opts = {}) {
res = await fetchImpl(url, init);
} catch (err) {
if (err?.name === 'AbortError') throw err;
- throw new X402Error(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });
+ throw new ThreeWsError(`Network request to ${url.pathname} failed: ${err?.message || err}`, { code: 'network_error' });
}
const text = await res.text();
@@ -98,7 +99,7 @@ export function createHttp(opts = {}) {
if (res.status === 402) {
throw new PaymentRequiredError(message, { code, status: 402, accepts: payload?.accepts ?? null, detail: payload?.detail, body: payload });
}
- throw new X402Error(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });
+ throw new ThreeWsError(message, { code, status: res.status, detail: payload?.detail, retryAfter, body: payload });
};
}
diff --git a/packages/x402-server/src/index.d.ts b/packages/x402-server/src/index.d.ts
index be6d1b929..5ea1ffc41 100644
--- a/packages/x402-server/src/index.d.ts
+++ b/packages/x402-server/src/index.d.ts
@@ -1,6 +1,6 @@
// Type definitions for @three-ws/x402-server
-export declare class X402Error extends Error {
+export declare class ThreeWsError extends Error {
name: string;
code: string;
status: number | null;
@@ -9,7 +9,7 @@ export declare class X402Error extends Error {
body: unknown;
}
-export declare class PaymentRequiredError extends X402Error {
+export declare class PaymentRequiredError extends ThreeWsError {
accepts: unknown | null;
}
@@ -42,7 +42,7 @@ export interface Accept {
};
}
-/** The split of an optional fee carved OUT of the listed price. */
+/** The split of a platform fee carved OUT of the listed price. */
export interface FeeSplit {
price: string;
net: string;
@@ -59,9 +59,8 @@ export interface PayTo {
}
/**
- * Settlement asset. `'usdc'` (the default) resolves canonical USDC per lane;
- * `'three'` resolves the optional $THREE SPL token (Solana-only); or pin
- * explicit addresses per lane.
+ * Settlement asset. `'usdc'` resolves canonical USDC per lane; `'three'` resolves
+ * the $THREE platform token (Solana-only); or pin explicit addresses per lane.
*/
export type Asset = 'usdc' | 'three' | { solana?: string; base?: string };
@@ -75,8 +74,8 @@ export interface BuildChallengeOptions {
/** The Solana facilitator sponsor account (required for a Solana accept). */
feePayer?: string;
/**
- * Optionally advertise $THREE alongside USDC on the Solana lane (a second
- * accept, pushed after USDC) so a wallet can settle either. Off by default.
+ * Advertise $THREE alongside USDC on the Solana lane (a second accept, pushed
+ * after USDC). The platform's two main x402 assets in one challenge.
*/
acceptThree?: boolean;
/**
@@ -84,7 +83,7 @@ export interface BuildChallengeOptions {
* the USDC `price` value.
*/
threeAmount?: string | number;
- /** Optional fee in basis points, split OUT of price (≤ 1000 / 10%). */
+ /** Platform fee in basis points, split OUT of price (≤ 1000 / 10%). */
feeBps?: number;
/** Fee recipient. Required when feeBps > 0. */
feeTo?: string;
@@ -200,7 +199,7 @@ export declare function settlePayment(args: { verified: Verified } | Verified):
export declare function paid(opts: PaidOptions, handler: Function): (...args: any[]) => Promise<unknown>;
/**
- * Split an optional fee OUT of the listed price. Returns null when no fee applies
+ * Split a platform fee OUT of the listed price. Returns null when no fee applies
* (rate 0, no recipient, or a sub-atomic fee). `bps` is clamped to [0, 1000].
*/
export declare function feeSplit(priceAtomics: bigint | number | string, bps: number, recipient: string): FeeSplit | null;
diff --git a/packages/x402-server/src/index.js b/packages/x402-server/src/index.js
index 7d476b277..ee517be5b 100644
--- a/packages/x402-server/src/index.js
+++ b/packages/x402-server/src/index.js
@@ -2,57 +2,62 @@
//
// Framework-agnostic merchant middleware + primitives that issue a 402 Payment
// Required challenge, verify the buyer's X-PAYMENT header against a facilitator,
-// run the work, settle on-chain, and emit the X-PAYMENT-RESPONSE receipt — in
-// the order x402 requires: verify → dispatch → settle. This is NOT the buyer
-// side: it never signs or pays. Pair it with any buyer-side x402 fetch wrapper
-// in a test.
+// run the work, settle on-chain, and emit the X-PAYMENT-RESPONSE receipt — the
+// exact verify → dispatch → settle order the three.ws rails enforce in
+// production. This is NOT the buyer side: it never signs or pays. Pair it with
+// the buyer-side @three-ws/x402-fetch in a test.
//
-// Defaults: USDC settlement on Solana and Base, against a public facilitator,
-// with zero extra configuration. $THREE (a Solana SPL token) is an optional
-// settlement asset you can advertise alongside USDC.
+// Every wire shape here is grounded in the real platform source:
+// - challenge envelope + accept entries → api/_lib/x402-spec.js (build402Body /
+// paymentRequirements)
+// - facilitator /verify + /settle bodies → api/_lib/x402-spec.js
+// (callFacilitator: { x402Version, paymentPayload, paymentRequirements })
+// - fee split (clamp 10%, carved out of price, never marks up the buyer) →
+// api/_lib/marketplace-platform-fee.js
//
// See README.md for the full reference.
-import { createHttp, X402Error } from './http.js';
+import { createHttp, ThreeWsError } from './http.js';
-export { X402Error, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';
+export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';
-// v2 x402 wire format version.
+// v2 wire format (api/_lib/x402-spec.js X402_VERSION).
export const X402_VERSION = 2;
-// CAIP-2 network IDs. Solana mainnet uses the truncated genesis-block hash; EVM
-// uses eip155:<chainId>.
+// CAIP-2 network IDs, mirrored from x402-spec.js. Solana mainnet uses the
+// truncated genesis-block hash; EVM uses eip155:<chainId>.
export const NETWORK_SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
export const NETWORK_BASE_MAINNET = 'eip155:8453';
export const NETWORK_BASE_SEPOLIA = 'eip155:84532';
-// Default facilitator that settles Solana + Base. PayAI runs a public x402
-// facilitator; override per-route with the `facilitator` option or globally via
-// the X402_FACILITATOR_URL env var.
+// The facilitator that settles Solana + Base by default. PayAI's public
+// facilitator is the platform default in api/_lib/env.js
+// (X402_FACILITATOR_URL_SOLANA / _BASE both fall back to it). Override per-route
+// with the `facilitator` option.
export const DEFAULT_FACILITATOR_URL = 'https://facilitator.payai.network';
-// Hard ceiling on the optional fee — a guard so a fat-fingered config can never
-// charge an absurd fee.
+// Hard ceiling on the platform fee — a guard so a fat-fingered config can never
+// charge an absurd fee (api/_lib/marketplace-platform-fee.js MAX_FEE_BPS).
export const MAX_FEE_BPS = 1000; // 10%
-// Canonical USDC addresses per lane. `asset: 'usdc'` (the default) resolves to
-// these; pin explicit addresses with `asset: { solana, base }`.
+// Canonical USDC addresses per lane (api/_lib/env.js defaults). `asset: 'usdc'`
+// resolves to these; pin explicit addresses with `asset: { solana, base }`.
const CANONICAL_USDC = {
solana: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
base: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
};
-// $THREE — an optional Solana SPL settlement token you can advertise alongside
-// USDC. Solana-only (it's an SPL mint). `asset: 'three'` resolves to it;
-// `acceptThree: true` advertises it next to USDC on the Solana lane. 6 decimals.
-// Entirely opt-in: leave it off and the server settles plain USDC.
+// $THREE — the three.ws platform token, the second main x402 settlement asset
+// alongside USDC. Solana-only (it's an SPL mint). `asset: 'three'` resolves to
+// it; `acceptThree: true` advertises it next to USDC on the Solana lane, exactly
+// as api/_lib/x402-spec.js does server-side. 6 decimals.
const CANONICAL_THREE = {
solana: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
};
const THREE_DECIMALS = 6;
// Maps the ergonomic lane name → CAIP-2 network id. Solana leads when both are
-// present, so first-accept clients settle there.
+// present, matching paymentRequirements()'s Solana-first ordering.
const LANE_NETWORK = {
solana: NETWORK_SOLANA_MAINNET,
base: NETWORK_BASE_MAINNET,
@@ -81,6 +86,7 @@ export function createX402Server(options = {}) {
/**
* Build the v2 402 envelope: `{ x402Version, error, resource, accepts,
* extensions }` — the same object you base64 into the PAYMENT-REQUIRED header.
+ * Mirrors api/_lib/x402-spec.js build402Body + paymentRequirements.
*/
function buildChallenge(opts = {}) {
return buildChallengeEnvelope(opts);
@@ -91,11 +97,11 @@ export function createX402Server(options = {}) {
* accepts[] you advertised) via the facilitator's /verify. Returns
* `{ ok: true, payer, accept, raw }` on success, or `{ ok: false, code,
* reason, body }` (a fresh 402 body) on a rejected/under-paid payment.
- * **Run the work only when `ok`.**
+ * **Run the work only when `ok`.** Mirrors x402-spec.js verifyPayment.
*/
async function verifyPayment(args = {}, expected) {
// Two call shapes: verifyPayment({ paymentHeader, requirements }) and the
- // positional verifyPayment(xPaymentHeader, expected).
+ // README's positional verifyPayment(xPaymentHeader, expected).
let header;
let requirements;
let signal;
@@ -114,7 +120,7 @@ export function createX402Server(options = {}) {
* Settle a verified payment on-chain via the facilitator's /settle and return
* the receipt `{ network, payer, transaction, raw }` — the object you base64
* into the X-PAYMENT-RESPONSE header. Run this AFTER the work succeeds, never
- * before.
+ * before. Mirrors x402-spec.js settlePayment.
*/
async function settlePayment(args = {}) {
const verified = args.verified || args;
@@ -136,7 +142,7 @@ export function createX402Server(options = {}) {
}
// A lazily-created shared client backs the zero-config default functions, so
-// `import { paid }` works with no setup.
+// `import { paid }` works with no setup (mirrors forge's defaultClient()).
let shared = null;
function defaultClient() {
return (shared ||= createX402Server());
@@ -161,20 +167,20 @@ export function paid(opts, handler) {
// ── Challenge construction ───────────────────────────────────────────────
-// Build one v2 accept entry per advertised lane, Solana-first. Each entry
-// carries scheme/network/amount/asset/payTo/maxTimeoutSeconds + the per-lane
-// `extra` block (Solana needs a feePayer; Base pins the EIP-712 domain name
-// "USD Coin").
+// Build one v2 accept entry per advertised lane, in the platform's Solana-first
+// order. Each entry carries scheme/network/amount/asset/payTo/maxTimeoutSeconds
+// + the per-lane `extra` block (Solana needs a feePayer; Base pins the EIP-712
+// domain name "USD Coin"). Grounded in paymentRequirements().
function buildAccepts({ price, asset, payTo, network, feePayer, maxTimeoutSeconds, resourceUrl, acceptThree, threeAmount }) {
if (price === undefined || price === null || String(price) === '') {
- throw new X402Error('buildChallenge() needs a `price` in atomic units.', { code: 'invalid_input' });
+ throw new ThreeWsError('buildChallenge() needs a `price` in atomic units.', { code: 'invalid_input' });
}
const amount = String(price);
if (!/^\d+$/.test(amount)) {
- throw new X402Error(`price must be a whole atomic amount string, got "${amount}".`, { code: 'invalid_input' });
+ throw new ThreeWsError(`price must be a whole atomic amount string, got "${amount}".`, { code: 'invalid_input' });
}
if (!payTo || typeof payTo !== 'object') {
- throw new X402Error('buildChallenge() needs `payTo` with at least one lane (solana / base).', { code: 'invalid_input' });
+ throw new ThreeWsError('buildChallenge() needs `payTo` with at least one lane (solana / base).', { code: 'invalid_input' });
}
// Which lanes to advertise: explicit `network`, else every lane present in
@@ -188,29 +194,29 @@ function buildAccepts({ price, asset, payTo, network, feePayer, maxTimeoutSecond
if (acceptThree) {
threeAmt = threeAmount === undefined || threeAmount === null || String(threeAmount) === '' ? amount : String(threeAmount);
if (!/^\d+$/.test(threeAmt)) {
- throw new X402Error(`threeAmount must be a whole atomic amount string, got "${threeAmt}".`, { code: 'invalid_input' });
+ throw new ThreeWsError(`threeAmount must be a whole atomic amount string, got "${threeAmt}".`, { code: 'invalid_input' });
}
}
const out = [];
for (const lane of lanes) {
if (!LANES.includes(lane)) {
- throw new X402Error(`Unknown network lane "${lane}". Expected one of: ${LANES.join(', ')}.`, { code: 'invalid_input' });
+ throw new ThreeWsError(`Unknown network lane "${lane}". Expected one of: ${LANES.join(', ')}.`, { code: 'invalid_input' });
}
const to = payTo[lane];
if (!to) {
- throw new X402Error(`network includes "${lane}" but payTo.${lane} is not set.`, { code: 'invalid_input' });
+ throw new ThreeWsError(`network includes "${lane}" but payTo.${lane} is not set.`, { code: 'invalid_input' });
}
out.push(buildAccept({ lane, amount, asset, payTo: to, feePayer, maxTimeoutSeconds, resourceUrl }));
- // When opted in, $THREE rides immediately after the USDC Solana accept, so
- // a wallet's token chooser surfaces both while a first-accept client still
- // settles the default USDC.
+ // $THREE rides immediately after the USDC Solana accept — the platform's
+ // two main assets, Solana-first — so a wallet's token chooser surfaces both
+ // while a first-accept client still settles USDC. Mirrors paymentRequirements().
if (lane === 'solana' && acceptThree) {
out.push(buildAccept({ lane: 'solana', amount: threeAmt, asset: 'three', payTo: to, feePayer, maxTimeoutSeconds, resourceUrl }));
}
}
if (!out.length) {
- throw new X402Error('No payable lanes — set payTo for solana and/or base.', { code: 'invalid_input' });
+ throw new ThreeWsError('No payable lanes — set payTo for solana and/or base.', { code: 'invalid_input' });
}
return out;
}
@@ -231,7 +237,7 @@ function buildAccept({ lane, amount, asset, payTo, feePayer, maxTimeoutSeconds,
// PayAI's Solana facilitator rejects with `missing_fee_payer` unless the
// accept advertises the sponsor account that co-signs the SPL transfer.
if (!feePayer) {
- throw new X402Error('Solana accepts need a `feePayer` (the facilitator sponsor account) — set X402_FEE_PAYER_SOLANA.', { code: 'missing_fee_payer' });
+ throw new ThreeWsError('Solana accepts need a `feePayer` (the facilitator sponsor account) — set X402_FEE_PAYER_SOLANA.', { code: 'missing_fee_payer' });
}
// `extra` names the settlement token — $THREE when this is a THREE accept,
// USDC otherwise — so a wallet labels the choice correctly.
@@ -253,7 +259,7 @@ function resolveAsset(asset, lane) {
// $THREE is an SPL mint — Solana only. Advertising it on an EVM lane is a
// misconfiguration, not a silent USDC fallback.
if (lane !== 'solana') {
- throw new X402Error(`$THREE settlement is Solana-only — lane "${lane}" can't advertise THREE.`, { code: 'invalid_input' });
+ throw new ThreeWsError(`$THREE settlement is Solana-only — lane "${lane}" can't advertise THREE.`, { code: 'invalid_input' });
}
return CANONICAL_THREE.solana;
}
@@ -309,8 +315,8 @@ function buildChallengeEnvelope({
extensions,
};
- // Surface the optional fee plan when configured — split out of the price,
- // never marked up onto the buyer. `null` means no fee applies (see feeSplit).
+ // Surface the fee plan when configured — split out of the price, never marked
+ // up onto the buyer. `null` means no fee applies (see feeSplit).
if (feeBps != null && feeTo) {
envelope.fee = feeSplit(list[0]?.amount ?? price, feeBps, feeTo);
}
@@ -320,11 +326,12 @@ function buildChallengeEnvelope({
// ── Fee split ────────────────────────────────────────────────────────────
/**
- * Split an optional fee OUT of the listed price: `fee = floor(price × bps /
+ * Split a platform fee OUT of the listed price: `fee = floor(price × bps /
* 10_000)`, `net = price − fee`. The buyer's total is never marked up — they
- * pay `price`, the creator nets `net`, the fee recipient receives `fee`. Returns
+ * pay `price`, the creator nets `net`, the treasury receives `fee`. Returns
* `null` when no fee applies (rate 0, no recipient, or a sub-atomic fee) so the
* creator receives the whole price. `bps` is clamped to `[0, MAX_FEE_BPS]`.
+ * Mirrors api/_lib/marketplace-platform-fee.js (resolveMarketplaceFee).
*
* @param {bigint|number|string} priceAtomics
* @param {number} bps
@@ -365,35 +372,35 @@ function clampBps(bps) {
function decodePaymentHeader(header) {
if (!header) {
- throw new X402Error('X-PAYMENT header is required.', { code: 'payment_required', status: 402 });
+ throw new ThreeWsError('X-PAYMENT header is required.', { code: 'payment_required', status: 402 });
}
let json;
try {
json = base64Decode(String(header));
} catch (err) {
- throw new X402Error(`X-PAYMENT base64 decode failed: ${err?.message || err}`, { code: 'invalid_payment', status: 400 });
+ throw new ThreeWsError(`X-PAYMENT base64 decode failed: ${err?.message || err}`, { code: 'invalid_payment', status: 400 });
}
let payload;
try {
payload = JSON.parse(json);
} catch (err) {
- throw new X402Error(`X-PAYMENT JSON parse failed: ${err?.message || err}`, { code: 'invalid_payment', status: 400 });
+ throw new ThreeWsError(`X-PAYMENT JSON parse failed: ${err?.message || err}`, { code: 'invalid_payment', status: 400 });
}
if (!payload || typeof payload !== 'object') {
- throw new X402Error('X-PAYMENT must decode to a JSON object.', { code: 'invalid_payment', status: 400 });
+ throw new ThreeWsError('X-PAYMENT must decode to a JSON object.', { code: 'invalid_payment', status: 400 });
}
return payload;
}
// Match the decoded payload to one of the offered requirements by network,
-// falling back to the first entry. The facilitator does the deep
-// EIP-712/Permit2 matching for the EVM path.
+// falling back to the first entry. Mirrors x402-spec.js selectRequirement's
+// non-EVM path (the facilitator does the deep EIP-712/Permit2 matching).
function selectRequirement(paymentPayload, requirements) {
const network = paymentPayload?.network || paymentPayload?.accepted?.network;
if (network) {
const found = requirements.find((r) => r.network === network);
if (!found) {
- throw new X402Error(`payment network "${network}" is not offered by this resource.`, { code: 'unsupported_network', status: 400 });
+ throw new ThreeWsError(`payment network "${network}" is not offered by this resource.`, { code: 'unsupported_network', status: 400 });
}
return found;
}
@@ -404,7 +411,7 @@ async function runVerify({ request, paymentHeader, requirements, signal }) {
const all = Array.isArray(requirements) ? requirements : [requirements];
const payable = all.filter(Boolean);
if (!payable.length) {
- throw new X402Error('verifyPayment() needs the `requirements` (your accepts[]) to match against.', { code: 'invalid_input' });
+ throw new ThreeWsError('verifyPayment() needs the `requirements` (your accepts[]) to match against.', { code: 'invalid_input' });
}
let paymentPayload;
@@ -433,7 +440,7 @@ async function runVerify({ request, paymentHeader, requirements, signal }) {
if (!result || result.isValid !== true) {
const reason = result?.invalidReason || 'payment rejected by facilitator';
- return rejected(new X402Error(`payment rejected: ${reason}`, { code: 'invalid_payment', status: 402 }), payable);
+ return rejected(new ThreeWsError(`payment rejected: ${reason}`, { code: 'invalid_payment', status: 402 }), payable);
}
return {
@@ -452,7 +459,7 @@ async function runSettle({ request, verified, signal }) {
const paymentPayload = verified?.paymentPayload;
const requirement = verified?.requirement || verified?.accept;
if (!requirement || !paymentPayload) {
- throw new X402Error('settlePayment() requires the object returned by verifyPayment().', { code: 'invalid_input' });
+ throw new ThreeWsError('settlePayment() requires the object returned by verifyPayment().', { code: 'invalid_input' });
}
let result;
@@ -469,16 +476,16 @@ async function runSettle({ request, verified, signal }) {
}
if (!result || result.success !== true) {
- throw new X402Error(`settle failed: ${result?.errorReason || 'unknown reason'}`, { code: 'settle_failed', status: 502, body: result });
+ throw new ThreeWsError(`settle failed: ${result?.errorReason || 'unknown reason'}`, { code: 'settle_failed', status: 502, body: result });
}
// Cross-check the facilitator's claimed network/payer against what we verified
- // (defense-in-depth against a misbehaving facilitator).
+ // (defense-in-depth, mirrors x402-spec.js settlePayment).
if (result.network && requirement.network && result.network !== requirement.network) {
- throw new X402Error(`facilitator /settle network mismatch: requested ${requirement.network}, got ${result.network}.`, { code: 'facilitator_bad_response', status: 502 });
+ throw new ThreeWsError(`facilitator /settle network mismatch: requested ${requirement.network}, got ${result.network}.`, { code: 'facilitator_bad_response', status: 502 });
}
if (verified.payer && result.payer && String(result.payer).toLowerCase() !== String(verified.payer).toLowerCase()) {
- throw new X402Error(`facilitator /settle payer mismatch: verified ${verified.payer}, settled ${result.payer}.`, { code: 'facilitator_bad_response', status: 502 });
+ throw new ThreeWsError(`facilitator /settle payer mismatch: verified ${verified.payer}, settled ${result.payer}.`, { code: 'facilitator_bad_response', status: 502 });
}
return {
@@ -511,11 +518,11 @@ function rejected(err, requirements) {
// rejected payment. `/verify` failures mean no funds moved; `/settle` failures
// are uncertain (verified + work ran).
function mapFacilitatorError(err, path, fallbackCode = 'facilitator_unreachable') {
- if (err instanceof X402Error && err.code !== 'network_error' && err.status && err.status < 500) {
+ if (err instanceof ThreeWsError && err.code !== 'network_error' && err.status && err.status < 500) {
return err;
}
const code = err?.code === 'network_error' ? fallbackCode : (err?.code || fallbackCode);
- return new X402Error(`facilitator ${path} failed: ${err?.message || err}`, {
+ return new ThreeWsError(`facilitator ${path} failed: ${err?.message || err}`, {
code: fallbackCode === 'settle_uncertain' ? 'settle_uncertain' : code,
status: 502,
body: err?.body ?? null,
@@ -530,7 +537,7 @@ function mapFacilitatorError(err, path, fallbackCode = 'facilitator_unreachable'
function buildPaidHandler({ buildChallenge, verifyPayment, settlePayment }, opts = {}, handler) {
if (typeof handler !== 'function') {
- throw new X402Error('paid(options, handler) needs a handler function.', { code: 'invalid_input' });
+ throw new ThreeWsError('paid(options, handler) needs a handler function.', { code: 'invalid_input' });
}
const {
price,
@@ -553,7 +560,7 @@ function buildPaidHandler({ buildChallenge, verifyPayment, settlePayment }, opts
// Validate the fee config up front: a fee needs both a rate and a recipient,
// or it ships inert (rate 0 → no fee, no surprise billing).
if (feeBps > 0 && !feeTo) {
- throw new X402Error('feeBps > 0 requires feeTo (the fee recipient) — no recipient, no fee.', { code: 'invalid_input' });
+ throw new ThreeWsError('feeBps > 0 requires feeTo (the fee recipient) — no recipient, no fee.', { code: 'invalid_input' });
}
// A route-scoped server when a custom facilitator is set; else the shared one.
diff --git a/packages/x402-server/test/x402-server.test.js b/packages/x402-server/test/x402-server.test.js
index 25ecbc994..6dcade319 100644
--- a/packages/x402-server/test/x402-server.test.js
+++ b/packages/x402-server/test/x402-server.test.js
@@ -5,14 +5,15 @@ import {
buildChallenge,
feeSplit,
fetchAdapter,
- X402Error,
+ ThreeWsError,
NETWORK_SOLANA_MAINNET,
NETWORK_BASE_MAINNET,
} from '../src/index.js';
// A scripted fetch double: each call shifts the next queued response and records
// the request. No network, no real facilitator — we assert on request shaping
-// and response parsing, which is all the SDK is responsible for.
+// and response parsing, which is all the SDK is responsible for. (Copied
+// verbatim from @three-ws/forge's test harness.)
function stubFetch(responses) {
const calls = [];
const queue = [...responses];
@@ -47,17 +48,17 @@ test('buildChallenge() emits the exact v2 accepts[] envelope', () => {
asset: 'usdc',
payTo: { solana: SYNTH_SOLANA_PAYTO, base: SYNTH_BASE_PAYTO },
feePayer: SYNTH_SOLANA_FEEPAYER,
- resourceUrl: 'https://api.example.com/api/thing',
+ resourceUrl: 'https://three.ws/api/thing',
description: 'Doc summarize',
});
assert.equal(challenge.x402Version, 2);
assert.equal(challenge.error, 'X-PAYMENT header is required');
- assert.equal(challenge.resource.url, 'https://api.example.com/api/thing');
+ assert.equal(challenge.resource.url, 'https://three.ws/api/thing');
assert.equal(challenge.resource.description, 'Doc summarize');
assert.equal(challenge.accepts.length, 2);
- // Solana leads (Solana-first ordering) and carries the fee payer.
+ // Solana leads (platform Solana-first ordering) and carries the fee payer.
const sol = challenge.accepts[0];
assert.equal(sol.scheme, 'exact');
assert.equal(sol.network, NETWORK_SOLANA_MAINNET);
@@ -89,7 +90,7 @@ test('buildChallenge() advertises only the requested lane', () => {
const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
-test('acceptThree adds an optional $THREE Solana accept after the default USDC', () => {
+test('acceptThree adds a $THREE Solana accept after USDC (both main assets)', () => {
const challenge = buildChallenge({
price: '10000',
payTo: { solana: SYNTH_SOLANA_PAYTO, base: SYNTH_BASE_PAYTO },
@@ -136,7 +137,7 @@ test("asset: 'three' pins the $THREE mint on Solana", () => {
test("asset: 'three' on an EVM lane is rejected (Solana-only)", () => {
assert.throws(
() => buildChallenge({ price: '10000', asset: 'three', payTo: { base: SYNTH_BASE_PAYTO }, network: ['base'] }),
- (err) => err instanceof X402Error && err.code === 'invalid_input',
+ (err) => err instanceof ThreeWsError && err.code === 'invalid_input',
);
});
@@ -144,7 +145,7 @@ test('a Solana accept without a feePayer is rejected with missing_fee_payer', ()
assert.throws(
() => buildChallenge({ price: '1000', payTo: { solana: SYNTH_SOLANA_PAYTO } }),
(e) => {
- assert.ok(e instanceof X402Error);
+ assert.ok(e instanceof ThreeWsError);
assert.equal(e.code, 'missing_fee_payer');
return true;
},
@@ -211,7 +212,7 @@ test('a facilitator outage on /verify is a typed 502, never a rejected payment',
const accepts = buildChallenge({ price: '1000', payTo: { base: SYNTH_BASE_PAYTO }, network: ['base'] }).accepts;
const header = xPaymentHeader({ network: NETWORK_BASE_MAINNET, payload: { authorization: { value: '1000' } } });
await assert.rejects(() => server.verifyPayment({ paymentHeader: header, requirements: accepts }), (e) => {
- assert.ok(e instanceof X402Error);
+ assert.ok(e instanceof ThreeWsError);
assert.equal(e.status, 502);
return true;
});
@@ -244,7 +245,7 @@ test('paid() returns a 402 challenge when no X-PAYMENT header is present', async
);
const captured = { headers: {}, body: null, ended: false };
- const req = { url: '/api/thing', headers: { host: 'api.example.com' } };
+ const req = { url: '/api/thing', headers: { host: 'three.ws' } };
const res = {
statusCode: 200,
writableEnded: false,
@@ -281,7 +282,7 @@ test('paid() verifies, runs the handler, then settles on a paid call', async ()
);
const header = xPaymentHeader({ network: NETWORK_BASE_MAINNET, payload: { authorization: { value: '10000', to: SYNTH_BASE_PAYTO } } });
- const req = { url: '/api/thing', headers: { host: 'api.example.com', 'x-payment': header } };
+ const req = { url: '/api/thing', headers: { host: 'three.ws', 'x-payment': header } };
const res = { statusCode: 200, writableEnded: false, setHeader() {}, end() { this.writableEnded = true; } };
const receipt = await handler(req, res);
@@ -300,7 +301,7 @@ test('paid() supports a fetch-style adapter (Request → Response)', async () =>
{ price: '5000', payTo: { base: SYNTH_BASE_PAYTO }, network: ['base'], adapter: fetchAdapter },
async () => new Response(JSON.stringify({ ok: true })),
);
- const request = new Request('https://api.example.com/api/thing');
+ const request = new Request('https://three.ws/api/thing');
const response = await handler(request);
assert.equal(response.status, 402);
assert.ok(response.headers.get('PAYMENT-REQUIRED'));
diff --git a/scripts/extract-package.sh b/scripts/extract-package.sh
index d73f616e6..54d494c76 100755
--- a/scripts/extract-package.sh
+++ b/scripts/extract-package.sh
@@ -50,31 +50,14 @@ git filter-repo --force --subdirectory-filter "$PREFIX"
# Land on a clean `main` branch.
git branch -m main 2>/dev/null || git checkout -q -b main
-# Publishing identity for the standalone package. SCOPE rewrites the npm scope
-# (the monorepo keeps @three-ws so its internal imports don't break); AUTHOR sets
-# the maintainer. Defaults: @nirholas scope, nirholas author.
-SCOPE="${SCOPE:-@nirholas}"
-AUTHOR_NAME="${AUTHOR_NAME:-nirholas}"
-echo "==> [3/5] rewrite package.json identity -> $SCOPE/* author:$AUTHOR_NAME repo:$OWNER/$REPO_NAME"
-OWNER="$OWNER" REPO_NAME="$REPO_NAME" SCOPE="$SCOPE" AUTHOR_NAME="$AUTHOR_NAME" node -e '
+echo "==> [3/5] rewrite package.json repository/bugs -> $OWNER/$REPO_NAME"
+OWNER="$OWNER" REPO_NAME="$REPO_NAME" node -e '
const fs = require("fs");
const p = JSON.parse(fs.readFileSync("package.json", "utf8"));
const owner = process.env.OWNER, repo = process.env.REPO_NAME;
- const scope = process.env.SCOPE, author = process.env.AUTHOR_NAME;
- // Re-scope the npm name: @three-ws/x402-fetch -> @nirholas/x402-fetch.
- // VS Code extensions cannot be scoped — they use a plain name + publisher.
- if (typeof p.name === "string") {
- if (p.engines && p.engines.vscode) {
- p.name = p.name.replace(/^@[^/]+\//, "");
- p.publisher = author.replace(/^@/, "");
- } else if (p.name.startsWith("@")) {
- p.name = p.name.replace(/^@[^/]+\//, scope + "/");
- }
- }
- p.author = author;
p.repository = { type: "git", url: `git+https://github.com/${owner}/${repo}.git` };
p.bugs = { url: `https://github.com/${owner}/${repo}/issues` };
- p.homepage = `https://github.com/${owner}/${repo}#readme`;
+ if (!p.homepage) p.homepage = `https://github.com/${owner}/${repo}#readme`;
fs.writeFileSync("package.json", JSON.stringify(p, null, "\t") + "\n");
'
diff --git a/x402-modal-sdk/README.md b/x402-modal-sdk/README.md
index 158d3e60d..ee3ffef93 100644
--- a/x402-modal-sdk/README.md
+++ b/x402-modal-sdk/README.md
@@ -190,10 +190,7 @@ Bound elements dispatch bubbling `CustomEvent`s:
## Configuration
-All fields are optional and the defaults are vendor-neutral — no backend origin,
-no footer attribution, no builder-code echo — so the modal settles a `402` from
-any origin with zero configuration. Configure only to brand it or repoint the
-Solana checkout backend.
+All fields are optional; the defaults reproduce the hosted three.ws modal.
```js
configure({
@@ -299,10 +296,11 @@ fee-payer.
a React/Vue/Svelte handler, or drop the `/global` script and use `data-*`
buttons.
-**Where does this run in production?** Anywhere you have an x402-protected
-endpoint — the modal is self-contained and needs no vendor backend for the EVM
-path. ([three.ws](https://three.ws) is one deployment that uses it.)
+**Where does this run in production?** This is the same modal that powers
+payments on [three.ws](https://three.ws); the package is its standalone,
+configurable home.
## License
-[Apache-2.0](./LICENSE) © three.ws.
+[Apache-2.0](./LICENSE) © three.ws. Part of the [three.ws](https://three.ws)
+platform for building, animating, rigging, and monetizing 3D AI agents.
diff --git a/x402-modal-sdk/build.mjs b/x402-modal-sdk/build.mjs
index 19ef8a96e..2bb4db226 100644
--- a/x402-modal-sdk/build.mjs
+++ b/x402-modal-sdk/build.mjs
@@ -1,6 +1,6 @@
#!/usr/bin/env node
/**
- * Build the package.
+ * Build @three-ws/x402-modal.
*
* Two artifacts:
* dist/x402-modal.mjs — ESM, side-effect-free. The public API (`pay`,
@@ -14,7 +14,7 @@
*/
import { build } from 'esbuild';
-import { mkdirSync, readFileSync } from 'node:fs';
+import { mkdirSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -22,16 +22,11 @@ const here = dirname(fileURLToPath(import.meta.url));
const outDir = resolve(here, 'dist');
mkdirSync(outDir, { recursive: true });
-// Build a banner from package metadata so it stays correct without edits.
-const pkg = JSON.parse(readFileSync(resolve(here, 'package.json'), 'utf8'));
-const banner = `/*! ${pkg.name} v${pkg.version}${pkg.license ? ` | ${pkg.license}` : ''} */`;
-
const common = {
bundle: true,
sourcemap: true,
target: ['es2020'],
logLevel: 'info',
- banner: { js: banner },
// The Solana web3.js / @noble/hashes imports are runtime CDN URLs resolved in
// the browser — never bundle them.
external: ['https://*'],
@@ -55,4 +50,4 @@ await build({
outfile: resolve(outDir, 'x402.global.js'),
});
-console.log(`[${pkg.name}] built dist/x402-modal.mjs, dist/x402.global.js`);
+console.log('[x402-modal] built dist/x402-modal.mjs, dist/x402.global.js');
diff --git a/x402-modal-sdk/docs/BACKEND.md b/x402-modal-sdk/docs/BACKEND.md
index 867223223..ffea634d2 100644
--- a/x402-modal-sdk/docs/BACKEND.md
+++ b/x402-modal-sdk/docs/BACKEND.md
@@ -90,9 +90,7 @@ The modal then re-sends the original request to `resource_url` with
## Reference implementation
-A complete, runnable reference lives in [`examples/server.mjs`](../examples/server.mjs).
-A production handler (e.g. a Vercel function at `api/x402-checkout.js`) has the
-same shape:
+A production implementation backs three.ws at `api/x402-checkout.js`. Its shape:
```js
// POST /api/x402-checkout?action=prepare|encode
diff --git a/x402-modal-sdk/docs/CONFIGURATION.md b/x402-modal-sdk/docs/CONFIGURATION.md
index e42669e2d..dc31b589a 100644
--- a/x402-modal-sdk/docs/CONFIGURATION.md
+++ b/x402-modal-sdk/docs/CONFIGURATION.md
@@ -6,10 +6,8 @@ Three ways to configure, in increasing specificity (later wins):
2. **`configure({ … })`** — global defaults, set once at startup.
3. **`pay({ … })` options** — per-call overrides.
-All defaults are vendor-neutral: no hardcoded backend origin, no footer
-attribution, and no builder-code echo. An un-configured drop-in settles a `402`
-from any origin out of the box — you only configure to brand it or to repoint
-the Solana checkout backend.
+All defaults reproduce the hosted three.ws modal, so an un-configured drop-in
+behaves exactly like `https://three.ws/x402.js`.
---
@@ -24,14 +22,14 @@ getConfig(); // → fully-resolved snapshot
| field | type | default | purpose |
|---|---|---|---|
| `apiOrigin` | `string \| null` | `null` → script origin | Origin of the Solana `prepare`/`encode` helper. `''` = same-origin. Ignored by the EVM path. |
-| `brand` | `{ label?, href? } \| null` | `null` (no footer attribution) | Footer attribution. Set `{ label, href? }` to add your own; merge-updated thereafter (set only `label` and `href` survives). `null` clears it. |
-| `builderCode` | `{ wallet?, service? } \| null` | `null` (echo disabled) | ERC-8021 self-attribution echoed when the `402` declares a builder code. Set your own `{ wallet, service }` to opt in; codes must match `^[a-z0-9_]{1,32}$`. |
+| `brand` | `{ label?, href? }` | `Powered by three.ws` → `https://three.ws` | Footer attribution. Merge-updated (set only `label` and `href` survives). |
+| `builderCode` | `{ wallet?, service? } \| null` | `{ wallet: '3d_agent', service: '3d_agent_modal' }` | ERC-8021 self-attribution echoed when the `402` declares a builder code. `null` disables the echo. Codes must match `^[a-z0-9_]{1,32}$`. |
| `solanaWeb3Url` | `string` | `esm.sh/@solana/[email protected]` | CDN module dynamic-imported on the Solana path. Repoint to self-host under a strict CSP. |
| `nobleHashesUrl` | `string` | `esm.sh/@noble/[email protected]/sha3` | CDN keccak module, used only for EVM SIWX sign-in. |
-`configure()` merges: once a brand is set, `configure({ brand: { label: 'X' } })`
-keeps the existing `href`. Pass `apiOrigin: null` to reset to script-origin
-resolution; pass `brand: null` or `builderCode: null` to switch either off.
+`configure()` merges: `configure({ brand: { label: 'X' } })` keeps the existing
+`href`. Pass `apiOrigin: null` to reset to script-origin resolution; pass
+`builderCode: null` to switch the echo off.
---
diff --git a/x402-modal-sdk/examples/index.html b/x402-modal-sdk/examples/index.html
index eb711f82a..1029dd3c0 100644
--- a/x402-modal-sdk/examples/index.html
+++ b/x402-modal-sdk/examples/index.html
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>x402 payment modal — demo</title>
+ <title>@three-ws/x402-modal — demo</title>
<style>
:root { color-scheme: light dark; }
* { box-sizing: border-box; }
@@ -39,16 +39,9 @@
</head>
<body>
<main>
- <h1>x402 payment modal</h1>
+ <h1>@three-ws/x402-modal</h1>
<p class="lede">A drop-in payment modal for any x402 paid endpoint. Two ways to wire it, both below.</p>
- <p class="muted">
- Set <code>ENDPOINT</code> below to your own x402-protected route, then
- click a button. With no edit the buttons point at
- <code>/api/paid/summarize</code> on this same origin — run an x402
- endpoint there (or anywhere) and the modal settles its 402 for you.
- </p>
-
<h2>1 — Declarative (<code>data-x402-*</code>)</h2>
<p>The button below is bound automatically by the global script. Point
<code>data-x402-endpoint</code> at your own x402 route to try it live.</p>
@@ -56,12 +49,10 @@
<button
class="cta"
id="declarative"
- data-x402-endpoint="/api/paid/summarize"
- data-x402-method="POST"
- data-x402-body='{"text":"The quick brown fox jumps over the lazy dog."}'
- data-x402-merchant="Acme API"
- data-x402-action="Summarize text">
- Pay &amp; summarize
+ data-x402-endpoint="https://three.ws/api/x402/dance-tip?dancer=1&dance=rumba"
+ data-x402-merchant="three.ws"
+ data-x402-action="Tip a dancer">
+ Pay &amp; tip
</button>
<pre id="declarative-out" class="muted">result will appear here…</pre>
</div>
@@ -76,9 +67,8 @@
<p class="muted">
This page loads the local build at <code>../dist/x402.global.js</code>.
Run <code>npm run build</code> in the package root first, then serve this
- folder (e.g. <code>npx serve</code>) and open it. Swap
- <code>ENDPOINT</code> for any live x402 route — the modal needs zero
- vendor configuration to settle its 402.
+ folder (e.g. <code>npx serve</code>) and open it. The demo endpoint is a
+ live three.ws x402 route; swap it for your own.
</p>
</main>
@@ -89,9 +79,6 @@
<script type="module">
import { pay } from '../dist/x402-modal.mjs';
- // Point this at your own x402-protected route. Both buttons use it.
- const ENDPOINT = '/api/paid/summarize';
-
// Declarative button → listen for the DOM events the global build fires.
const dEl = document.getElementById('declarative');
const dOut = document.getElementById('declarative-out');
@@ -111,11 +98,9 @@
pOut.textContent = 'opening modal…';
try {
const out = await pay({
- endpoint: ENDPOINT,
- method: 'POST',
- body: { text: 'The quick brown fox jumps over the lazy dog.' },
- merchant: 'Acme API',
- action: 'Summarize text',
+ endpoint: 'https://three.ws/api/x402/dance-tip?dancer=1&dance=rumba',
+ merchant: 'three.ws',
+ action: 'Tip a dancer',
});
pOut.className = '';
pOut.textContent = JSON.stringify({ result: out.result, payment: out.payment }, null, 2);
diff --git a/x402-modal-sdk/package.json b/x402-modal-sdk/package.json
index 7a09a6b79..66d2fc784 100644
--- a/x402-modal-sdk/package.json
+++ b/x402-modal-sdk/package.json
@@ -1,7 +1,7 @@
{
"name": "@three-ws/x402-modal",
"version": "0.2.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. Works against any origin with zero configuration; USDC by default.",
+ "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",
"payments",
diff --git a/x402-modal-sdk/src/x402-modal.js b/x402-modal-sdk/src/x402-modal.js
index ecb40ba5d..b6bcc7613 100644
--- a/x402-modal-sdk/src/x402-modal.js
+++ b/x402-modal-sdk/src/x402-modal.js
@@ -40,11 +40,10 @@ import {
const VERSION = '0.2.0';
// ─────────────────────────────────────────────────────────── configuration ───
-// Everything the host wants to brand or repoint lives here. The defaults are
-// vendor-neutral — no hardcoded origin, no footer attribution, no builder-code
-// echo — so the modal settles a 402 from ANY origin out of the box. A
-// deployment brands or repoints by overriding them with `configure()` (global)
-// or per-call `pay({ ... })` options (which always win over the global config).
+// Everything the host wants to brand or repoint lives here. Defaults reproduce
+// three.ws's hosted behaviour exactly, so the drop-in script is unchanged; a
+// standalone deployment overrides them with `configure()` (global) or per-call
+// `pay({ ... })` options (which always win over the global config).
const DEFAULTS = {
// Origin that serves the Solana `prepare` / `encode` checkout helpers
@@ -52,14 +51,12 @@ const DEFAULTS = {
// payment path uses these — the EVM/EIP-3009 path is fully client-side and
// needs no backend. `null` ⇒ resolve from the script's own origin at runtime.
apiOrigin: null,
- // Footer attribution shown at the bottom of the modal. `null` ⇒ no footer
- // attribution; set `{ label, href? }` to add your own.
- brand: null,
+ // Footer attribution shown at the bottom of the modal.
+ brand: { label: 'Powered by three.ws', href: 'https://three.ws' },
// ERC-8021 builder-code self-attribution echoed back when the 402 challenge
// declares a builder code. `wallet` = your wallet code, `service` = your
- // integration code. `null` (the default) disables the echo; set your own
- // codes (each matching `^[a-z0-9_]{1,32}$`) to opt in.
- builderCode: null,
+ // integration code. Set to null to disable the echo entirely.
+ builderCode: { wallet: '3d_agent', service: '3d_agent_modal' },
// CDN modules dynamic-imported on demand. Override to self-host / satisfy a
// strict Content-Security-Policy.
solanaWeb3Url: 'https://esm.sh/@solana/[email protected]?bundle',
@@ -68,7 +65,7 @@ const DEFAULTS = {
const config = {
apiOrigin: DEFAULTS.apiOrigin,
- brand: DEFAULTS.brand ? { ...DEFAULTS.brand } : null,
+ brand: { ...DEFAULTS.brand },
builderCode: DEFAULTS.builderCode ? { ...DEFAULTS.builderCode } : null,
solanaWeb3Url: DEFAULTS.solanaWeb3Url,
nobleHashesUrl: DEFAULTS.nobleHashesUrl,
@@ -93,8 +90,7 @@ function resolveScriptOrigin() {
export function configure(opts = {}) {
if (!opts || typeof opts !== 'object') return getConfig();
if (opts.apiOrigin !== undefined) config.apiOrigin = opts.apiOrigin;
- if (opts.brand === null) config.brand = null;
- else if (opts.brand) config.brand = { ...(config.brand || {}), ...opts.brand };
+ if (opts.brand) config.brand = { ...config.brand, ...opts.brand };
if (opts.builderCode === null) config.builderCode = null;
else if (opts.builderCode) config.builderCode = { ...(config.builderCode || {}), ...opts.builderCode };
if (opts.solanaWeb3Url) config.solanaWeb3Url = opts.solanaWeb3Url;
@@ -105,7 +101,7 @@ export function configure(opts = {}) {
export function getConfig() {
return {
apiOrigin: config.apiOrigin,
- brand: config.brand ? { ...config.brand } : null,
+ brand: { ...config.brand },
builderCode: config.builderCode ? { ...config.builderCode } : null,
solanaWeb3Url: config.solanaWeb3Url,
nobleHashesUrl: config.nobleHashesUrl,
diff --git a/x402-modal-sdk/test/configure.test.js b/x402-modal-sdk/test/configure.test.js
index 6d6ef21aa..9cf211497 100644
--- a/x402-modal-sdk/test/configure.test.js
+++ b/x402-modal-sdk/test/configure.test.js
@@ -17,42 +17,35 @@ test('pay() rejects without an endpoint', async () => {
await assert.rejects(() => pay({}), /endpoint is required/);
});
-test('defaults are vendor-neutral (no origin, no brand, no builder-code echo)', () => {
+test('configure merges brand and builderCode without dropping siblings', () => {
const base = getConfig();
- // Out of the box the modal settles any 402 with zero configuration: no
- // hardcoded backend origin, no footer attribution, no builder-code echo.
- assert.equal(base.apiOrigin, null);
- assert.equal(base.brand, null);
- assert.equal(base.builderCode, null);
-});
+ assert.equal(base.brand.label, 'Powered by three.ws');
+ assert.equal(base.builderCode.wallet, '3d_agent');
-test('configure merges brand and builderCode without dropping siblings', () => {
- // Opt into a brand, then a partial override must keep the untouched sibling.
- configure({ brand: { label: 'Powered by Acme', href: 'https://acme.com' } });
- configure({ brand: { label: 'Acme Pay' } });
+ configure({ brand: { label: 'Powered by Acme' } });
const afterBrand = getConfig();
- assert.equal(afterBrand.brand.label, 'Acme Pay');
+ assert.equal(afterBrand.brand.label, 'Powered by Acme');
// href left intact since only label was overridden
- assert.equal(afterBrand.brand.href, 'https://acme.com');
- // null clears the brand back to neutral
- configure({ brand: null });
- assert.equal(getConfig().brand, null);
+ assert.equal(afterBrand.brand.href, 'https://three.ws');
configure({ apiOrigin: 'https://pay.example.com' });
assert.equal(getConfig().apiOrigin, 'https://pay.example.com');
- configure({ builderCode: { wallet: 'acme', service: 'acme_pay' } });
configure({ builderCode: { service: 'acme_checkout' } });
const afterBuilder = getConfig();
assert.equal(afterBuilder.builderCode.service, 'acme_checkout');
- assert.equal(afterBuilder.builderCode.wallet, 'acme');
+ assert.equal(afterBuilder.builderCode.wallet, '3d_agent');
// null disables the echo entirely
configure({ builderCode: null });
assert.equal(getConfig().builderCode, null);
- // restore neutral defaults for any later test run in the same process
- configure({ apiOrigin: null, brand: null, builderCode: null });
+ // restore defaults for any later test run in the same process
+ configure({
+ apiOrigin: null,
+ brand: { label: 'Powered by three.ws', href: 'https://three.ws' },
+ builderCode: { wallet: '3d_agent', service: '3d_agent_modal' },
+ });
});
test("configure honours an explicit empty-string apiOrigin (same-origin)", () => {
diff --git a/x402-modal-sdk/types/index.d.ts b/x402-modal-sdk/types/index.d.ts
index 079195ed2..773b91ae3 100644
--- a/x402-modal-sdk/types/index.d.ts
+++ b/x402-modal-sdk/types/index.d.ts
@@ -32,7 +32,7 @@ export interface SpendingCaps {
maxPerDay?: number | string;
}
-/** Global configuration. Defaults are vendor-neutral: no origin, brand, or builder-code echo. */
+/** Global configuration. Defaults reproduce three.ws's hosted behaviour. */
export interface X402Config {
/**
* Origin serving the Solana `prepare`/`encode` checkout helpers
diff --git a/x402-payment-modal/CHANGELOG.md b/x402-payment-modal/CHANGELOG.md
index 5aedffcf0..0765dff7d 100644
--- a/x402-payment-modal/CHANGELOG.md
+++ b/x402-payment-modal/CHANGELOG.md
@@ -3,31 +3,15 @@
All notable changes to `@three-ws/x402-payment-modal` are documented here. This
project adheres to [Semantic Versioning](https://semver.org).
-## Unreleased
-
-### Changed
-
-- **Host-neutral by default.** The modal now settles a 402 challenge from any
- origin with zero configuration and **USDC as the always-on default settlement
- asset**. Branding (`brand`) and ERC-8021 builder-code self-attribution
- (`builderCode`) now default to empty — the footer "Powered by" link is hidden
- until you set your own `brand`, and no builder code is echoed unless you opt in.
- `checkoutOrigin` still resolves to the script's own origin by default. Set any
- of these via `configure()` or `data-*` attributes.
-- **Token model clarified.** USDC is the default token everywhere. The `THREE`
- token shortcut remains supported as an **optional, opt-in** convenience
- (`solanaAccept({ token: 'three' })`, `THREE_MINT`) — recognized on sight but
- never a default. Any SPL mint works the same way via an explicit `mint`.
-
## 1.2.0
Hardening pass for scale and a UX/accessibility overhaul.
### Fixed
-- **Token-2022 mints now settle.** `prepareSolanaCheckout`
- hardcoded the legacy SPL Token program, so building a payment in a Token-2022
- mint threw `TokenInvalidAccountOwnerError`. The server now detects each mint's owning
+- **$THREE (and any Token-2022 mint) now settles.** `prepareSolanaCheckout`
+ hardcoded the legacy SPL Token program, so building a $THREE payment threw
+ `TokenInvalidAccountOwnerError`. The server now detects each mint's owning
program (legacy vs Token-2022) and derives ATAs, the idempotent-create, and
`transferChecked` against the right one.
@@ -85,29 +69,30 @@ Hardening pass for scale and a UX/accessibility overhaul.
### Added
-- **Multiple Solana tokens with a token picker.** When a 402 challenge offers
- more than one Solana token, the modal renders a token picker so the buyer
- chooses which to pay in; the headline price and the built transaction follow the
- choice. USDC is recognized by mint, and an optional `THREE` token shortcut is
- recognized too — correct symbol, decimals, and branding even when the `accept`
- omits `extra.name`/`extra.decimals`.
+- **Pay in USDC _or_ THREE on Solana.** When a 402 challenge offers more than one
+ Solana token, the modal renders a token picker so the buyer chooses which to
+ pay in; the headline price and the built transaction follow the choice. USDC
+ and [$THREE](https://three.ws/three-token) (`FeMb…pump`) are recognized by mint
+ — correct symbol, decimals, and branding even when the `accept` omits
+ `extra.name`/`extra.decimals`.
- **`solanaAccept()` server helper** — build a spec-shaped Solana `accept` from
- `token: 'usdc'` (or an explicit `mint`, or the optional `'three'` shortcut) with
- the price as `uiAmount` (human) or `amount` (atomic). Exports `USDC_MINT_SOLANA`,
- `THREE_MINT`, and `WELL_KNOWN_SOLANA_TOKENS`.
-- **`window.X402.tokens`** + client exports `USDC_MINT_SOLANA`, `THREE_MINT`,
+ `token: 'usdc' | 'three'` (or an explicit `mint`) with the price as `uiAmount`
+ (human) or `amount` (atomic). Exports `THREE_MINT`, `USDC_MINT_SOLANA`, and
+ `WELL_KNOWN_SOLANA_TOKENS`.
+- **`window.X402.tokens`** + client exports `THREE_MINT`, `USDC_MINT_SOLANA`,
`KNOWN_SOLANA_TOKENS` for inline merchants composing challenges in the browser.
### Notes
-- A floating-price (non-stablecoin) token can't be dollar-denominated in the
- browser, so client-side spending caps apply to stablecoins (USDC) only — enforce
- other tokens' caps server-side. Settlement is unchanged — the checkout endpoint
- already transfers any SPL mint named by the chosen `accept`.
+- THREE is a utility token, not a stablecoin: the browser can't dollar-denominate
+ it, so client-side spending caps apply to USDC only — enforce THREE caps
+ server-side. Settlement is unchanged — the checkout endpoint already transfers
+ any SPL mint named by the chosen `accept`.
## 1.0.0
-Initial public release: a standalone, dependency-free package.
+Initial public release. Extracted from the three.ws platform as a standalone,
+dependency-free package.
### Added
diff --git a/x402-payment-modal/README.md b/x402-payment-modal/README.md
index 78605abb3..6c46b5be0 100644
--- a/x402-payment-modal/README.md
+++ b/x402-payment-modal/README.md
@@ -41,11 +41,10 @@ throttle retries, and the receipt, so you ship a paid endpoint in minutes.
- **Solana + EVM.** Phantom (Solana) and any injected EVM wallet (Base USDC
via EIP-3009 `transferWithAuthorization`). The modal picks the right path from
the 402 challenge.
-- **USDC by default; any SPL token optional.** USDC is the always-on default
- settlement asset. A merchant can additionally offer a second Solana token (any
- SPL mint) and the buyer gets a token picker — the headline price and the
- transaction follow the choice. See
- [Accepting multiple Solana tokens](#accepting-multiple-solana-tokens).
+- **Pay in USDC _or_ THREE on Solana.** Offer both and the buyer gets a token
+ picker — pay in USDC, or in [$THREE](https://three.ws/three-token), the three.ws
+ utility token, recognized on sight (symbol, decimals, branding). See
+ [Accepting multiple Solana tokens](#accepting-multiple-solana-tokens-usdc--three).
- **SIWX re-entry.** If a wallet already paid for a resource, it can sign back in
instead of paying again. See [docs/siwx.md](docs/siwx.md).
- **Spending caps.** Optional per-call / hourly / daily caps enforced in the
@@ -236,8 +235,8 @@ configure({
| `checkoutOrigin` | `data-x402-checkout-origin` | the script's own origin |
| `checkoutPath` | `data-x402-checkout-path` | `/api/x402-checkout` |
| `footerNote` | `data-x402-footer-note` | `x402 · onchain settled` |
-| `brand.name` / `brand.url` | `data-x402-brand-name` / `-brand-url` | none (footer "Powered by" link hidden) |
-| `builderCode.wallet` / `.service` | `data-x402-builder-wallet` / `-builder-service` | empty (no self-attribution) |
+| `brand.name` / `brand.url` | `data-x402-brand-name` / `-brand-url` | `three.ws` |
+| `builderCode.wallet` / `.service` | `data-x402-builder-wallet` / `-builder-service` | three.ws codes |
| `esm.solanaWeb3` / `esm.nobleHashesSha3` | — | pinned esm.sh URLs |
Repoint `esm.*` at a self-hosted mirror if a strict Content-Security-Policy
@@ -276,14 +275,13 @@ Lower-level helpers (`prepareSolanaCheckout`, `encodeX402Payment`,
---
-## Accepting multiple Solana tokens
+## Accepting multiple Solana tokens (USDC + THREE)
-USDC is the default settlement asset and works with zero extra configuration. An
-x402 challenge can also list more than one accepted payment. List a USDC accept
-**and** a second SPL-token accept on Solana, and the modal renders a token
-picker: the buyer chooses which to pay in, the headline price and the transaction
-follow the choice. No client wiring — the checkout endpoint already builds an SPL
-transfer for whatever mint the chosen accept names.
+An x402 challenge can list more than one accepted payment. List a USDC accept
+**and** a [$THREE](https://three.ws/three-token) accept on Solana, and the modal
+renders a token picker: the buyer chooses which to pay in, the headline price and
+the transaction follow the choice. No client wiring — the checkout endpoint
+already builds an SPL transfer for whatever mint the chosen accept names.
Build the accepts with the `solanaAccept` helper (no hardcoded mints):
@@ -291,30 +289,24 @@ Build the accepts with the `solanaAccept` helper (no hardcoded mints):
import { solanaAccept } from '@three-ws/x402-payment-modal/server';
// feePayer is your facilitator's sponsor account (pays the SOL network fee).
-const usdcOnly = solanaAccept({ token: 'usdc', uiAmount: 0.25, payTo, feePayer }); // $0.25 in USDC
-
-// Want to also accept a second token? Add any SPL mint as another accept entry:
const accepts = [
- solanaAccept({ token: 'usdc', uiAmount: 0.25, payTo, feePayer }), // $0.25 in USDC (default)
- solanaAccept({ mint: MY_TOKEN_MINT, uiAmount: 1000, decimals: 6, name: 'MYTOKEN', payTo, feePayer }),
+ solanaAccept({ token: 'usdc', uiAmount: 0.25, payTo, feePayer }), // $0.25 in USDC
+ solanaAccept({ token: 'three', uiAmount: 1000, payTo, feePayer }), // or 1,000 THREE
];
// Return them in your 402 body / PAYMENT-REQUIRED envelope:
// { x402Version: 2, accepts }
```
-`solanaAccept` takes `token: 'usdc'` for the default USDC rail, or an explicit
-`mint` (+ `decimals`/`name`) for any other SPL token, the price as `uiAmount`
-(human units) or `amount` (atomic string), and emits a spec-shaped `accept`. The
-constants `USDC_MINT_SOLANA` and `WELL_KNOWN_SOLANA_TOKENS` are exported. As a
-convenience, a `THREE` token shortcut (`token: 'three'`) and its `THREE_MINT`
-constant are also exported and recognized on sight — purely optional, opt in by
-offering it in your challenge. On the client, the same mints are exposed at
-`window.X402.tokens` for inline merchants.
-
-> **Non-stablecoins:** the modal can only dollar-denominate stablecoins (USDC)
-> for browser-side spending caps. A floating-price token's caps must be enforced
-> server-side. USDC caps work in the browser as usual.
+`solanaAccept` takes `token: 'usdc' | 'three'` (or an explicit `mint` for any
+SPL token), the price as `uiAmount` (human units) or `amount` (atomic string),
+and emits a spec-shaped `accept`. The constants `THREE_MINT`, `USDC_MINT_SOLANA`,
+and `WELL_KNOWN_SOLANA_TOKENS` are exported too. On the client, the same mints
+are exposed at `window.X402.tokens` for inline merchants.
+
+> **THREE is a utility token, not a stablecoin.** Its price floats, so the modal
+> can't dollar-denominate it for browser-side spending caps — enforce caps for
+> THREE server-side. USDC caps work in the browser as usual.
---
diff --git a/x402-payment-modal/build.mjs b/x402-payment-modal/build.mjs
index 4fd7d7930..eab14c683 100644
--- a/x402-payment-modal/build.mjs
+++ b/x402-payment-modal/build.mjs
@@ -23,10 +23,7 @@ mkdirSync(distDir, { recursive: true });
const pkg = JSON.parse(readFileSync(join(here, 'package.json'), 'utf8'));
const source = readFileSync(srcFile, 'utf8');
-// Banner is derived entirely from package metadata — no hardcoded host or
-// branding — so the same build script works for any fork/republish.
-const bannerUrl = pkg.homepage || pkg.repository?.url || '';
-const banner = `/*! ${pkg.name} v${pkg.version} — ${pkg.license}${bannerUrl ? ` — ${bannerUrl}` : ''} */\n`;
+const banner = `/*! ${pkg.name} v${pkg.version} — ${pkg.license} — ${pkg.homepage} */\n`;
// 1. Readable, unminified copy for CDN debugging and source maps in DevTools.
writeFileSync(join(distDir, 'x402.js'), banner + source);
diff --git a/x402-payment-modal/docs/api-reference.md b/x402-payment-modal/docs/api-reference.md
index 18f1c913e..6db78fb49 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.2.0"
+console.log(version); // "1.1.0"
```
---
diff --git a/x402-payment-modal/examples/server-express/server.js b/x402-payment-modal/examples/server-express/server.js
index 7208a12b0..6c57f8b2c 100644
--- a/x402-payment-modal/examples/server-express/server.js
+++ b/x402-payment-modal/examples/server-express/server.js
@@ -44,7 +44,8 @@ app.use('/api/x402-checkout', x402CheckoutRouter({ rpcUrl: SOLANA_RPC_URL }));
//
// IMPORTANT: verifying and settling the X-PAYMENT payload against an x402
// facilitator is OUT OF SCOPE for this demo. In production you would verify the
-// payment proof (and idempotency) before returning 200. See the docs in ../../docs.
+// payment proof (and idempotency) before returning 200. See the docs:
+// https://github.com/three-ws/x402-payment-modal/tree/main/docs
//
// Synthetic placeholders below — replace payTo / feePayer with YOUR addresses.
const DEMO_PAY_TO = 'So11111111111111111111111111111111111111112'; // replace me
@@ -54,22 +55,21 @@ app.get('/api/paid/hello', (req, res) => {
const hasPayment = Boolean(req.get('X-PAYMENT'));
if (!hasPayment) {
- // No payment yet → answer with the x402 v2 challenge. USDC is the default
- // settlement asset; `solanaAccept` builds the spec-shaped entry.
+ // No payment yet → answer with the x402 v2 challenge. We offer TWO Solana
+ // tokens — USDC and THREE — so the modal shows a token picker and the buyer
+ // chooses which to pay in. `solanaAccept` builds each spec-shaped entry.
const common = { payTo: DEMO_PAY_TO, feePayer: DEMO_FEE_PAYER, maxTimeoutSeconds: 60 };
return res.status(402).json({
x402Version: 2,
error: 'Payment required',
resource: {
url: `${req.protocol}://${req.get('host')}/api/paid/hello`,
- description: 'A friendly hello — pay $0.01 in USDC.',
+ description: 'A friendly hello — pay in USDC or THREE.',
mimeType: 'application/json',
},
accepts: [
- solanaAccept({ token: 'usdc', uiAmount: 0.01, ...common }), // $0.01 in USDC (default)
- // To additionally accept a second Solana token, push another accept for
- // any SPL mint and the modal renders a token picker, e.g.:
- // solanaAccept({ mint: MY_TOKEN_MINT, uiAmount: 1000, decimals: 6, name: 'MYTOKEN', ...common }),
+ solanaAccept({ token: 'usdc', uiAmount: 0.01, ...common }), // $0.01 in USDC
+ solanaAccept({ token: 'three', uiAmount: 1000, ...common }), // or 1,000 THREE
],
});
}
diff --git a/x402-payment-modal/examples/solana-crypto-paywall/README.md b/x402-payment-modal/examples/solana-crypto-paywall/README.md
index 3dab91465..e12704c51 100644
--- a/x402-payment-modal/examples/solana-crypto-paywall/README.md
+++ b/x402-payment-modal/examples/solana-crypto-paywall/README.md
@@ -12,8 +12,8 @@ click ─▶ 402 challenge ─▶ Phantom connect ─▶ sign SPL transfer
Three things make it a real test, not a mock:
1. **The modal loads from npm.** `public/index.html` pulls
- `https://unpkg.com/@three-ws/[email protected]` — the exact published
- artifact — so you're testing the shipped code, not local source.
+ `https://unpkg.com/@three-ws/[email protected]` — the exact artifact we
+ publish — so you're testing the shipped code, not local source.
2. **The data is gated for real.** `/api/paid/crypto` returns live CoinGecko
prices **only** after the payment verifies *and* settles on-chain via the
[PayAI](https://facilitator.payai.network) facilitator. No payment, no data.
@@ -21,7 +21,7 @@ Three things make it a real test, not a mock:
constant for it — you start the server, paste a Solana address into the page,
and that address becomes the `payTo` in the 402 challenge.
-## Run it (inside this package's repo)
+## Run it (inside the three.ws repo)
The server reuses the repo's `express` + `@solana/*` and imports the package's
checkout helpers from source, so no install is needed:
diff --git a/x402-payment-modal/examples/solana-crypto-paywall/facilitator.mjs b/x402-payment-modal/examples/solana-crypto-paywall/facilitator.mjs
index 86f0b6ee0..69083fb3b 100644
--- a/x402-payment-modal/examples/solana-crypto-paywall/facilitator.mjs
+++ b/x402-payment-modal/examples/solana-crypto-paywall/facilitator.mjs
@@ -7,9 +7,9 @@
// facilitator co-signs as the fee payer and broadcasts — so the merchant never
// holds a private key and pays no gas.
//
-// This is the standard x402 facilitator wire format (verify/settle), trimmed to
-// exactly what the Solana exact path needs so the example stays self-contained
-// and easy to read:
+// This is the same wire format the main three.ws app uses (api/_lib/x402-spec.js
+// verifyPayment/settlePayment), trimmed to exactly what the Solana exact path
+// needs so the example stays self-contained and easy to read:
//
// POST {facilitator}/verify { x402Version, paymentPayload, paymentRequirements }
// → { isValid: boolean, invalidReason?, payer? }
diff --git a/x402-payment-modal/examples/solana-crypto-paywall/public/index.html b/x402-payment-modal/examples/solana-crypto-paywall/public/index.html
index 2e7c9314b..620f02f56 100644
--- a/x402-payment-modal/examples/solana-crypto-paywall/public/index.html
+++ b/x402-payment-modal/examples/solana-crypto-paywall/public/index.html
@@ -3,22 +3,20 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>x402 Crypto Paywall — Solana</title>
+ <title>x402 Crypto Paywall — Solana · three.ws</title>
<meta name="description" content="Pay $0.01 USDC on Solana to unlock live crypto prices — a demo of the @three-ws/x402-payment-modal npm package." />
<!--
The payment modal is loaded straight from npm (unpkg) so this page exercises
- the EXACT artifact published. Pinned to a version per the package's own
- security guidance; bump it to test a new release. The brand-* attributes below
- are illustrative — set them to YOUR own merchant name/URL (or omit them to
- hide the footer link entirely).
+ the EXACT artifact we publish. Pinned to a version per the package's own
+ security guidance; bump it to test a new release.
-->
<script
type="module"
- src="https://unpkg.com/@three-ws/[email protected]"
- data-x402-brand-name="Crypto Prices"
- data-x402-brand-url="https://example.com"
- data-x402-footer-note="x402 · Solana · settled by a facilitator"></script>
+ src="https://unpkg.com/@three-ws/[email protected]"
+ data-x402-brand-name="three.ws Crypto"
+ data-x402-brand-url="https://three.ws"
+ data-x402-footer-note="x402 · Solana · settled by PayAI"></script>
<style>
:root {
@@ -195,12 +193,12 @@
<header class="hero">
<div class="brandline">
<span class="dot" aria-hidden="true"></span>
- <b>Crypto Prices</b>
+ <b>three.ws</b>
<span class="pill" id="verPill"><span class="live"></span><span id="verText">loading modal…</span></span>
</div>
<h1>Pay-per-call <span class="grad">crypto prices</span>,<br/>settled on Solana.</h1>
<p class="lede">
- A live demo of <code>@three-ws/x402-payment-modal</code> — the modal published on npm.
+ A live demo of <code>@three-ws/x402-payment-modal</code> — the modal we ship on npm.
Set a payout wallet, pick coins, and pay $0.01 USDC with Phantom to unlock real
CoinGecko prices. One click; no wallet code.
</p>
@@ -218,7 +216,7 @@
<label class="fld" for="payTo">Solana address (base58)</label>
<div class="inrow">
<input id="payTo" type="text" inputmode="text" autocomplete="off" spellcheck="false"
- placeholder="e.g. 5xY…your Solana wallet…aB1z" aria-describedby="cfgStatus" />
+ placeholder="e.g. 5xY…your Solana wallet…Jpump" aria-describedby="cfgStatus" />
<button id="saveCfg" class="ghost" type="button">Save</button>
</div>
<div class="cfg-status" id="cfgStatus" role="status" aria-live="polite">No payout wallet set yet.</div>
@@ -451,7 +449,7 @@
endpoint: '/api/paid/crypto',
method: 'POST',
body: { ids },
- merchant: 'Crypto Prices',
+ merchant: 'three.ws Crypto',
action: 'Live prices · ' + ids.length + ' coin' + (ids.length > 1 ? 's' : ''),
});
state.last = { data: out.result, payment: out.payment };
@@ -492,7 +490,7 @@
// confirm the npm modal is live
try {
const X = await whenModalReady();
- X.configure({ checkoutOrigin: location.origin, brand: { name: 'Crypto Prices', url: 'https://example.com' } });
+ X.configure({ checkoutOrigin: location.origin, brand: { name: 'three.ws Crypto', url: 'https://three.ws' } });
$('verPill').classList.add('ready');
$('verText').textContent = 'modal v' + (X.version || '?') + ' · live from npm';
} catch (err) {
diff --git a/x402-payment-modal/examples/solana-crypto-paywall/server.mjs b/x402-payment-modal/examples/solana-crypto-paywall/server.mjs
index a9b013768..5106cfe85 100644
--- a/x402-payment-modal/examples/solana-crypto-paywall/server.mjs
+++ b/x402-payment-modal/examples/solana-crypto-paywall/server.mjs
@@ -12,7 +12,7 @@
// The only "config" that isn't runtime is the facilitator's fee-payer sponsor
// (a PUBLIC Solana account, not a secret) and the CoinGecko/PayAI URLs.
//
-// Run (from inside this package's repo — reuses the repo's express + @solana deps):
+// Run (from inside the three.ws repo — uses the repo's express + @solana deps):
// node x402-payment-modal/examples/solana-crypto-paywall/server.mjs
// open http://localhost:4021
//
@@ -40,10 +40,10 @@ import {
const __dirname = dirname(fileURLToPath(import.meta.url));
const PORT = Number(process.env.PORT) || 4021;
-// The facilitator co-signs Solana settlements as the fee payer. This is the
-// facilitator's PUBLIC sponsor pubkey (it pays the SOL network fee so the buyer
-// needs only USDC), NOT a secret and NOT the payout wallet. Override only if you
-// point X402_FACILITATOR_URL at a facilitator with a different sponsor.
+// PayAI's facilitator co-signs Solana settlements as the fee payer. This is the
+// three.ws default sponsor — a PUBLIC pubkey (it pays the SOL network fee so the
+// buyer needs only USDC), NOT a secret and NOT the payout wallet. Override only
+// if you point X402_FACILITATOR_URL at a facilitator with a different sponsor.
const FEE_PAYER = process.env.X402_FEE_PAYER_SOLANA || '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4';
// A public Solana RPC works for a quick try (rate-limited). Pass a dedicated RPC
diff --git a/x402-payment-modal/package.json b/x402-payment-modal/package.json
index f856b8bfd..50e94a957 100644
--- a/x402-payment-modal/package.json
+++ b/x402-payment-modal/package.json
@@ -77,7 +77,8 @@
"modal",
"agentic",
"web3",
- "402"
+ "402",
+ "three-ws"
],
"author": "three.ws <[email protected]> (https://three.ws)",
"license": "Apache-2.0",
diff --git a/x402-payment-modal/server/checkout.js b/x402-payment-modal/server/checkout.js
index 3d4448583..10a3e2699 100644
--- a/x402-payment-modal/server/checkout.js
+++ b/x402-payment-modal/server/checkout.js
@@ -13,9 +13,8 @@
// live in ./express.js and ./vercel.js.
//
// Runtime deps: @solana/web3.js and @solana/spl-token (declared as optional peer
-// dependencies — install them in the app that mounts this handler). This module
-// is fully host-neutral: it has no required configuration and assumes no
-// particular merchant, facilitator, or origin.
+// dependencies — install them in the app that mounts this handler). Nothing here
+// imports anything three.ws-specific.
import {
Connection,
@@ -44,14 +43,12 @@ const DEFAULT_MAINNET_RPC = 'https://api.mainnet-beta.solana.com';
const DEFAULT_DEVNET_RPC = 'https://api.devnet.solana.com';
// ─────────────────────────────────────────────── Well-known Solana tokens ────
-// USDC is the always-on default settlement asset on Solana — the universal
-// dollar-stable rail. THREE is an OPTIONAL, opt-in convenience token: a merchant
-// that wants to additionally accept it passes `token: 'three'` (or any explicit
-// `mint`) to `solanaAccept()`. It is never a default. `solanaAccept()` builds the
-// x402 `accept` entry for USDC, THREE, or any other SPL mint — the prepare path
-// already transfers any mint, so offering an extra token needs no further wiring.
+// The two settlement assets the modal treats as first-class on Solana. USDC is
+// the universal dollar-stable rail; THREE is the three.ws utility token, so any
+// endpoint can let holders pay in THREE alongside USDC. `solanaAccept()` builds
+// the x402 `accept` entry for either (or any other SPL mint) — the prepare path
+// already transfers any mint, so offering THREE needs no further wiring.
export const USDC_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
-// Optional opt-in token shortcut (not a default).
export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
export const WELL_KNOWN_SOLANA_TOKENS = Object.freeze({
diff --git a/x402-payment-modal/src/index.js b/x402-payment-modal/src/index.js
index 120392835..860a24c6b 100644
--- a/x402-payment-modal/src/index.js
+++ b/x402-payment-modal/src/index.js
@@ -35,38 +35,30 @@
// Everything host-specific (the Solana checkout origin, branding, builder-code
// attribution, and the esm.sh CDN URLs used for the Solana/EVM crypto helpers)
// is configurable via `configure({...})` or `data-*` attributes on the script
-// tag — see CONFIG / configure() below and docs/api-reference.md. With zero
-// configuration the modal settles a 402 challenge from any origin: USDC is the
-// always-on default settlement asset on both Solana and EVM.
+// tag — see CONFIG / configure() below and docs/api-reference.md.
const VERSION = '1.2.0';
// ─────────────────────────────────────────────────────────── configuration ───
// All host-specific knobs live here so the modal runs unchanged on any site.
-// Every default is host-neutral: the modal settles a 402 challenge from ANY
-// origin out of the box, with no per-host configuration. Override any of these
-// with configure() or via `data-*` attributes on the <script> tag (read once at
-// load by readScriptConfig).
+// Defaults match the three.ws hosted instance; override with configure() or via
+// `data-*` attributes on the <script> tag (read once at load by readScriptConfig).
const CONFIG = {
// Origin that serves the Solana checkout endpoints
// (`/api/x402-checkout?action=prepare|encode`). `null` → resolve from this
- // script's own src, falling back to the current page origin. So by default the
- // checkout server is assumed to live on the SAME origin that serves the modal
- // — set `checkoutOrigin` only if you host the checkout endpoint elsewhere. EVM
- // payments never touch this — the wallet signs EIP-3009 typed-data locally.
+ // script's own src, falling back to the current page origin. EVM payments
+ // never touch this — the wallet signs EIP-3009 typed-data locally.
checkoutOrigin: null,
// Path of the checkout endpoint on `checkoutOrigin`. Override if you mount
// the server handler somewhere other than /api/x402-checkout.
checkoutPath: '/api/x402-checkout',
- // Footer attribution shown in the modal. `name: null` (the default) hides the
- // "Powered by …" link entirely. Set `{ name, url, logo }` to show your own.
- brand: { name: null, url: null },
+ // Footer attribution shown in the modal.
+ brand: { name: 'three.ws', url: 'https://three.ws' },
// Small text on the left of the footer.
footerNote: 'x402 · onchain settled',
// ERC-8021 builder-code self-attribution echoed back when the 402 challenge
- // declares a builder-code extension. Empty by default (no self-attribution) —
- // set either field to your own registered builder code to opt in.
- builderCode: { wallet: '', service: '' },
+ // declares a builder-code extension. Set either field to '' to disable it.
+ builderCode: { wallet: '3d_agent', service: '3d_agent_modal' },
// Color scheme: 'auto' follows the OS; 'light'/'dark' force it.
theme: 'auto',
// Optional flat map of --x402-* design tokens for brand-matching at runtime.
@@ -175,18 +167,13 @@ function normalizeAccept(accept) {
// ─────────────────────────────────────────────── Well-known Solana tokens ────
// Mints the modal recognizes on sight, so a 402 `accept` can omit
// `extra.name`/`extra.decimals` and still render with the correct symbol,
-// decimals, and branding. USDC is the always-on default settlement asset:
-// • USDC — the universal dollar-stable rail, used by default everywhere.
-// • THREE — an OPTIONAL, opt-in token a merchant can additionally accept.
-// It is never the default; a merchant offers it simply by adding a Solana
-// `accept` whose `asset` is THREE_MINT (the server checkout transfers any
-// SPL mint, so no extra wiring), and buyers may then choose it alongside
-// USDC. Any other SPL mint works the same way via merchant-supplied
-// `extra.name`/`extra.decimals` — THREE just ships with built-in metadata.
+// decimals, and branding. Two settlement assets are first-class on Solana:
+// • USDC — the universal dollar-stable rail.
+// • THREE — the three.ws utility token. Holders can pay any x402 endpoint
+// that opts into accepting it, right alongside USDC. See three.ws/three-token.
+// A merchant offers THREE simply by adding a Solana `accept` whose `asset` is
+// THREE_MINT (the server checkout transfers any SPL mint, so no extra wiring).
export const USDC_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
-// Optional, recognized-on-sight token. Not a default — opt in by offering it in
-// the 402 challenge. Kept as a convenience so its `accept` renders without
-// merchant-supplied metadata.
export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
export const KNOWN_SOLANA_TOKENS = Object.freeze({
@@ -377,11 +364,10 @@ function browserRollbackReservation(reservation) {
}
// ──────────────────────────────────────────── ERC-8021 builder-code echo ────
-// A 402 challenge may declare a builder-code extension whose `a` field the
-// server enforces matches on the echoed payload (anti-tamper). Builders/wallets
-// can append their own service code in `s` and set their wallet code `w` by
-// configuring `builderCode: { wallet, service }`. Empty by default — no
-// self-attribution is sent unless you opt in with your own registered code.
+// The server-side x402-spec.js enforces that any client-echoed builder-code
+// `a` matches what the 402 challenge declared (anti-tamper). Builders/wallets
+// can append their own service code in `s` and set their wallet code `w`
+// — for our own demo modal we self-attribute `w: "3d_agent"` and `s: ["3d_agent_modal"]`.
const BUILDER_CODE_KEY = 'builder-code';
const BUILDER_CODE_PATTERN = /^[a-z0-9_]{1,32}$/;
@@ -1500,7 +1486,7 @@ class CheckoutModal {
const txBytes = base64ToUint8Array(prep.tx_base64);
// Phantom returns a fully-signed VersionedTransaction with the buyer's
// signature added. The facilitator's fee-payer signature is added by
- // the x402 facilitator during /settle.
+ // PayAI during /settle.
const SolanaWeb3 = await loadSolanaWeb3();
const tx = SolanaWeb3.VersionedTransaction.deserialize(txBytes);
const signed = await provider.signTransaction(tx);
diff --git a/x402-payment-modal/types/index.d.ts b/x402-payment-modal/types/index.d.ts
index a40852524..dfdaa472a 100644
--- a/x402-payment-modal/types/index.d.ts
+++ b/x402-payment-modal/types/index.d.ts
@@ -116,9 +116,8 @@ export const version: string;
/** Solana USDC mint (mainnet). */
export const USDC_MINT_SOLANA: string;
-/** THREE — an optional, opt-in token mint recognized by the modal so a 402
- * `accept` using it renders with the right symbol/decimals without
- * merchant-supplied metadata. Never a default; USDC is the default asset. */
+/** $THREE — the three.ws utility token mint. Recognized by the modal so a 402
+ * `accept` using it renders as THREE without merchant-supplied metadata. */
export const THREE_MINT: string;
export interface KnownSolanaToken {
diff --git a/x402-payment-modal/types/server.d.ts b/x402-payment-modal/types/server.d.ts
index ae0d4931a..71916f400 100644
--- a/x402-payment-modal/types/server.d.ts
+++ b/x402-payment-modal/types/server.d.ts
@@ -47,7 +47,7 @@ export const NETWORK_SOLANA_DEVNET: string;
/** Solana USDC mint (mainnet). */
export const USDC_MINT_SOLANA: string;
-/** THREE — an optional, opt-in token mint (not a default; USDC is the default). */
+/** $THREE — the three.ws utility token mint. */
export const THREE_MINT: string;
export interface WellKnownToken {