@three-ws/x402-modal 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,180 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other transformations
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contribution embodied within the Work constitutes direct or contributory
82
+ patent infringement, then any patent licenses granted to You under
83
+ this License for that Work shall terminate as of the date such
84
+ litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the License.
117
+
118
+ You may add Your own license statement for Your modifications and
119
+ may provide additional grant of rights to use, copy, modify, merge,
120
+ publish, distribute, sublicense, and/or sell copies of the
121
+ Derivative Works, and to permit persons to whom the Derivative Works
122
+ are furnished to do so.
123
+
124
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
125
+ any Contribution intentionally submitted for inclusion in the Work
126
+ by You to the Licensor shall be under the terms and conditions of
127
+ this License, without any additional terms or conditions.
128
+ Notwithstanding the above, nothing herein shall supersede or modify
129
+ the terms of any separate license agreement you may have executed
130
+ with Licensor regarding such Contributions.
131
+
132
+ 6. Trademarks. This License does not grant permission to use the trade
133
+ names, trademarks, service marks, or product names of the Licensor,
134
+ except as required for reasonable and customary use in describing the
135
+ origin of the Work and reproducing the content of the NOTICE file.
136
+
137
+ 7. Disclaimer of Warranty. Unless required by applicable law or
138
+ agreed to in writing, Licensor provides the Work (and each
139
+ Contributor provides its Contributions) on an "AS IS" BASIS,
140
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
141
+ implied, including, without limitation, any warranties or conditions
142
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
143
+ PARTICULAR PURPOSE. You are solely responsible for determining the
144
+ appropriateness of using or reproducing the Work and assume any
145
+ risks associated with Your exercise of permissions under this License.
146
+
147
+ 8. Limitation of Liability. In no event and under no legal theory,
148
+ whether in tort (including negligence), contract, or otherwise,
149
+ unless required by applicable law (such as deliberate and grossly
150
+ negligent acts) or agreed to in writing, shall any Contributor be
151
+ liable to You for damages, including any direct, indirect, special,
152
+ incidental, or exemplary damages of any character arising as a
153
+ result of this License or out of the use or inability to use the
154
+ Work (including but not limited to damages for loss of goodwill,
155
+ work stoppage, computer failure or malfunction, or all other
156
+ commercial damages or losses), even if such Contributor has been
157
+ advised of the possibility of such damages.
158
+
159
+ 9. Accepting Warranty or Additional Liability. While redistributing
160
+ the Work or Derivative Works thereof, You may choose to offer,
161
+ and charge a fee for, acceptance of support, warranty, indemnity,
162
+ or other liability obligations and/or rights consistent with this
163
+ License. However, in accepting such obligations, You may offer only
164
+ conditions consistent with this License.
165
+
166
+ END OF TERMS AND CONDITIONS
167
+
168
+ Copyright 2026 nirholas
169
+
170
+ Licensed under the Apache License, Version 2.0 (the "License");
171
+ you may not use this file except in compliance with the License.
172
+ You may obtain a copy of the License at
173
+
174
+ http://www.apache.org/licenses/LICENSE-2.0
175
+
176
+ Unless required by applicable law or agreed to in writing, software
177
+ distributed under the License is distributed on an "AS IS" BASIS,
178
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
179
+ See the License for the specific language governing permissions and
180
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,306 @@
1
+ <div align="center">
2
+
3
+ # @three-ws/x402-modal
4
+
5
+ **A drop-in payment modal for any [x402](https://x402.org) paid endpoint.**
6
+
7
+ One script tag turns an HTTP `402 Payment Required` into a polished checkout:
8
+ wallet connect (Phantom on Solana, MetaMask/EVM via EIP-3009), the
9
+ `402 → sign → settle` flow, SIWX re-entry, spending caps, and a receipt — all
10
+ in **vanilla JS, with no bundler and no framework**.
11
+
12
+ [![npm](https://img.shields.io/npm/v/@three-ws/x402-modal?logo=npm&color=cb3837)](https://www.npmjs.com/package/@three-ws/x402-modal)
13
+ [![downloads](https://img.shields.io/npm/dm/@three-ws/x402-modal?color=cb3837)](https://www.npmjs.com/package/@three-ws/x402-modal)
14
+ ![license](https://img.shields.io/npm/l/@three-ws/x402-modal?color=3b82f6)
15
+ ![node](https://img.shields.io/node/v/@three-ws/x402-modal?color=339933&logo=node.js)
16
+
17
+ [Quick start](#quick-start) · [How it works](#how-it-works) · [API](#api) · [Configuration](#configuration) · [Backend](#the-backend) · [Tutorials](./TUTORIAL.md) · [FAQ](#faq)
18
+
19
+ </div>
20
+
21
+ ---
22
+
23
+ ## Why
24
+
25
+ [x402](https://x402.org) revives HTTP `402 Payment Required` as a real payment
26
+ rail: a server answers a request with a `402` whose body lists what it
27
+ `accepts` (asset, amount, network, pay-to), the client pays, and re-sends the
28
+ request with an `X-PAYMENT` header. It's perfect for pay-per-call APIs, agent
29
+ economies, and content paywalls — but every merchant ends up rebuilding the same
30
+ fiddly client: parse the challenge, connect a wallet, sign the right thing for
31
+ the right chain, retry, settle, show a receipt.
32
+
33
+ **This package is that client, done once and done well.** Point it at a `402`
34
+ endpoint and it renders the entire flow. The EVM/Base path is 100%
35
+ client-side. The Solana path needs one small backend helper (see
36
+ [The backend](#the-backend)).
37
+
38
+ ## Quick start
39
+
40
+ ### 1 — One script tag (zero JS)
41
+
42
+ ```html
43
+ <script type="module" src="https://unpkg.com/@three-ws/x402-modal/global"></script>
44
+
45
+ <button
46
+ data-x402-endpoint="https://api.example.com/paid/summarize"
47
+ data-x402-method="POST"
48
+ data-x402-body='{"text":"hello world"}'
49
+ data-x402-merchant="Acme"
50
+ data-x402-action="Summarize">
51
+ Pay &amp; summarize
52
+ </button>
53
+ ```
54
+
55
+ Clicking the button opens the modal, runs the payment, calls the endpoint, and
56
+ fires an `x402:result` event on the button with `{ ok, result, payment, response }`:
57
+
58
+ ```js
59
+ document.querySelector('button').addEventListener('x402:result', (e) => {
60
+ console.log('paid + got result:', e.detail.result);
61
+ });
62
+ ```
63
+
64
+ ### 2 — Programmatic (full control)
65
+
66
+ ```js
67
+ import { pay } from '@three-ws/x402-modal';
68
+
69
+ const out = await pay({
70
+ endpoint: '/api/paid/summarize',
71
+ method: 'POST',
72
+ body: { text: 'hello world' },
73
+ merchant: 'Acme',
74
+ action: 'Summarize',
75
+ });
76
+
77
+ console.log(out.result); // the endpoint's response, after settlement
78
+ console.log(out.payment); // { network, payer, transaction }
79
+ ```
80
+
81
+ `pay()` resolves once the paid call returns `200`, or rejects with an `Error`
82
+ whose `.code === 'cancelled'` if the user closes the modal.
83
+
84
+ ### 3 — Self-hosted, fully branded
85
+
86
+ ```html
87
+ <script
88
+ type="module"
89
+ src="https://your.cdn/x402.global.js"
90
+ data-x402-api-origin="https://pay.your-company.com"
91
+ data-x402-brand-label="Powered by Acme"
92
+ data-x402-brand-href="https://acme.com"></script>
93
+ ```
94
+
95
+ or from JS, before the first `pay()`:
96
+
97
+ ```js
98
+ import { configure } from '@three-ws/x402-modal';
99
+
100
+ configure({
101
+ apiOrigin: 'https://pay.your-company.com', // Solana checkout backend
102
+ brand: { label: 'Powered by Acme', href: 'https://acme.com' },
103
+ });
104
+ ```
105
+
106
+ > **No dependencies to install.** The ESM build leaves the two optional wallet
107
+ > libraries (`@solana/web3.js` for Solana, a keccak for EVM sign-in) as runtime
108
+ > CDN imports, fetched only when that wallet path actually runs. The `/global`
109
+ > build is a single self-contained file.
110
+
111
+ ## How it works
112
+
113
+ ```
114
+ pay({ endpoint })
115
+
116
+ ├─ 1. discover GET/POST endpoint → 402 (or 401 + payment-required header)
117
+ │ parse `accepts[]` (asset · amount · network · payTo)
118
+
119
+ ├─ 2. connect pick a wallet that can satisfy an accept:
120
+ │ Solana → Phantom EVM → MetaMask / window.ethereum
121
+
122
+ ├─ 3. authorize Solana: backend builds the tx → Phantom signs it
123
+ │ EVM: wallet signs an EIP-3009 transferWithAuthorization
124
+ │ (no on-chain tx, no gas for the payer)
125
+
126
+ └─ 4. verify re-send the request with `X-PAYMENT` → endpoint runs the work,
127
+ settles on-chain, returns 200 + `x-payment-response` receipt
128
+ ```
129
+
130
+ Each step renders as a live row in the modal (spinner → check → error), with a
131
+ **Try again** affordance on failure, automatic retry on a `429` upstream
132
+ throttle (the payment isn't settled until the work succeeds, so re-sending can't
133
+ double-charge), and a receipt with an explorer link on success.
134
+
135
+ ### Networks
136
+
137
+ | Network | Wallet | Scheme | Needs a backend? |
138
+ |---|---|---|---|
139
+ | **Base** (`eip155:8453`) | MetaMask / any `window.ethereum` | EIP-3009 `transferWithAuthorization` | **No** — fully client-side |
140
+ | Base Sepolia, Arbitrum, Optimism | same | EIP-3009 | No |
141
+ | **Solana** (`solana:*`) | Phantom | `exact` (facilitator-settled) | Yes — `prepare`/`encode` helper |
142
+
143
+ When a `402` advertises more than one network the modal shows a wallet picker;
144
+ when it advertises exactly one, it goes straight there.
145
+
146
+ ## API
147
+
148
+ ### `pay(options): Promise<PayResult>`
149
+
150
+ | option | type | default | notes |
151
+ |---------------|-------------------------------|--------------------|-------|
152
+ | `endpoint` | `string` | — (**required**) | the x402-protected URL to pay for and call |
153
+ | `method` | `string` | `GET` / `POST`* | *POST when a `body` is set |
154
+ | `body` | `object \| string` | — | forwarded to the endpoint (object → JSON) |
155
+ | `headers` | `Record<string,string>` | — | merged into discovery + paid calls |
156
+ | `merchant` | `string` | `Payment` | shown in the modal header |
157
+ | `action` | `string` | `Pay-per-call` | shown in the modal header |
158
+ | `caps` | `{ maxPerCall, maxPerHour, maxPerDay }` | — | µUSD spending caps (see [Configuration](#configuration)) |
159
+ | `autoConnect` | `boolean` | `false` | skip the picker when exactly one wallet is detected |
160
+ | `apiOrigin` | `string` | global config | per-call override of the Solana checkout backend |
161
+ | `brand` | `{ label, href }` | global config | per-call footer override |
162
+
163
+ Returns `{ ok: true, result, payment?, siwx?, response }`. `payment` is present
164
+ on a fresh payment (`{ network, payer, transaction }`); `siwx` is present when
165
+ the user re-entered via sign-in instead of paying.
166
+
167
+ ### `configure(config): config` · `getConfig(): config`
168
+
169
+ Set global defaults once at startup. See [Configuration](#configuration).
170
+
171
+ ### `init(): void`
172
+
173
+ Scan the document and bind every `[data-x402-endpoint]` element. The `/global`
174
+ build calls this automatically (and re-scans on DOM mutation); call it yourself
175
+ only when using the ESM build with declarative buttons.
176
+
177
+ ### DOM events (declarative usage)
178
+
179
+ Bound elements dispatch bubbling `CustomEvent`s:
180
+
181
+ - `x402:result` — `detail` is the full `PayResult`.
182
+ - `x402:error` — `detail` is `{ error: string }`. (Cancellation does **not** fire this.)
183
+ - `x402:siwx-signed` — `detail` is `{ address, network }`, when re-entry was via SIWX.
184
+
185
+ ### `data-*` attributes (declarative usage)
186
+
187
+ `data-x402-endpoint` (required), `data-x402-method`, `data-x402-body` (JSON),
188
+ `data-x402-headers` (JSON), `data-x402-caps` (JSON), `data-x402-api-origin`,
189
+ `data-x402-merchant`, `data-x402-action`.
190
+
191
+ ## Configuration
192
+
193
+ All fields are optional; the defaults reproduce the hosted three.ws modal.
194
+
195
+ ```js
196
+ configure({
197
+ // Origin serving the Solana prepare/encode checkout helpers. Only the Solana
198
+ // path uses it; the EVM path needs no backend. null → resolve from the
199
+ // script's own origin; '' → same-origin.
200
+ apiOrigin: 'https://pay.example.com',
201
+
202
+ // Footer attribution.
203
+ brand: { label: 'Powered by Acme', href: 'https://acme.com' },
204
+
205
+ // ERC-8021 builder-code self-attribution, echoed back only when the 402
206
+ // challenge declares a builder code. null disables the echo.
207
+ builderCode: { wallet: 'acme', service: 'acme_checkout' },
208
+
209
+ // Override the on-demand CDN modules (e.g. to self-host under a strict CSP).
210
+ solanaWeb3Url: 'https://esm.sh/@solana/web3.js@1.95.3?bundle',
211
+ nobleHashesUrl: 'https://esm.sh/@noble/hashes@1.4.0/sha3?bundle',
212
+ });
213
+ ```
214
+
215
+ ### Spending caps
216
+
217
+ Caps are enforced in `localStorage`, bucketed by rolling UTC hour and day, and
218
+ survive reloads. Amounts are **micro-USD** (`1_000_000` = `$1`). A failed payment
219
+ rolls its reservation back.
220
+
221
+ ```js
222
+ await pay({
223
+ endpoint: '/api/paid/x',
224
+ caps: {
225
+ maxPerCall: 1_000_000, // $1.00 per call
226
+ maxPerHour: 10_000_000, // $10/hour
227
+ maxPerDay: 50_000_000, // $50/day
228
+ },
229
+ });
230
+ ```
231
+
232
+ Stablecoins (USDC, USDT, DAI) are converted to µUSD exactly. Non-stable assets
233
+ pass through atomic in the browser (no price feed is fetched to keep the script
234
+ dependency-free) — enforce those server-side.
235
+
236
+ ## The backend
237
+
238
+ **EVM / Base needs no backend.** The payer signs an EIP-3009
239
+ `transferWithAuthorization` in their wallet and the modal sends the signed
240
+ authorization straight to your merchant endpoint as `X-PAYMENT`. Your x402
241
+ server (and its facilitator) verify and settle it.
242
+
243
+ **Solana needs one tiny helper**, because building a Solana transfer transaction
244
+ requires RPC access and the facilitator's fee-payer. The modal expects two
245
+ actions at `{apiOrigin}/api/x402-checkout`:
246
+
247
+ | action | request | response |
248
+ |---|---|---|
249
+ | `?action=prepare` | `{ accept, buyer }` | `{ tx_base64 }` — an unsigned/partially-signed `VersionedTransaction` |
250
+ | `?action=encode` | `{ accept, signed_tx_base64, resource_url, builder_code? }` | `{ x_payment }` — the base64 `X-PAYMENT` value to send to the merchant |
251
+
252
+ `apiOrigin` defaults to the origin that served the script, so when you self-host
253
+ both the script and this helper there is nothing to configure. See
254
+ [`docs/BACKEND.md`](./docs/BACKEND.md) for the full contract and a reference
255
+ implementation, and [`examples/`](./examples) for runnable code.
256
+
257
+ ## Install
258
+
259
+ ```sh
260
+ npm i @three-ws/x402-modal
261
+ ```
262
+
263
+ ```js
264
+ import { pay, configure } from '@three-ws/x402-modal'; // ESM, no side effects
265
+ ```
266
+
267
+ or skip the install entirely and use the CDN `/global` build (auto-binds
268
+ `[data-x402-endpoint]`, exposes `window.X402`).
269
+
270
+ ## Security notes
271
+
272
+ - The modal **never holds keys**. Signing happens in the user's wallet; the
273
+ signed payload goes to your endpoint.
274
+ - A `429` from the merchant is retried with the *same* signed payment — safe,
275
+ because x402 settles only after the work succeeds.
276
+ - Upstream throttle/billing text is never relayed to the buyer verbatim.
277
+ - All endpoint-supplied strings are HTML-escaped before rendering.
278
+ - For the Solana path, the dynamic CDN import can be blocked by a strict
279
+ Content-Security-Policy; either allow it, repoint it via `solanaWeb3Url`, or
280
+ steer users to the dependency-free Base path.
281
+
282
+ ## FAQ
283
+
284
+ **Do I need a wallet adapter / WalletConnect?** No. Solana uses the injected
285
+ Phantom provider; EVM uses the injected `window.ethereum`.
286
+
287
+ **Does the payer pay gas?** On EVM, no — EIP-3009 is a gasless signed
288
+ authorization your facilitator submits. On Solana the facilitator is the
289
+ fee-payer.
290
+
291
+ **Can I theme it?** It ships a self-contained stylesheet with light/dark
292
+ (`prefers-color-scheme`) support. Override the `.x402-*` classes, or set
293
+ `brand` for the footer. The header reflects `merchant` / `action`.
294
+
295
+ **Framework support?** It's framework-agnostic. Import `pay()` and call it from
296
+ a React/Vue/Svelte handler, or drop the `/global` script and use `data-*`
297
+ buttons.
298
+
299
+ **Where does this run in production?** This is the same modal that powers
300
+ payments on [three.ws](https://three.ws); the package is its standalone,
301
+ configurable home.
302
+
303
+ ## License
304
+
305
+ [Apache-2.0](./LICENSE) © three.ws. Part of the [three.ws](https://three.ws)
306
+ platform for building, animating, rigging, and monetizing 3D AI agents.