@bwalletx/connect 0.3.0 → 0.4.1

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.
@@ -0,0 +1,404 @@
1
+ import {
2
+ BWALLETX_RDNS,
3
+ RDNS_EXTENSION,
4
+ pairBwalletX,
5
+ restorePairing
6
+ } from "./chunk-NNMUSWPG.js";
7
+
8
+ // src/pay.ts
9
+ import { P2PKH, PublicKey, Transaction, Utils } from "@bsv/sdk";
10
+ var BRC29_PROTOCOL = [2, "3241645161d8"];
11
+ var PaymentError = class extends Error {
12
+ constructor(code, message, maybeSent = false, cause) {
13
+ super(message);
14
+ this.code = code;
15
+ this.maybeSent = maybeSent;
16
+ this.cause = cause;
17
+ this.name = "PaymentError";
18
+ }
19
+ code;
20
+ maybeSent;
21
+ cause;
22
+ };
23
+ var isLegacy = (s) => typeof s.pay === "function" && typeof s.createAction !== "function";
24
+ var isIdentityKeyHex = (s) => /^0[23][0-9a-fA-F]{64}$/.test(s);
25
+ var isPaymail = (s) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s);
26
+ function randomB64(n) {
27
+ const b = new Uint8Array(n);
28
+ globalThis.crypto.getRandomValues(b);
29
+ return Utils.toBase64(Array.from(b));
30
+ }
31
+ function opReturn(text) {
32
+ const d = Utils.toArray(text, "utf8");
33
+ const len = d.length;
34
+ const push = len < 76 ? [len] : len <= 255 ? [76, len] : [77, len & 255, len >> 8];
35
+ return Utils.toHex([0, 106, ...push, ...d]);
36
+ }
37
+ var clip = (s, n) => s.length > n ? s.slice(0, n - 1) + "\u2026" : s;
38
+ var describe = (s) => clip(s.length < 5 ? `${s} payment`.trim() : s, 50);
39
+ async function usdRate(o) {
40
+ if (typeof o.usdPerBsv === "number") return o.usdPerBsv;
41
+ try {
42
+ if (typeof o.usdPerBsv === "function") return await o.usdPerBsv();
43
+ const r = await (o.fetch ?? fetch)("https://api.whatsonchain.com/v1/bsv/main/exchangerate");
44
+ const j = await r.json();
45
+ if (!r.ok || !(Number(j.rate) > 0)) throw new Error(`status ${r.status}`);
46
+ return Number(j.rate);
47
+ } catch (e) {
48
+ throw new PaymentError("RATE_FAILED", `Could not get the BSV/USD rate: ${e.message}`, false, e);
49
+ }
50
+ }
51
+ async function amountInSats(req, o = {}) {
52
+ if (req.sats != null) {
53
+ if (!Number.isSafeInteger(req.sats) || req.sats <= 0) throw new PaymentError("BAD_REQUEST", "sats must be a positive integer");
54
+ return req.sats;
55
+ }
56
+ if (req.usd != null) {
57
+ if (!(req.usd > 0)) throw new PaymentError("BAD_REQUEST", "usd must be positive");
58
+ return Math.max(1, Math.ceil(req.usd / await usdRate(o) * 1e8));
59
+ }
60
+ throw new PaymentError("BAD_REQUEST", "Give sats or usd");
61
+ }
62
+ async function resolvePaymailP2P(paymail, sats, f = fetch) {
63
+ const [alias, domain] = paymail.split("@");
64
+ const fail = (m, e) => new PaymentError("RESOLVE_FAILED", `Could not resolve ${paymail}: ${m}`, false, e);
65
+ let caps;
66
+ try {
67
+ const r = await f(`https://${domain}/.well-known/bsvalias`);
68
+ caps = (await r.json()).capabilities;
69
+ } catch (e) {
70
+ throw fail("no bsvalias document (or CORS blocked it; resolve on your server and pass resolvePaymail)", e);
71
+ }
72
+ const fill = (u) => u.replace("{alias}", encodeURIComponent(alias)).replace("{domain.tld}", domain);
73
+ const dest = caps?.["2a40af698840"];
74
+ if (!dest) throw fail("it does not offer P2P payment destinations");
75
+ let body;
76
+ try {
77
+ const r = await f(fill(dest), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ satoshis: sats }) });
78
+ if (!r.ok) throw new Error(`status ${r.status}`);
79
+ body = await r.json();
80
+ } catch (e) {
81
+ throw fail(e.message, e);
82
+ }
83
+ if (!body.outputs?.length) throw fail("no outputs returned");
84
+ const receive = caps["5f1323cddf31"];
85
+ return {
86
+ outputs: body.outputs.map((o) => ({ script: o.script, satoshis: o.satoshis })),
87
+ reference: body.reference,
88
+ submit: receive ? async (hex) => {
89
+ await f(fill(receive), {
90
+ method: "POST",
91
+ headers: { "content-type": "application/json" },
92
+ body: JSON.stringify({ hex, reference: body.reference, metadata: {} })
93
+ });
94
+ } : void 0
95
+ };
96
+ }
97
+ async function runAction(wallet, description, outputs, labels) {
98
+ try {
99
+ return await wallet.createAction({
100
+ description: describe(description),
101
+ outputs: outputs.map((o) => ({ lockingScript: o.script, satoshis: o.satoshis, outputDescription: describe(o.description ?? "payment") })),
102
+ labels: labels?.length ? labels : void 0,
103
+ options: { randomizeOutputs: false }
104
+ });
105
+ } catch (e) {
106
+ const msg = e?.message ?? String(e);
107
+ const rejected = /denied|reject|cancel|abort|user/i.test(msg) || e?.code === 4001;
108
+ throw new PaymentError(rejected ? "WALLET_REJECTED" : "WALLET_ERROR", rejected ? "The payment was declined in the wallet." : `The wallet could not make the payment: ${msg}`, !rejected, e);
109
+ }
110
+ }
111
+ async function pay(source, req, o = {}) {
112
+ const to = (req.to ?? "").trim();
113
+ if (!to) throw new PaymentError("BAD_REQUEST", "Give a recipient (to)");
114
+ if (req.memo && req.memo.length > 1e3) throw new PaymentError("BAD_REQUEST", "memo is too long");
115
+ const sats = await amountInSats(req, o);
116
+ if (isLegacy(source)) return source.pay({ ...req, to, sats });
117
+ let outputs;
118
+ let remittance;
119
+ let submit;
120
+ if (isIdentityKeyHex(to)) {
121
+ const derivationPrefix = randomB64(8);
122
+ const derivationSuffix = randomB64(8);
123
+ let pk;
124
+ let me;
125
+ try {
126
+ ({ publicKey: pk } = await source.getPublicKey({ protocolID: BRC29_PROTOCOL, keyID: `${derivationPrefix} ${derivationSuffix}`, counterparty: to.toLowerCase() }));
127
+ ({ publicKey: me } = await source.getPublicKey({ identityKey: true }));
128
+ } catch (e) {
129
+ throw new PaymentError("WALLET_ERROR", `The wallet could not derive the payment key: ${e.message}`, false, e);
130
+ }
131
+ outputs = [{ script: new P2PKH().lock(PublicKey.fromString(pk).toHash()).toHex(), satoshis: sats, description: "payment" }];
132
+ remittance = { senderIdentityKey: me, derivationPrefix, derivationSuffix, outputIndex: 0 };
133
+ } else if (isPaymail(to)) {
134
+ const r2 = await (o.resolvePaymail ?? ((p, s) => resolvePaymailP2P(p, s, o.fetch ?? fetch)))(to, sats);
135
+ outputs = r2.outputs;
136
+ submit = r2.submit;
137
+ } else {
138
+ try {
139
+ outputs = [{ script: new P2PKH().lock(to).toHex(), satoshis: sats, description: "payment" }];
140
+ } catch {
141
+ throw new PaymentError("BAD_REQUEST", `Not a paymail, address or identity key: ${to}`);
142
+ }
143
+ }
144
+ if (req.memo && req.memoOnChain) outputs = [...outputs, { script: opReturn(req.memo), satoshis: 0, description: "memo" }];
145
+ const r = await runAction(source, req.memo || `Pay ${clip(to, 30)}`, outputs, req.labels);
146
+ if (!r.txid) throw new PaymentError("WALLET_ERROR", "The wallet did not return a txid", true);
147
+ const tx = r.tx ? Array.from(r.tx) : void 0;
148
+ if (submit && tx) {
149
+ await submit(Transaction.fromAtomicBEEF(tx).toHex()).catch(() => {
150
+ });
151
+ }
152
+ return { txid: r.txid, tx, sats, outputs, remittance };
153
+ }
154
+ function tip(source, req, o = {}) {
155
+ return pay(source, { memo: "Tip", ...req, labels: [...req.labels ?? [], "tip"] }, o);
156
+ }
157
+ async function buyToken(source, req) {
158
+ if (isLegacy(source)) throw new PaymentError("NOT_SUPPORTED", "This wallet cannot buy tokens. Use a BRC-100 wallet such as bWalletX.");
159
+ const q = await req.quote({ token: req.token, amount: req.amount });
160
+ if (!q?.outputs?.length) throw new PaymentError("BAD_REQUEST", "The quote returned no outputs");
161
+ const sats = q.outputs.reduce((n, x) => n + x.satoshis, 0);
162
+ const r = await runAction(source, q.description ?? `Buy ${clip(req.token, 30)}`, q.outputs, [...req.labels ?? [], "token-buy"]);
163
+ if (!r.txid) throw new PaymentError("WALLET_ERROR", "The wallet did not return a txid", true);
164
+ const res = { txid: r.txid, tx: r.tx ? Array.from(r.tx) : void 0, sats, outputs: q.outputs };
165
+ await q.onPaid?.(res);
166
+ return res;
167
+ }
168
+
169
+ // src/wallets.ts
170
+ import { WalletClient } from "@bsv/sdk";
171
+ async function brc100Connected(wallet, o) {
172
+ await wallet.waitForAuthentication({}).catch(() => {
173
+ });
174
+ const { publicKey } = await wallet.getPublicKey({ identityKey: true });
175
+ return { wallet, payer: wallet, identityKey: publicKey, optionId: o.id, kind: o.kind };
176
+ }
177
+ function brc100Option(wallet, info) {
178
+ const opt = {
179
+ id: info.id,
180
+ name: info.name,
181
+ icon: info.icon,
182
+ rdns: info.rdns,
183
+ kind: "brc100",
184
+ isBwalletX: info.isBwalletX ?? false,
185
+ connect: () => brc100Connected(wallet, opt)
186
+ };
187
+ return opt;
188
+ }
189
+ function pairingOption(pairing) {
190
+ const opt = {
191
+ id: "bwalletx-pairing",
192
+ name: "bWalletX on your phone",
193
+ kind: "pairing",
194
+ isBwalletX: true,
195
+ async connect() {
196
+ const p = typeof pairing === "function" ? pairing() : pairing;
197
+ const w = await restorePairing(p) ?? await pairBwalletX(p);
198
+ return brc100Connected(w, opt);
199
+ }
200
+ };
201
+ return opt;
202
+ }
203
+ function handcashAdapter(o) {
204
+ const opt = {
205
+ id: "handcash",
206
+ name: "HandCash",
207
+ icon: o.icon,
208
+ kind: "handcash",
209
+ isBwalletX: false,
210
+ async connect() {
211
+ const p = await o.login();
212
+ return {
213
+ wallet: null,
214
+ payer: o.pay ? { pay: o.pay } : null,
215
+ identityKey: p.identityKey ?? null,
216
+ handle: p.handle,
217
+ paymail: p.paymail ?? `${p.handle.replace(/^\$/, "")}@handcash.io`,
218
+ optionId: opt.id,
219
+ kind: "handcash",
220
+ transitional: true
221
+ };
222
+ }
223
+ };
224
+ return opt;
225
+ }
226
+ var NAMES = { [RDNS_EXTENSION]: "bWalletX", "space.bwallet.mobile": "bWalletX" };
227
+ async function probe(substrate, ms) {
228
+ try {
229
+ const w = new WalletClient(substrate);
230
+ const ok = await Promise.race([w.isAuthenticated({}).then(() => true), new Promise((r) => setTimeout(() => r(false), ms))]);
231
+ return ok ? w : null;
232
+ } catch {
233
+ return null;
234
+ }
235
+ }
236
+ async function discoverWallets(o = {}) {
237
+ const out = [];
238
+ const ms = o.ms ?? 1200;
239
+ if (typeof window !== "undefined") {
240
+ const seen = /* @__PURE__ */ new Map();
241
+ const onAnnounce = (e) => {
242
+ const d = e.detail;
243
+ if (!d?.wallet) return;
244
+ const rdns = d.info?.rdns ?? d.info?.uuid ?? `wallet-${seen.size}`;
245
+ if (seen.has(rdns)) return;
246
+ const isB = BWALLETX_RDNS.includes(rdns);
247
+ seen.set(rdns, brc100Option(d.wallet, { id: rdns, rdns, name: NAMES[rdns] ?? d.info?.name ?? rdns, icon: d.info?.icon, isBwalletX: isB }));
248
+ };
249
+ window.addEventListener("brc100:announceWallet", onAnnounce);
250
+ window.dispatchEvent(new Event("brc100:requestWallet"));
251
+ const local = o.probeLocal ? Promise.all([probe("json-api", ms), probe("Cicada", ms)]) : Promise.resolve([null, null]);
252
+ await new Promise((r) => setTimeout(r, ms));
253
+ window.removeEventListener("brc100:announceWallet", onAnnounce);
254
+ out.push(...seen.values());
255
+ const cwi = window.CWI;
256
+ if (cwi && ![...seen.values()].some((x) => x.rdns === "space.bwallet.mobile")) {
257
+ out.push(brc100Option(cwi, { id: "window.CWI", name: "This app\u2019s wallet", isBwalletX: false }));
258
+ }
259
+ const [json, cicada] = await local;
260
+ if (json) out.push(brc100Option(json, { id: "localhost:3321", name: "Desktop wallet (localhost:3321)" }));
261
+ if (cicada) out.push(brc100Option(cicada, { id: "localhost:3301", name: "Desktop wallet (localhost:3301)" }));
262
+ }
263
+ if (o.pairing) out.push(pairingOption(o.pairing));
264
+ out.push(...o.extra ?? []);
265
+ const rank = (w) => w.isBwalletX ? 0 : w.kind === "handcash" ? 2 : 1;
266
+ return out.map((w, i) => ({ w, i })).sort((a, b) => rank(a.w) - rank(b.w) || a.i - b.i).map((x) => x.w);
267
+ }
268
+
269
+ // src/modal.ts
270
+ import qrcode from "qrcode-generator";
271
+ var CSS = `
272
+ .bwx-ov{position:fixed;inset:0;z-index:2147483000;background:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;padding:16px;font:15px/1.4 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
273
+ .bwx-box{background:#0b0b0b;color:#f4f1e8;border:1px solid #3a3220;border-radius:16px;width:min(360px,100%);padding:20px;box-shadow:0 20px 60px rgba(0,0,0,.5)}
274
+ .bwx-box h2{margin:0 0 6px;font-size:18px;color:#e8c766}
275
+ .bwx-box p{margin:0 0 14px;color:#bdb6a3;font-size:14px}
276
+ .bwx-qr{background:#fff;border-radius:12px;padding:12px;display:flex;justify-content:center}
277
+ .bwx-qr svg{width:100%;height:auto;max-width:260px}
278
+ .bwx-code{margin:14px 0 0;text-align:center;font-size:28px;letter-spacing:.3em;color:#e8c766;font-variant-numeric:tabular-nums}
279
+ .bwx-row{display:flex;gap:8px;margin-top:14px}
280
+ .bwx-btn{flex:1;border:1px solid #3a3220;background:#15130e;color:#f4f1e8;border-radius:10px;padding:10px 12px;font:inherit;cursor:pointer}
281
+ .bwx-btn:hover{border-color:#e8c766}
282
+ .bwx-list{display:flex;flex-direction:column;gap:8px}
283
+ .bwx-opt{display:flex;align-items:center;gap:10px;text-align:left}
284
+ .bwx-opt img{width:24px;height:24px;border-radius:6px}
285
+ .bwx-tag{margin-left:auto;font-size:11px;color:#8d866f}
286
+ `;
287
+ function mount() {
288
+ const root = document.createElement("div");
289
+ root.className = "bwx-ov";
290
+ root.setAttribute("role", "dialog");
291
+ root.setAttribute("aria-modal", "true");
292
+ const style = document.createElement("style");
293
+ style.textContent = CSS;
294
+ const box = document.createElement("div");
295
+ box.className = "bwx-box";
296
+ root.append(style, box);
297
+ document.body.appendChild(root);
298
+ return { root, box, close: () => root.remove() };
299
+ }
300
+ function el(tag, cls, text) {
301
+ const e = document.createElement(tag);
302
+ if (cls) e.className = cls;
303
+ if (text != null) e.textContent = text;
304
+ return e;
305
+ }
306
+ function qrSvg(text) {
307
+ const q = qrcode(0, "M");
308
+ q.addData(text);
309
+ q.make();
310
+ return q.createSvgTag({ cellSize: 4, margin: 2, scalable: true });
311
+ }
312
+ function pairingModal(o = {}) {
313
+ const ac = new AbortController();
314
+ let ui = null;
315
+ let codeEl = null;
316
+ const close = () => {
317
+ ui?.close();
318
+ ui = null;
319
+ };
320
+ ac.signal.addEventListener("abort", close);
321
+ return {
322
+ signal: ac.signal,
323
+ close,
324
+ onLink(link) {
325
+ if (typeof document === "undefined") return;
326
+ close();
327
+ ui = mount();
328
+ const h = el("h2", "", o.title ?? "Connect bWalletX");
329
+ const p = el("p", "", "Scan with bWalletX on your phone, or paste the link into web.bwalletx.com.");
330
+ const qr = el("div", "bwx-qr");
331
+ qr.innerHTML = qrSvg(link);
332
+ codeEl = el("div", "bwx-code", "");
333
+ codeEl.setAttribute("aria-live", "polite");
334
+ const row = el("div", "bwx-row");
335
+ const copy = el("button", "bwx-btn", "Copy link");
336
+ copy.onclick = () => void navigator.clipboard?.writeText(link).then(() => copy.textContent = "Copied");
337
+ const cancel = el("button", "bwx-btn", "Cancel");
338
+ cancel.onclick = () => {
339
+ o.onCancel?.();
340
+ ac.abort();
341
+ };
342
+ row.append(copy, cancel);
343
+ ui.box.append(h, p, qr, codeEl, row);
344
+ },
345
+ onCode(code) {
346
+ if (codeEl) {
347
+ codeEl.textContent = code;
348
+ const p = ui?.box.querySelector("p");
349
+ if (p) p.textContent = "Check bWalletX shows the same code, then tap Connect.";
350
+ }
351
+ }
352
+ };
353
+ }
354
+ function pickWallet(options, o = {}) {
355
+ if (typeof document === "undefined") return Promise.resolve(null);
356
+ return new Promise((resolve) => {
357
+ const ui = mount();
358
+ const done = (w) => {
359
+ ui.close();
360
+ resolve(w);
361
+ };
362
+ ui.box.append(el("h2", "", o.title ?? "Choose a wallet"));
363
+ if (!options.length) ui.box.append(el("p", "", "No wallet found. Get bWalletX at bwalletx.com."));
364
+ const list = el("div", "bwx-list");
365
+ for (const w of options) {
366
+ const b = el("button", "bwx-btn bwx-opt");
367
+ if (w.icon) {
368
+ const img = el("img");
369
+ img.src = w.icon;
370
+ img.alt = "";
371
+ b.append(img);
372
+ }
373
+ b.append(el("span", "", w.name));
374
+ if (w.kind === "handcash") b.append(el("span", "bwx-tag", "until BRC-100"));
375
+ b.onclick = () => done(w);
376
+ list.append(b);
377
+ }
378
+ const cancel = el("button", "bwx-btn", "Cancel");
379
+ cancel.onclick = () => done(null);
380
+ ui.root.onclick = (e) => e.target === ui.root && done(null);
381
+ ui.box.append(list, el("div", "bwx-row"));
382
+ ui.box.lastChild.append(cancel);
383
+ });
384
+ }
385
+
386
+ export {
387
+ BRC29_PROTOCOL,
388
+ PaymentError,
389
+ isIdentityKeyHex,
390
+ isPaymail,
391
+ amountInSats,
392
+ resolvePaymailP2P,
393
+ pay,
394
+ tip,
395
+ buyToken,
396
+ brc100Option,
397
+ pairingOption,
398
+ handcashAdapter,
399
+ discoverWallets,
400
+ qrSvg,
401
+ pairingModal,
402
+ pickWallet
403
+ };
404
+ //# sourceMappingURL=chunk-FUQ46RJV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pay.ts","../src/wallets.ts","../src/modal.ts"],"sourcesContent":["/**\n * Browser-side payment helpers on top of the BRC-100 wallet's createAction. Works with any\n * BRC-100 wallet. Each helper asks the wallet once; it never retries a spend. If a call fails\n * the error says whether the wallet may have sent anything (`maybeSent`).\n */\nimport { P2PKH, PublicKey, Transaction, Utils, type WalletInterface } from '@bsv/sdk';\n\n/** BRC-29 payment protocol id. */\nexport const BRC29_PROTOCOL: [2, string] = [2, '3241645161d8'];\n\nexport type PayTo = string; // paymail (name@domain), P2PKH address, or 66-hex identity key\n\nexport interface PayOutput {\n /** Locking script hex. */\n script: string;\n satoshis: number;\n description?: string;\n}\n\nexport interface PayRequest {\n to: PayTo;\n /** Amount in satoshis. Give this or `usd`. */\n sats?: number;\n /** Amount in US dollars, converted at `usdPerBsv` (or the live WhatsOnChain rate). */\n usd?: number;\n /** Shown in the wallet and, with `memoOnChain`, written in an OP_RETURN output. */\n memo?: string;\n memoOnChain?: boolean;\n /** Labels for the wallet's history. */\n labels?: string[];\n}\n\nexport interface PayOptions {\n /** Fixed rate for `usd`. Otherwise fetched from WhatsOnChain. */\n usdPerBsv?: number | (() => Promise<number>);\n /** Resolve a paymail to outputs. Default: bsvalias P2P payment destination (needs CORS on the paymail host). */\n resolvePaymail?: (paymail: string, sats: number) => Promise<{ outputs: PayOutput[]; reference?: string; submit?: (rawTxHex: string) => Promise<void> }>;\n fetch?: typeof fetch;\n}\n\nexport interface Brc29Remittance {\n senderIdentityKey: string;\n derivationPrefix: string;\n derivationSuffix: string;\n outputIndex: number;\n}\n\nexport interface PayResult {\n txid: string;\n /** Atomic BEEF (BRC-95) if the wallet returned it. Send it to your server's verifyPayment. */\n tx?: number[];\n sats: number;\n outputs: PayOutput[];\n /** For an identity-key payment: what the recipient needs to internalize the output (BRC-29). Deliver it to them. */\n remittance?: Brc29Remittance;\n}\n\nexport type PaymentErrorCode = 'BAD_REQUEST' | 'RESOLVE_FAILED' | 'RATE_FAILED' | 'WALLET_REJECTED' | 'WALLET_ERROR' | 'NOT_SUPPORTED';\n\nexport class PaymentError extends Error {\n constructor(\n readonly code: PaymentErrorCode,\n message: string,\n /** true when the wallet was asked to spend and the outcome is unknown. Check before trying again. */\n readonly maybeSent = false,\n readonly cause?: unknown,\n ) {\n super(message);\n this.name = 'PaymentError';\n }\n}\n\n/** A wallet that is not BRC-100 (the HandCash transitional adapter) can still pay through this. */\nexport interface LegacyPayer {\n pay(req: PayRequest & { sats: number }): Promise<PayResult>;\n}\nexport type PaySource = WalletInterface | LegacyPayer;\n\nconst isLegacy = (s: PaySource): s is LegacyPayer => typeof (s as LegacyPayer).pay === 'function' && typeof (s as WalletInterface).createAction !== 'function';\n\nexport const isIdentityKeyHex = (s: string) => /^0[23][0-9a-fA-F]{64}$/.test(s);\nexport const isPaymail = (s: string) => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(s);\n\nfunction randomB64(n: number) {\n const b = new Uint8Array(n);\n globalThis.crypto.getRandomValues(b);\n return Utils.toBase64(Array.from(b));\n}\n\nfunction opReturn(text: string): string {\n const d = Utils.toArray(text, 'utf8');\n const len = d.length;\n const push = len < 0x4c ? [len] : len <= 0xff ? [0x4c, len] : [0x4d, len & 0xff, len >> 8];\n return Utils.toHex([0x00, 0x6a, ...push, ...d]);\n}\n\nconst clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + '…' : s);\n/** createAction descriptions must be 5–50 bytes. */\nconst describe = (s: string) => clip(s.length < 5 ? `${s} payment`.trim() : s, 50);\n\nasync function usdRate(o: PayOptions): Promise<number> {\n if (typeof o.usdPerBsv === 'number') return o.usdPerBsv;\n try {\n if (typeof o.usdPerBsv === 'function') return await o.usdPerBsv();\n const r = await (o.fetch ?? fetch)('https://api.whatsonchain.com/v1/bsv/main/exchangerate');\n const j = (await r.json()) as { rate?: number };\n if (!r.ok || !(Number(j.rate) > 0)) throw new Error(`status ${r.status}`);\n return Number(j.rate);\n } catch (e) {\n throw new PaymentError('RATE_FAILED', `Could not get the BSV/USD rate: ${(e as Error).message}`, false, e);\n }\n}\n\n/** Satoshis for a request (sats as given, or usd converted, rounded up). */\nexport async function amountInSats(req: Pick<PayRequest, 'sats' | 'usd'>, o: PayOptions = {}): Promise<number> {\n if (req.sats != null) {\n if (!Number.isSafeInteger(req.sats) || req.sats <= 0) throw new PaymentError('BAD_REQUEST', 'sats must be a positive integer');\n return req.sats;\n }\n if (req.usd != null) {\n if (!(req.usd > 0)) throw new PaymentError('BAD_REQUEST', 'usd must be positive');\n return Math.max(1, Math.ceil((req.usd / (await usdRate(o))) * 1e8));\n }\n throw new PaymentError('BAD_REQUEST', 'Give sats or usd');\n}\n\n/** Default paymail resolver: bsvalias P2P Payment Destination (BRC-? / capability 2a40af698840). */\nexport async function resolvePaymailP2P(paymail: string, sats: number, f: typeof fetch = fetch) {\n const [alias, domain] = paymail.split('@');\n const fail = (m: string, e?: unknown) => new PaymentError('RESOLVE_FAILED', `Could not resolve ${paymail}: ${m}`, false, e);\n let caps: Record<string, string>;\n try {\n const r = await f(`https://${domain}/.well-known/bsvalias`);\n caps = ((await r.json()) as { capabilities: Record<string, string> }).capabilities;\n } catch (e) {\n throw fail('no bsvalias document (or CORS blocked it; resolve on your server and pass resolvePaymail)', e);\n }\n const fill = (u: string) => u.replace('{alias}', encodeURIComponent(alias)).replace('{domain.tld}', domain);\n const dest = caps?.['2a40af698840'];\n if (!dest) throw fail('it does not offer P2P payment destinations');\n let body: { outputs?: { script: string; satoshis: number }[]; reference?: string };\n try {\n const r = await f(fill(dest), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ satoshis: sats }) });\n if (!r.ok) throw new Error(`status ${r.status}`);\n body = await r.json();\n } catch (e) {\n throw fail((e as Error).message, e);\n }\n if (!body.outputs?.length) throw fail('no outputs returned');\n const receive = caps['5f1323cddf31'];\n return {\n outputs: body.outputs.map((o) => ({ script: o.script, satoshis: o.satoshis })),\n reference: body.reference,\n submit: receive\n ? async (hex: string) => {\n await f(fill(receive), {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ hex, reference: body.reference, metadata: {} }),\n });\n }\n : undefined,\n };\n}\n\nasync function runAction(wallet: WalletInterface, description: string, outputs: PayOutput[], labels?: string[]) {\n try {\n return await wallet.createAction({\n description: describe(description),\n outputs: outputs.map((o) => ({ lockingScript: o.script, satoshis: o.satoshis, outputDescription: describe(o.description ?? 'payment') })),\n labels: labels?.length ? labels : undefined,\n options: { randomizeOutputs: false },\n });\n } catch (e) {\n const msg = (e as Error)?.message ?? String(e);\n const rejected = /denied|reject|cancel|abort|user/i.test(msg) || (e as { code?: unknown })?.code === 4001;\n // Not retried: a lost reply could mean the wallet already broadcast it.\n throw new PaymentError(rejected ? 'WALLET_REJECTED' : 'WALLET_ERROR', rejected ? 'The payment was declined in the wallet.' : `The wallet could not make the payment: ${msg}`, !rejected, e);\n }\n}\n\n/** Pay a paymail, address or identity key. One wallet prompt; never retried. */\nexport async function pay(source: PaySource, req: PayRequest, o: PayOptions = {}): Promise<PayResult> {\n const to = (req.to ?? '').trim();\n if (!to) throw new PaymentError('BAD_REQUEST', 'Give a recipient (to)');\n if (req.memo && req.memo.length > 1000) throw new PaymentError('BAD_REQUEST', 'memo is too long');\n const sats = await amountInSats(req, o);\n if (isLegacy(source)) return source.pay({ ...req, to, sats });\n\n let outputs: PayOutput[];\n let remittance: Brc29Remittance | undefined;\n let submit: ((hex: string) => Promise<void>) | undefined;\n if (isIdentityKeyHex(to)) {\n const derivationPrefix = randomB64(8);\n const derivationSuffix = randomB64(8);\n let pk: string;\n let me: string;\n try {\n ({ publicKey: pk } = await source.getPublicKey({ protocolID: BRC29_PROTOCOL, keyID: `${derivationPrefix} ${derivationSuffix}`, counterparty: to.toLowerCase() }));\n ({ publicKey: me } = await source.getPublicKey({ identityKey: true }));\n } catch (e) {\n throw new PaymentError('WALLET_ERROR', `The wallet could not derive the payment key: ${(e as Error).message}`, false, e);\n }\n outputs = [{ script: new P2PKH().lock(PublicKey.fromString(pk).toHash() as number[]).toHex(), satoshis: sats, description: 'payment' }];\n remittance = { senderIdentityKey: me, derivationPrefix, derivationSuffix, outputIndex: 0 };\n } else if (isPaymail(to)) {\n const r = await (o.resolvePaymail ?? ((p, s) => resolvePaymailP2P(p, s, o.fetch ?? fetch)))(to, sats);\n outputs = r.outputs;\n submit = r.submit;\n } else {\n try {\n outputs = [{ script: new P2PKH().lock(to).toHex(), satoshis: sats, description: 'payment' }];\n } catch {\n throw new PaymentError('BAD_REQUEST', `Not a paymail, address or identity key: ${to}`);\n }\n }\n if (req.memo && req.memoOnChain) outputs = [...outputs, { script: opReturn(req.memo), satoshis: 0, description: 'memo' }];\n\n const r = await runAction(source, req.memo || `Pay ${clip(to, 30)}`, outputs, req.labels);\n if (!r.txid) throw new PaymentError('WALLET_ERROR', 'The wallet did not return a txid', true);\n const tx = r.tx ? Array.from(r.tx) : undefined;\n if (submit && tx) {\n // Tell the paymail host about the tx. Best effort: the payment itself is already made.\n await submit(Transaction.fromAtomicBEEF(tx).toHex()).catch(() => {});\n }\n return { txid: r.txid, tx, sats, outputs, remittance };\n}\n\n/** pay() labelled as a tip. */\nexport function tip(source: PaySource, req: PayRequest, o: PayOptions = {}): Promise<PayResult> {\n return pay(source, { memo: 'Tip', ...req, labels: [...(req.labels ?? []), 'tip'] }, o);\n}\n\nexport interface TokenQuote {\n /** Outputs to fund, as your server priced them (e.g. payment to the seller + fee). */\n outputs: PayOutput[];\n description?: string;\n /** Called with the result after the wallet signs; e.g. POST txid + tx to your server for verifyPayment. */\n onPaid?: (r: PayResult) => Promise<void> | void;\n}\n\nexport interface BuyTokenRequest {\n token: string;\n amount: number | string;\n /** The hook point: return the outputs for this purchase (usually from your server). */\n quote: (req: { token: string; amount: number | string }) => Promise<TokenQuote>;\n labels?: string[];\n}\n\n/** Buy a token: your `quote` hook prices it, the wallet pays once, `onPaid` delivers it. */\nexport async function buyToken(source: PaySource, req: BuyTokenRequest): Promise<PayResult> {\n if (isLegacy(source)) throw new PaymentError('NOT_SUPPORTED', 'This wallet cannot buy tokens. Use a BRC-100 wallet such as bWalletX.');\n const q = await req.quote({ token: req.token, amount: req.amount });\n if (!q?.outputs?.length) throw new PaymentError('BAD_REQUEST', 'The quote returned no outputs');\n const sats = q.outputs.reduce((n, x) => n + x.satoshis, 0);\n const r = await runAction(source, q.description ?? `Buy ${clip(req.token, 30)}`, q.outputs, [...(req.labels ?? []), 'token-buy']);\n if (!r.txid) throw new PaymentError('WALLET_ERROR', 'The wallet did not return a txid', true);\n const res: PayResult = { txid: r.txid, tx: r.tx ? Array.from(r.tx) : undefined, sats, outputs: q.outputs };\n await q.onPaid?.(res);\n return res;\n}\n","/**\n * Every wallet the user could connect with, behind one interface. BRC-100 first: bWalletX, then any\n * other wallet that announces itself (Yours, Metanet, ...), the in-app browser, optional localhost\n * desktop wallets, phone pairing, and app-supplied adapters (e.g. the transitional HandCash one).\n */\nimport { WalletClient, type WalletInterface } from '@bsv/sdk';\nimport { BWALLETX_RDNS, RDNS_EXTENSION } from './discover.js';\nimport { pairBwalletX, restorePairing, type PairingOptions } from './pair.js';\nimport type { PaySource } from './pay.js';\n\nexport type WalletKind = 'brc100' | 'pairing' | 'handcash' | 'custom';\n\nexport interface ConnectedWallet {\n /** The BRC-100 wallet. null for a non-BRC-100 adapter (HandCash today). */\n wallet: WalletInterface | null;\n /** What pay/tip use: the BRC-100 wallet, or the adapter's own payer. */\n payer: PaySource | null;\n /** The identity public key (hex) when the wallet has one. */\n identityKey: string | null;\n handle?: string;\n paymail?: string;\n /** Which option connected. */\n optionId: string;\n kind: WalletKind;\n /** True for adapters kept only until the vendor ships BRC-100. */\n transitional?: boolean;\n}\n\nexport interface WalletOption {\n id: string;\n name: string;\n icon?: string;\n kind: WalletKind;\n rdns?: string;\n /** True for bWalletX (extension, in-app or paired). */\n isBwalletX: boolean;\n connect(): Promise<ConnectedWallet>;\n}\n\nasync function brc100Connected(wallet: WalletInterface, o: Pick<WalletOption, 'id' | 'kind'>): Promise<ConnectedWallet> {\n await wallet.waitForAuthentication({}).catch(() => {});\n const { publicKey } = await wallet.getPublicKey({ identityKey: true });\n return { wallet, payer: wallet, identityKey: publicKey, optionId: o.id, kind: o.kind };\n}\n\n/** Wrap any BRC-100 wallet as a picker option. */\nexport function brc100Option(wallet: WalletInterface, info: { id: string; name: string; icon?: string; rdns?: string; isBwalletX?: boolean }): WalletOption {\n const opt: WalletOption = {\n id: info.id,\n name: info.name,\n icon: info.icon,\n rdns: info.rdns,\n kind: 'brc100',\n isBwalletX: info.isBwalletX ?? false,\n connect: () => brc100Connected(wallet, opt),\n };\n return opt;\n}\n\n/** Phone / web.bwalletx.com pairing as an option (shows a QR through `pairing`). Reuses a stored pairing first. */\nexport function pairingOption(pairing: PairingOptions | (() => PairingOptions)): WalletOption {\n const opt: WalletOption = {\n id: 'bwalletx-pairing',\n name: 'bWalletX on your phone',\n kind: 'pairing',\n isBwalletX: true,\n async connect() {\n const p = typeof pairing === 'function' ? pairing() : pairing;\n const w = (await restorePairing(p)) ?? (await pairBwalletX(p));\n return brc100Connected(w, opt);\n },\n };\n return opt;\n}\n\nexport interface HandCashAdapterOptions {\n /**\n * Your existing HandCash Connect login (redirect/popup + your server route). Resolve with the\n * profile once the user is signed in. This package does not import any HandCash SDK.\n */\n login(): Promise<{ handle: string; paymail?: string; identityKey?: string }>;\n /** Your existing HandCash pay call (usually a server route using the auth token). Optional. */\n pay?: Extract<PaySource, { pay: unknown }>['pay'];\n icon?: string;\n}\n\n/**\n * TRANSITIONAL. Keeps existing HandCash users working behind the same picker until HandCash's\n * BRC-100 support ships; then remove this and HandCash appears as an ordinary BRC-100 wallet.\n */\nexport function handcashAdapter(o: HandCashAdapterOptions): WalletOption {\n const opt: WalletOption = {\n id: 'handcash',\n name: 'HandCash',\n icon: o.icon,\n kind: 'handcash',\n isBwalletX: false,\n async connect() {\n const p = await o.login();\n return {\n wallet: null,\n payer: o.pay ? { pay: o.pay } : null,\n identityKey: p.identityKey ?? null,\n handle: p.handle,\n paymail: p.paymail ?? `${p.handle.replace(/^\\$/, '')}@handcash.io`,\n optionId: opt.id,\n kind: 'handcash',\n transitional: true,\n };\n },\n };\n return opt;\n}\n\nexport interface DiscoverWalletsOptions {\n /** How long to collect BRC-100 announcements, ms. Default 1200. */\n ms?: number;\n /**\n * Also probe desktop wallets on localhost (Metanet / json-api on 3321, Cicada on 3301).\n * Off by default: some browsers prompt for local-network access.\n */\n probeLocal?: boolean;\n /** Add the phone pairing option (needs a way to show the QR, e.g. pairingModal()). */\n pairing?: PairingOptions | (() => PairingOptions);\n /** App-supplied options appended at the end (e.g. handcashAdapter(...)). */\n extra?: WalletOption[];\n}\n\nconst NAMES: Record<string, string> = { [RDNS_EXTENSION]: 'bWalletX', 'space.bwallet.mobile': 'bWalletX' };\n\nasync function probe(substrate: 'json-api' | 'Cicada', ms: number): Promise<WalletInterface | null> {\n try {\n const w = new WalletClient(substrate);\n const ok = await Promise.race([w.isAuthenticated({}).then(() => true), new Promise<boolean>((r) => setTimeout(() => r(false), ms))]);\n return ok ? w : null;\n } catch {\n return null;\n }\n}\n\n/** All wallets we can see, bWalletX first. SSR-safe: resolves [] (plus `extra`) outside a browser. */\nexport async function discoverWallets(o: DiscoverWalletsOptions = {}): Promise<WalletOption[]> {\n const out: WalletOption[] = [];\n const ms = o.ms ?? 1200;\n if (typeof window !== 'undefined') {\n const seen = new Map<string, WalletOption>();\n const onAnnounce = (e: Event) => {\n const d = (e as CustomEvent).detail as { info?: { rdns?: string; name?: string; icon?: string; uuid?: string }; wallet?: WalletInterface } | undefined;\n if (!d?.wallet) return;\n const rdns = d.info?.rdns ?? d.info?.uuid ?? `wallet-${seen.size}`;\n if (seen.has(rdns)) return;\n const isB = (BWALLETX_RDNS as readonly string[]).includes(rdns);\n seen.set(rdns, brc100Option(d.wallet, { id: rdns, rdns, name: NAMES[rdns] ?? d.info?.name ?? rdns, icon: d.info?.icon, isBwalletX: isB }));\n };\n window.addEventListener('brc100:announceWallet', onAnnounce);\n window.dispatchEvent(new Event('brc100:requestWallet'));\n const local = o.probeLocal ? Promise.all([probe('json-api', ms), probe('Cicada', ms)]) : Promise.resolve([null, null]);\n await new Promise((r) => setTimeout(r, ms));\n window.removeEventListener('brc100:announceWallet', onAnnounce);\n out.push(...seen.values());\n const cwi = (window as unknown as { CWI?: WalletInterface }).CWI;\n if (cwi && ![...seen.values()].some((x) => x.rdns === 'space.bwallet.mobile')) {\n out.push(brc100Option(cwi, { id: 'window.CWI', name: 'This app’s wallet', isBwalletX: false }));\n }\n const [json, cicada] = await local;\n if (json) out.push(brc100Option(json, { id: 'localhost:3321', name: 'Desktop wallet (localhost:3321)' }));\n if (cicada) out.push(brc100Option(cicada, { id: 'localhost:3301', name: 'Desktop wallet (localhost:3301)' }));\n }\n if (o.pairing) out.push(pairingOption(o.pairing));\n out.push(...(o.extra ?? []));\n // bWalletX first, transitional last; otherwise keep discovery order.\n const rank = (w: WalletOption) => (w.isBwalletX ? 0 : w.kind === 'handcash' ? 2 : 1);\n return out.map((w, i) => ({ w, i })).sort((a, b) => rank(a.w) - rank(b.w) || a.i - b.i).map((x) => x.w);\n}\n","/**\n * Built-in UI: the pairing QR modal and the wallet picker. Plain DOM, no framework, only created\n * when called in a browser.\n */\nimport qrcode from 'qrcode-generator';\nimport type { PairingOptions } from './pair.js';\nimport type { WalletOption } from './wallets.js';\n\nconst CSS = `\n.bwx-ov{position:fixed;inset:0;z-index:2147483000;background:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;padding:16px;font:15px/1.4 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\n.bwx-box{background:#0b0b0b;color:#f4f1e8;border:1px solid #3a3220;border-radius:16px;width:min(360px,100%);padding:20px;box-shadow:0 20px 60px rgba(0,0,0,.5)}\n.bwx-box h2{margin:0 0 6px;font-size:18px;color:#e8c766}\n.bwx-box p{margin:0 0 14px;color:#bdb6a3;font-size:14px}\n.bwx-qr{background:#fff;border-radius:12px;padding:12px;display:flex;justify-content:center}\n.bwx-qr svg{width:100%;height:auto;max-width:260px}\n.bwx-code{margin:14px 0 0;text-align:center;font-size:28px;letter-spacing:.3em;color:#e8c766;font-variant-numeric:tabular-nums}\n.bwx-row{display:flex;gap:8px;margin-top:14px}\n.bwx-btn{flex:1;border:1px solid #3a3220;background:#15130e;color:#f4f1e8;border-radius:10px;padding:10px 12px;font:inherit;cursor:pointer}\n.bwx-btn:hover{border-color:#e8c766}\n.bwx-list{display:flex;flex-direction:column;gap:8px}\n.bwx-opt{display:flex;align-items:center;gap:10px;text-align:left}\n.bwx-opt img{width:24px;height:24px;border-radius:6px}\n.bwx-tag{margin-left:auto;font-size:11px;color:#8d866f}\n`;\n\nfunction mount(): { root: HTMLDivElement; box: HTMLDivElement; close: () => void } {\n const root = document.createElement('div');\n root.className = 'bwx-ov';\n root.setAttribute('role', 'dialog');\n root.setAttribute('aria-modal', 'true');\n const style = document.createElement('style');\n style.textContent = CSS;\n const box = document.createElement('div');\n box.className = 'bwx-box';\n root.append(style, box);\n document.body.appendChild(root);\n return { root, box, close: () => root.remove() };\n}\n\nfunction el<K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string, text?: string) {\n const e = document.createElement(tag);\n if (cls) e.className = cls;\n if (text != null) e.textContent = text;\n return e;\n}\n\n/** An SVG QR code for `text` (error correction M). */\nexport function qrSvg(text: string): string {\n const q = qrcode(0, 'M');\n q.addData(text);\n q.make();\n return q.createSvgTag({ cellSize: 4, margin: 2, scalable: true });\n}\n\nexport interface PairingModalOptions {\n title?: string;\n /** Called when the user closes the modal (the pairing is then aborted). */\n onCancel?: () => void;\n}\n\n/**\n * PairingOptions that show a QR modal. Pass to signInWithBwalletX({ pairing: pairingModal() }) or\n * connectBwalletX. The modal opens when the link is ready and shows the match code. Call `close()`\n * once pairing settles (useBwalletX does this for you); Cancel aborts the pairing.\n */\nexport function pairingModal(o: PairingModalOptions = {}): PairingOptions & { close(): void } {\n const ac = new AbortController();\n let ui: ReturnType<typeof mount> | null = null;\n let codeEl: HTMLDivElement | null = null;\n const close = () => {\n ui?.close();\n ui = null;\n };\n ac.signal.addEventListener('abort', close);\n return {\n signal: ac.signal,\n close,\n onLink(link) {\n if (typeof document === 'undefined') return;\n close();\n ui = mount();\n const h = el('h2', '', o.title ?? 'Connect bWalletX');\n const p = el('p', '', 'Scan with bWalletX on your phone, or paste the link into web.bwalletx.com.');\n const qr = el('div', 'bwx-qr');\n qr.innerHTML = qrSvg(link);\n codeEl = el('div', 'bwx-code', '');\n codeEl.setAttribute('aria-live', 'polite');\n const row = el('div', 'bwx-row');\n const copy = el('button', 'bwx-btn', 'Copy link');\n copy.onclick = () => void navigator.clipboard?.writeText(link).then(() => (copy.textContent = 'Copied'));\n const cancel = el('button', 'bwx-btn', 'Cancel');\n cancel.onclick = () => {\n o.onCancel?.();\n ac.abort();\n };\n row.append(copy, cancel);\n ui.box.append(h, p, qr, codeEl, row);\n },\n onCode(code) {\n if (codeEl) {\n codeEl.textContent = code;\n const p = ui?.box.querySelector('p');\n if (p) p.textContent = 'Check bWalletX shows the same code, then tap Connect.';\n }\n },\n };\n}\n\n/** Show the picker; resolves with the chosen option, or null if closed. */\nexport function pickWallet(options: WalletOption[], o: { title?: string } = {}): Promise<WalletOption | null> {\n if (typeof document === 'undefined') return Promise.resolve(null);\n return new Promise((resolve) => {\n const ui = mount();\n const done = (w: WalletOption | null) => {\n ui.close();\n resolve(w);\n };\n ui.box.append(el('h2', '', o.title ?? 'Choose a wallet'));\n if (!options.length) ui.box.append(el('p', '', 'No wallet found. Get bWalletX at bwalletx.com.'));\n const list = el('div', 'bwx-list');\n for (const w of options) {\n const b = el('button', 'bwx-btn bwx-opt');\n if (w.icon) {\n const img = el('img');\n img.src = w.icon;\n img.alt = '';\n b.append(img);\n }\n b.append(el('span', '', w.name));\n if (w.kind === 'handcash') b.append(el('span', 'bwx-tag', 'until BRC-100'));\n b.onclick = () => done(w);\n list.append(b);\n }\n const cancel = el('button', 'bwx-btn', 'Cancel');\n cancel.onclick = () => done(null);\n ui.root.onclick = (e) => e.target === ui.root && done(null);\n ui.box.append(list, el('div', 'bwx-row'));\n (ui.box.lastChild as HTMLElement).append(cancel);\n });\n}\n"],"mappings":";;;;;;;;AAKA,SAAS,OAAO,WAAW,aAAa,aAAmC;AAGpE,IAAM,iBAA8B,CAAC,GAAG,cAAc;AAmDtD,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC,YACW,MACT,SAES,YAAY,OACZ,OACT;AACA,UAAM,OAAO;AANJ;AAGA;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EARW;AAAA,EAGA;AAAA,EACA;AAKb;AAQA,IAAM,WAAW,CAAC,MAAmC,OAAQ,EAAkB,QAAQ,cAAc,OAAQ,EAAsB,iBAAiB;AAE7I,IAAM,mBAAmB,CAAC,MAAc,yBAAyB,KAAK,CAAC;AACvE,IAAM,YAAY,CAAC,MAAc,6BAA6B,KAAK,CAAC;AA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