@bwalletx/connect 0.5.3 → 0.5.6
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/CHANGELOG.md +35 -0
- package/README.md +80 -8
- package/dist/bwalletx-connect.global.js +92 -25
- package/dist/bwalletx-connect.global.js.map +1 -1
- package/dist/{wallets-VOKIKBbO.d.ts → choice-DCh-tgpT.d.cts} +113 -5
- package/dist/{wallets-VOKIKBbO.d.cts → choice-DCh-tgpT.d.ts} +113 -5
- package/dist/chunk-34DKBQNN.js +222 -0
- package/dist/chunk-34DKBQNN.js.map +1 -0
- package/dist/{chunk-QRXFL66W.js → chunk-A2WLGS25.js} +6 -4
- package/dist/chunk-A2WLGS25.js.map +1 -0
- package/dist/chunk-IFGOAROM.js +255 -0
- package/dist/chunk-IFGOAROM.js.map +1 -0
- package/dist/chunk-LS6AYEBO.js +1886 -0
- package/dist/chunk-LS6AYEBO.js.map +1 -0
- package/dist/element-D9Zl-x12.d.cts +46 -0
- package/dist/element-D9Zl-x12.d.ts +46 -0
- package/dist/element.cjs +1221 -67
- package/dist/element.cjs.map +1 -1
- package/dist/element.d.cts +23 -28
- package/dist/element.d.ts +23 -28
- package/dist/element.js +29 -2
- package/dist/element.js.map +1 -1
- package/dist/index.cjs +1539 -449
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +185 -12
- package/dist/index.d.ts +185 -12
- package/dist/index.js +106 -12
- package/dist/index.js.map +1 -1
- package/dist/next.cjs +5 -3
- package/dist/next.cjs.map +1 -1
- package/dist/next.js +1 -1
- package/dist/react.cjs +1073 -194
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +75 -8
- package/dist/react.d.ts +75 -8
- package/dist/react.js +121 -40
- package/dist/react.js.map +1 -1
- package/dist/server.cjs +5 -3
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +8 -3
- package/dist/server.d.ts +8 -3
- package/dist/server.js +1 -1
- package/dist/shell-react.cjs.map +1 -1
- package/dist/shell-react.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-IUDD7YTQ.js +0 -839
- package/dist/chunk-IUDD7YTQ.js.map +0 -1
- package/dist/chunk-PI42H3XY.js +0 -459
- package/dist/chunk-PI42H3XY.js.map +0 -1
- package/dist/chunk-QRXFL66W.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/discover.ts","../src/in-order.ts","../src/pair.ts","../src/protocol.ts","../src/signin.ts","../src/access-client.ts","../src/element.ts"],"sourcesContent":["import { WalletClient, XDM, type WalletInterface } from '@bsv/sdk';\n\n/** Ids bWalletX announces in BRC-100 wallet discovery. */\nexport const RDNS_EXTENSION = 'com.bwalletx.extension';\nexport const RDNS_MOBILE = 'space.bwallet.mobile';\nexport const BWALLETX_RDNS = [RDNS_EXTENSION, RDNS_MOBILE] as const;\n\nexport type FoundBy = 'extension' | 'in-app';\n\nexport interface FoundWallet {\n wallet: WalletInterface;\n /** 'extension' for the Chrome extension; 'in-app' inside the bWalletX app's own browser. */\n method: FoundBy;\n rdns: string | null;\n}\n\n/**\n * Like findBwalletX, but also says which bWalletX answered.\n * Order: a BRC-100 announcement with a bWalletX rdns; then `window.CWI` (set by the in-app\n * browser, and by older builds that do not announce); otherwise null.\n */\nexport function discoverBwalletX(ms = 1200): Promise<FoundWallet | null> {\n if (typeof window === 'undefined') return Promise.resolve(null);\n return new Promise((resolve) => {\n let done = false;\n const finish = (r: FoundWallet | null) => {\n if (done) return;\n done = true;\n window.removeEventListener('brc100:announceWallet', onAnnounce);\n resolve(r);\n };\n const onAnnounce = (e: Event) => {\n const d = (e as CustomEvent).detail as { info?: { rdns?: string }; wallet?: WalletInterface } | undefined;\n const rdns = d?.info?.rdns ?? '';\n if (d?.wallet && (BWALLETX_RDNS as readonly string[]).includes(rdns)) {\n finish({ wallet: d.wallet, method: rdns === RDNS_EXTENSION ? 'extension' : 'in-app', rdns });\n }\n };\n window.addEventListener('brc100:announceWallet', onAnnounce);\n window.dispatchEvent(new Event('brc100:requestWallet'));\n setTimeout(() => {\n const cwi = (window as unknown as { CWI?: WalletInterface }).CWI;\n if (cwi) return finish({ wallet: cwi, method: 'in-app', rdns: null });\n // Inside bWalletX's in-wallet frame nothing is injected into the page: the wallet answers BRC-100 XDM\n // (postMessage to the parent) instead. Only tried when framed, and only kept if the parent answers.\n if (!isFramed()) return finish(null);\n void probeXdm(ms).then((w) => finish(w ? { wallet: w, method: 'in-app', rdns: null } : null));\n }, ms);\n });\n}\n\n/**\n * Find bWalletX in this page: the extension on a computer, or the wallet itself when the page is\n * open in bWalletX's in-app browser. Resolves null if nothing answered within `ms`.\n */\nexport async function findBwalletX(ms = 1200): Promise<WalletInterface | null> {\n return (await discoverBwalletX(ms))?.wallet ?? null;\n}\n\nconst isFramed = (): boolean => {\n try {\n return window.parent !== window;\n } catch {\n return true;\n }\n};\n\n/**\n * The only parents that may answer as bWalletX over XDM (security audit 25 Oct 2026). Without this, any page that\n * framed a site using this package became \"the wallet\": it saw every call (payments, sign-in challenges) and could\n * answer with a fake txid. The wallet's own frames: the web wallet, bwallet.space, the iOS/Android app shells and\n * the Chrome extension. Payments must still be checked on your server (verifyPayment), never trusted from the page.\n */\nexport const BWALLETX_PARENT_ORIGINS: readonly string[] = [\n 'https://web.bwalletx.com',\n 'https://desktop.bwalletx.com',\n 'https://bwalletx.com',\n 'https://www.bwallet.space',\n 'https://bwallet.space',\n 'capacitor://localhost', // iOS app shell\n 'https://localhost', // Android app shell\n 'tauri://localhost', // bWalletX Desktop (macOS)\n 'https://tauri.localhost', // bWalletX Desktop (Windows)\n 'chrome-extension://bombmmcjghjdlbmcclnhjodgcelnehgl', // bWalletX for Chrome (fixed id)\n];\n\n/** The parent frame's origin, as the browser reports it (ancestorOrigins, else the referrer), or null. */\nexport const parentOrigin = (): string | null => {\n try {\n const anc = (window.location as Location & { ancestorOrigins?: DOMStringList }).ancestorOrigins;\n if (anc && anc.length > 0) return anc[0] ?? null;\n if (!document.referrer) return null;\n // Not URL.origin: it is \"null\" for non-special schemes (capacitor:, chrome-extension:) in some engines.\n const u = new URL(document.referrer);\n return `${u.protocol}//${u.host}`;\n } catch {\n return null;\n }\n};\n\n/**\n * The parent frame's wallet over BRC-100 XDM, or null when the parent is not bWalletX (BWALLETX_PARENT_ORIGINS) or\n * does not answer within `ms`. Messages go to that exact origin and only its answers are taken.\n */\nexport async function probeXdm(ms = 1200, allowed: readonly string[] = BWALLETX_PARENT_ORIGINS): Promise<WalletInterface | null> {\n const origin = parentOrigin();\n if (!origin || !allowed.includes(origin)) return null;\n try {\n const w = new WalletClient(new XDM(origin) as unknown as WalletInterface);\n const ok = await Promise.race([\n w.isAuthenticated({}).then(\n () => true,\n () => false,\n ),\n new Promise<boolean>((r) => setTimeout(() => r(false), ms)),\n ]);\n return ok ? w : null;\n } catch {\n return null;\n }\n}\n","/**\n * Wrap an async frame handler so frames are handled one at a time, in arrival order.\n *\n * WebSocket `onmessage` does not wait for an async handler. The phone sends its plain `hello`\n * and then, as soon as the user taps Connect, a sealed `ready`. If the handler for `hello` is\n * still deriving the session key when `ready` arrives, a naive handler sees no key yet and drops\n * `ready`, so pairing never finishes. Chaining every frame onto one promise fixes that.\n */\nexport function inOrder<T>(handle: (frame: T) => Promise<void> | void, onError?: (e: unknown) => void) {\n let queue: Promise<void> = Promise.resolve();\n return (frame: T): Promise<void> => {\n queue = queue.then(() => handle(frame)).catch((e) => onError?.(e));\n return queue;\n };\n}\n","import { PrivateKey, type WalletInterface } from '@bsv/sdk';\nimport { inOrder } from './in-order.js';\nimport {\n DEFAULT_RELAY,\n PAIR_VERSION,\n QR_LIFETIME_S,\n Sealer,\n deriveSession,\n isSealed,\n newChannel,\n pairUrl,\n relaySocketUrl,\n type HelloFrame,\n type PairMessage,\n} from './protocol.js';\n\n/** localStorage-shaped storage. Methods may be sync or async. */\nexport interface PairStorage {\n getItem(key: string): string | null | Promise<string | null>;\n setItem(key: string, value: string): void | Promise<void>;\n removeItem(key: string): void | Promise<void>;\n}\n\n/** The minimum of the browser WebSocket API this package uses (the `ws` package also fits). */\nexport interface SocketLike {\n readonly readyState: number;\n onopen: ((ev: unknown) => void) | null;\n onmessage: ((ev: { data: unknown }) => void) | null;\n onerror: ((ev: unknown) => void) | null;\n onclose: ((ev: unknown) => void) | null;\n send(data: string): void;\n close(): void;\n}\nexport type SocketFactory = (url: string) => SocketLike;\n\nexport interface PairConnectionOptions {\n /** Where the pairing is kept so it survives a reload. Default: localStorage, else memory only. */\n storage?: PairStorage | null;\n /** Storage key. Default 'bwalletx.connect.pairing.v1'. */\n storageKey?: string;\n /** Opens a socket. Default: the global WebSocket. Pass one to run in Node or to test. */\n socket?: SocketFactory;\n /** Per-call timeout in ms. Default 120000. */\n callTimeoutMs?: number;\n}\n\nexport interface PairingOptions extends PairConnectionOptions {\n /** Show this link as a QR code, and as text to copy (web.bwalletx.com takes it pasted). */\n onLink: (link: string) => void;\n /** Show this 4-digit code. The wallet shows the same one; the user checks they match. */\n onCode: (code: string) => void;\n signal?: AbortSignal;\n /** Relay host. Default relay.bwallet.space. */\n relay?: string;\n /** This page's origin, as the relay will see it. Default location.origin. */\n origin?: string;\n}\n\n/** A BRC-100 wallet whose every call goes, end-to-end encrypted, to the paired phone or web wallet. */\nexport type PairedWallet = WalletInterface & {\n /** Close the relay connection. The pairing stays stored; the next call reconnects. */\n close(): void;\n /** Tell the wallet to unpair, close, and delete the stored pairing. */\n forget(): Promise<void>;\n};\n\ninterface StoredPairing {\n v: 1;\n c: string; // channel\n r: string; // relay host\n s: string; // our pairing private key (hex). Random; not a wallet key.\n k: string; // the wallet's pairing public key\n sent: number;\n lastSeen: number;\n pairedAt: number;\n}\n\nconst DEFAULT_KEY = 'bwalletx.connect.pairing.v1';\nconst OPEN = 1;\n\nfunction memoryStorage(): PairStorage {\n const m = new Map<string, string>();\n return { getItem: (k) => m.get(k) ?? null, setItem: (k, v) => void m.set(k, v), removeItem: (k) => void m.delete(k) };\n}\n\nfunction defaultStorage(): PairStorage {\n try {\n if (typeof localStorage !== 'undefined') return localStorage;\n } catch {\n /* blocked storage */\n }\n return memoryStorage();\n}\n\nfunction defaultSocket(): SocketFactory {\n return (url) => {\n if (typeof WebSocket === 'undefined') throw new Error('No WebSocket here. Pass options.socket.');\n return new WebSocket(url) as unknown as SocketLike;\n };\n}\n\nfunction parseStored(raw: string | null): StoredPairing | null {\n if (!raw) return null;\n try {\n const p = JSON.parse(raw) as Partial<StoredPairing>;\n const n = (x: unknown) => Number.isInteger(x) && (x as number) >= 0;\n if (p.v !== 1) return null;\n if (typeof p.c !== 'string' || !/^[A-Za-z0-9_-]{22}$/.test(p.c)) return null;\n if (typeof p.r !== 'string' || !/^[a-z0-9.-]+(:\\d+)?$/i.test(p.r)) return null;\n if (typeof p.s !== 'string' || !/^[0-9a-f]{64}$/i.test(p.s)) return null;\n if (typeof p.k !== 'string' || !/^0[23][0-9a-f]{64}$/i.test(p.k)) return null;\n if (!n(p.sent) || !n(p.lastSeen) || !n(p.pairedAt)) return null;\n return p as StoredPairing;\n } catch {\n return null;\n }\n}\n\nclass Link {\n private ws: SocketLike | null = null;\n private opening: Promise<void> | null = null;\n private waiting = new Map<string, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }>();\n private forgotten = false;\n\n constructor(\n private p: StoredPairing,\n private sealer: Sealer,\n private storage: PairStorage,\n private key: string,\n private socket: SocketFactory,\n private timeoutMs: number,\n ) {}\n\n /** Take over a socket that is already open (the one pairing used). */\n adopt(ws: SocketLike) {\n this.ws = ws;\n this.wire(ws);\n }\n\n private wire(ws: SocketLike) {\n ws.onmessage = inOrder((ev: { data: unknown }) => this.onFrame(String(ev.data)));\n ws.onerror = null;\n ws.onclose = () => {\n if (this.ws === ws) this.ws = null;\n this.failAll(new Error('The connection to bWalletX closed'));\n };\n }\n\n private persist() {\n if (this.forgotten) return;\n this.p = { ...this.p, ...this.sealer.counters };\n void Promise.resolve(this.storage.setItem(this.key, JSON.stringify(this.p))).catch(() => {});\n }\n\n private failAll(e: Error) {\n for (const w of this.waiting.values()) {\n clearTimeout(w.timer);\n w.reject(e);\n }\n this.waiting.clear();\n }\n\n private async ensure() {\n if (this.forgotten) throw new Error('This pairing was removed. Pair again.');\n if (this.ws && this.ws.readyState === OPEN) return;\n this.opening ??= this.reopen().finally(() => (this.opening = null));\n await this.opening;\n }\n\n private reopen() {\n // A fresh expiry lets the relay recreate the channel if it was dropped; the wallet rejoins on its own.\n const ws = this.socket(relaySocketUrl(this.p.r, this.p.c, 'site', Math.floor(Date.now() / 1000) + QR_LIFETIME_S - 10));\n return new Promise<void>((resolve, reject) => {\n ws.onopen = () => {\n this.ws = ws;\n this.wire(ws);\n resolve();\n };\n ws.onerror = () => reject(new Error('Could not reach the bWalletX pairing service'));\n ws.onclose = () => reject(new Error('Could not reach the bWalletX pairing service'));\n });\n }\n\n private async onFrame(raw: string) {\n let f: unknown;\n try {\n f = JSON.parse(raw);\n } catch {\n return;\n }\n const t = (f as { t?: string; error?: string }).t;\n if (t === 'relay' && (f as { error?: string }).error) {\n return this.failAll(new Error(`bWalletX pairing service: ${(f as { error: string }).error}`));\n }\n if (!isSealed(f)) return;\n const msg = await this.sealer.open(f);\n if (!msg) return;\n this.persist();\n if (msg.t === 'res') {\n const w = this.waiting.get(msg.id);\n if (!w) return;\n clearTimeout(w.timer);\n this.waiting.delete(msg.id);\n if (msg.error) w.reject(Object.assign(new Error(msg.error.message), { code: msg.error.code }));\n else w.resolve(msg.result);\n } else if (msg.t === 'close') {\n this.drop();\n this.failAll(new Error('bWalletX disconnected this site. Pair again.'));\n }\n }\n\n async call(action: string, params: unknown): Promise<unknown> {\n await this.ensure();\n const ws = this.ws!;\n const id = `${action}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n const result = new Promise<unknown>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (this.waiting.delete(id)) reject(new Error('No answer from bWalletX. Open it, unlocked, and approve.'));\n }, this.timeoutMs);\n this.waiting.set(id, { resolve, reject, timer });\n });\n ws.send(JSON.stringify(await this.sealer.seal({ t: 'req', id, action, params } satisfies PairMessage)));\n this.persist();\n return result;\n }\n\n close() {\n const ws = this.ws;\n this.ws = null;\n ws?.close();\n }\n\n private drop() {\n this.forgotten = true;\n void Promise.resolve(this.storage.removeItem(this.key)).catch(() => {});\n this.close();\n }\n\n async forget() {\n if (this.forgotten) return;\n try {\n if (this.ws && this.ws.readyState === OPEN) {\n this.ws.send(JSON.stringify(await this.sealer.seal({ t: 'close', reason: 'site unpaired' })));\n }\n } catch {\n /* best effort */\n }\n this.drop();\n }\n\n wallet(): PairedWallet {\n return new Proxy({} as PairedWallet, {\n get: (_t, method) => {\n if (method === 'close') return () => this.close();\n if (method === 'forget') return () => this.forget();\n if (typeof method !== 'string' || method === 'then' || method === 'toJSON') return undefined;\n return (params: unknown) => this.call(method, params ?? {});\n },\n });\n }\n}\n\n/**\n * Pair with bWalletX on a phone (scan the QR) or web.bwalletx.com (paste the link).\n * Resolves with a wallet once the user taps Connect. The pairing is stored (see `storage`) so\n * `restorePairing()` can reconnect after a reload without a new QR.\n */\nexport function pairBwalletX(opts: PairingOptions): Promise<PairedWallet> {\n const storage = opts.storage === undefined ? defaultStorage() : (opts.storage ?? memoryStorage());\n const key = opts.storageKey ?? DEFAULT_KEY;\n const socket = opts.socket ?? defaultSocket();\n const relay = opts.relay ?? DEFAULT_RELAY;\n const origin = opts.origin ?? (typeof location !== 'undefined' ? location.origin : '');\n if (!origin) return Promise.reject(new Error('pairBwalletX needs options.origin outside a browser'));\n\n const siteKey = PrivateKey.fromRandom(); // a throwaway pairing key, not a wallet key\n const channel = newChannel();\n const expiry = Math.floor(Date.now() / 1000) + QR_LIFETIME_S;\n\n return new Promise<PairedWallet>((resolve, reject) => {\n if (opts.signal?.aborted) return reject(new Error('cancelled'));\n let ws: SocketLike;\n try {\n ws = socket(relaySocketUrl(relay, channel, 'site', expiry));\n } catch (e) {\n return reject(e);\n }\n let sealer: Sealer | null = null;\n let walletKey = '';\n let settled = false;\n const fail = (e: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n ws.close();\n reject(e);\n };\n const timer = setTimeout(() => fail(new Error('The pairing code expired. Show a new one.')), QR_LIFETIME_S * 1000);\n opts.signal?.addEventListener('abort', () => fail(new Error('cancelled')));\n ws.onerror = () => fail(new Error('Could not reach the bWalletX pairing service'));\n ws.onclose = () => fail(new Error('The connection to bWalletX closed before pairing finished'));\n ws.onmessage = inOrder(async (ev: { data: unknown }) => {\n if (settled) return;\n let f: unknown;\n try {\n f = JSON.parse(String(ev.data));\n } catch {\n return;\n }\n if ((f as HelloFrame).t === 'hello' && !sealer) {\n walletKey = (f as HelloFrame).k;\n const s = await deriveSession(siteKey, walletKey, channel);\n sealer = new Sealer(s.key, 'site');\n opts.onCode(s.code);\n return;\n }\n if (!sealer || !isSealed(f)) return;\n const msg = await sealer.open(f);\n if (!msg) return;\n if (msg.t === 'ready') {\n settled = true;\n clearTimeout(timer);\n const p: StoredPairing = { v: 1, c: channel, r: relay, s: siteKey.toHex(), k: walletKey, ...sealer.counters, pairedAt: Date.now() };\n await Promise.resolve(storage.setItem(key, JSON.stringify(p))).catch(() => {});\n const link = new Link(p, sealer, storage, key, socket, opts.callTimeoutMs ?? 120_000);\n link.adopt(ws);\n resolve(link.wallet());\n } else if (msg.t === 'close') {\n fail(new Error('Pairing was declined in bWalletX'));\n }\n });\n opts.onLink(pairUrl({ v: PAIR_VERSION, r: relay, c: channel, k: siteKey.toPublicKey().toString(), o: origin, e: expiry }));\n });\n}\n\n/**\n * The wallet from a pairing stored by an earlier `pairBwalletX`, or null if there is none.\n * It connects on the first call. The wallet must still have this site paired.\n */\nexport async function restorePairing(opts: PairConnectionOptions = {}): Promise<PairedWallet | null> {\n const storage = opts.storage === undefined ? defaultStorage() : (opts.storage ?? memoryStorage());\n const key = opts.storageKey ?? DEFAULT_KEY;\n const p = parseStored(await Promise.resolve(storage.getItem(key)).catch(() => null));\n if (!p) return null;\n const { key: aes } = await deriveSession(PrivateKey.fromHex(p.s), p.k, p.c);\n const sealer = new Sealer(aes, 'site');\n sealer.restore({ sent: p.sent, lastSeen: p.lastSeen });\n return new Link(p, sealer, storage, key, opts.socket ?? defaultSocket(), opts.callTimeoutMs ?? 120_000).wallet();\n}\n\n/** Delete the stored pairing without telling the wallet. */\nexport async function clearPairing(opts: Pick<PairConnectionOptions, 'storage' | 'storageKey'> = {}) {\n const storage = opts.storage === undefined ? defaultStorage() : (opts.storage ?? memoryStorage());\n await Promise.resolve(storage.removeItem(opts.storageKey ?? DEFAULT_KEY)).catch(() => {});\n}\n","/**\n * Phone pairing protocol (tokenblaster.lol docs/wallet-connect.md §4), shared by the site side and\n * bWallet. Kept dependency-light (@bsv/sdk + WebCrypto) so the same file can be copied into sites\n * until it ships as @b0ase/wallet.\n *\n * QR: https://www.bwallet.space/pair?v=1&r=<relay host>&c=<channel>&k=<site pubkey>&o=<origin>&e=<expiry>\n * key: ECDH(secp256k1) → HKDF-SHA256(salt = channel bytes, info = \"bwallet-pair-v1\") → AES-256-GCM\n * frame: { s: seq, n: nonce b64, d: ciphertext b64 }, AAD = \"<sender role>|<s>\", s strictly increasing\n * code: first 2 bytes of SHA-256(key bits) → 4 digits, shown on both screens\n */\nimport { PrivateKey, PublicKey } from '@bsv/sdk';\n\nexport const PAIR_VERSION = '1';\nexport const PAIR_INFO = 'bwallet-pair-v1';\n// www: the bare domain redirects there, and app-link checks (Apple's AASA) don't follow redirects.\nexport const PAIR_HOST = 'www.bwallet.space';\nconst PAIR_HOSTS = new Set([PAIR_HOST, 'bwallet.space']);\nexport const DEFAULT_RELAY = 'relay.bwallet.space';\nexport const QR_LIFETIME_S = 120;\n\nexport type Role = 'site' | 'wallet';\nexport type WalletInfo = { name: string; icon?: string; rdns: string };\n\nexport type PairLink = { v: string; r: string; c: string; k: string; o: string; e: number };\n\n/** Plaintext messages inside encrypted frames. */\nexport type PairMessage =\n | { t: 'req'; id: string; action: string; params: unknown }\n | { t: 'res'; id: string; result?: unknown; error?: { code: string; message: string } }\n | { t: 'ready' }\n | { t: 'ping' }\n | { t: 'close'; reason: string };\n\n/** Unencrypted frames: from the relay, and the phone's hello (its key isn't shared yet). */\nexport type RelayFrame = { t: 'relay'; verifiedOrigin?: string; peer?: 'joined' | 'left'; role?: Role; error?: string };\nexport type HelloFrame = { t: 'hello'; k: string; info: WalletInfo };\nexport type SealedFrame = { s: number; n: string; d: string };\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder();\n\n// Chunked: String.fromCharCode(...bytes) overflows the call stack on large frames (signed transactions).\nconst binary = (bytes: Uint8Array) => {\n let s = '';\n for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n return s;\n};\nexport const b64url = (bytes: Uint8Array) =>\n btoa(binary(bytes)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\nexport const fromB64url = (s: string) => {\n const t = s.replace(/-/g, '+').replace(/_/g, '/');\n const bin = atob(t + '='.repeat((4 - (t.length % 4)) % 4));\n return Uint8Array.from(bin, (ch) => ch.charCodeAt(0));\n};\nconst b64 = (bytes: Uint8Array) => btoa(binary(bytes));\nconst fromB64 = (s: string) => Uint8Array.from(atob(s), (ch) => ch.charCodeAt(0));\n\nexport const newChannel = () => b64url(crypto.getRandomValues(new Uint8Array(16)));\n\nexport function pairUrl(link: PairLink): string {\n const q = new URLSearchParams({ v: link.v, r: link.r, c: link.c, k: link.k, o: link.o, e: String(link.e) });\n return `https://${PAIR_HOST}/pair?${q}`;\n}\n\n/** Parse a scanned QR (https link or bwallet:// fallback). Throws on anything else. */\nexport function parsePairUrl(text: string, nowS = Math.floor(Date.now() / 1000)): PairLink {\n const u = new URL(text.trim());\n const ok =\n (u.protocol === 'https:' && PAIR_HOSTS.has(u.host) && u.pathname === '/pair') ||\n (u.protocol === 'bwallet:' && /pair/.test(u.href));\n if (!ok) throw new Error('Not a bWallet pairing code');\n const g = (k: string) => u.searchParams.get(k) ?? '';\n const link: PairLink = { v: g('v'), r: g('r'), c: g('c'), k: g('k'), o: g('o'), e: Number(g('e')) };\n if (link.v !== PAIR_VERSION) throw new Error('This pairing code needs a newer bWallet');\n if (!/^[A-Za-z0-9_-]{22}$/.test(link.c)) throw new Error('Bad pairing code');\n if (!/^0[23][0-9a-f]{64}$/i.test(link.k)) throw new Error('Bad pairing code');\n if (!/^[a-z0-9.-]+(:\\d+)?$/i.test(link.r)) throw new Error('Bad pairing code');\n const o = new URL(link.o);\n if (o.origin !== link.o) throw new Error('Bad pairing code');\n if (!Number.isFinite(link.e) || link.e < nowS) throw new Error('This code has expired. Ask the site for a new one.');\n return link;\n}\n\nexport const relaySocketUrl = (relay: string, channel: string, role: Role, expiry?: number) => {\n const local = /^(localhost|127\\.0\\.0\\.1)(:\\d+)?$/.test(relay);\n const q = new URLSearchParams({ role });\n if (expiry) q.set('e', String(expiry));\n return `${local ? 'ws' : 'wss'}://${relay}/v1/c/${channel}?${q}`;\n};\n\n/** Shared AES key + 4-digit comparison code from my private key and their public key. */\nexport async function deriveSession(mine: PrivateKey, theirs: string, channel: string) {\n const point = mine.deriveSharedSecret(PublicKey.fromString(theirs));\n const ikm = new Uint8Array(point.encode(true) as number[]);\n const base = await crypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);\n const bits = new Uint8Array(\n await crypto.subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt: fromB64url(channel), info: enc.encode(PAIR_INFO) },\n base,\n 256,\n ),\n );\n const key = await crypto.subtle.importKey('raw', bits, 'AES-GCM', false, ['encrypt', 'decrypt']);\n const h = new Uint8Array(await crypto.subtle.digest('SHA-256', bits));\n const code = String(((h[0] << 8) | h[1]) % 10000).padStart(4, '0');\n return { key, code };\n}\n\n/** One direction-aware encrypted pipe. `me` is the sender role used in the AAD. */\nexport class Sealer {\n private sent = 0;\n private lastSeen = 0;\n constructor(\n private key: CryptoKey,\n private me: Role,\n ) {}\n\n async seal(msg: PairMessage): Promise<SealedFrame> {\n const s = ++this.sent;\n const n = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: n, additionalData: enc.encode(`${this.me}|${s}`) },\n this.key,\n enc.encode(JSON.stringify(msg)),\n ),\n );\n return { s, n: b64(n), d: b64(ct) };\n }\n\n /** Decrypts a frame from the other side; null for replays, reflections or tampering. */\n async open(f: SealedFrame): Promise<PairMessage | null> {\n if (!Number.isInteger(f.s) || f.s <= this.lastSeen) return null;\n const from: Role = this.me === 'site' ? 'wallet' : 'site';\n try {\n const pt = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: fromB64(f.n), additionalData: enc.encode(`${from}|${f.s}`) },\n this.key,\n fromB64(f.d),\n );\n this.lastSeen = f.s;\n return JSON.parse(dec.decode(pt)) as PairMessage;\n } catch {\n return null;\n }\n }\n\n /** For resuming a session after a reload: continue counters where they were. */\n get counters() {\n return { sent: this.sent, lastSeen: this.lastSeen };\n }\n restore(c: { sent: number; lastSeen: number }) {\n this.sent = c.sent;\n this.lastSeen = c.lastSeen;\n }\n}\n\nexport const isSealed = (x: unknown): x is SealedFrame =>\n !!x && typeof x === 'object' && 'd' in x && 'n' in x && 's' in x;\n","import type { WalletInterface, WalletProtocol } from '@bsv/sdk';\nimport { discoverBwalletX } from './discover.js';\nimport { pairBwalletX, restorePairing, type PairingOptions } from './pair.js';\n\n/** Security level 2, a protocol name used for nothing else. */\nexport const LOGIN_PROTOCOL: WalletProtocol = [2, 'bwallet sign in'];\n\n/** What your server's challenge route returns (createChallenge from '@bwalletx/connect/server'). */\nexport interface Challenge {\n nonce: string;\n message: string;\n keyID: string;\n protocolID?: WalletProtocol;\n}\n\nexport type SignInMethod = 'extension' | 'in-app' | 'pairing' | 'wallet';\n\nexport interface SignInOptions {\n /** Ask your server for a challenge for this identity key. */\n challenge: (identityKey: string) => Promise<Challenge>;\n /** Use this wallet instead of looking for one. `method` is then 'wallet'. */\n wallet?: WalletInterface;\n /** How to show the QR and code if pairing is needed. Without it, pairing is not tried. */\n pairing?: PairingOptions;\n /** Reuse a pairing stored by an earlier sign-in before showing a new QR. Default true. */\n reusePairing?: boolean;\n /** How long to wait for the extension or in-app browser to answer, in ms. Default 1200. */\n discoverMs?: number;\n}\n\nexport interface SignInResult {\n identityKey: string;\n /** DER signature as number[], ready to post to verifySignIn. */\n signature: number[];\n nonce: string;\n method: SignInMethod;\n /** The wallet that signed. Keep it to make more calls. */\n wallet: WalletInterface;\n}\n\n/** Find a wallet: extension or in-app browser first, then a stored pairing, then a new pairing. */\nexport async function connectBwalletX(\n opts: Pick<SignInOptions, 'wallet' | 'pairing' | 'reusePairing' | 'discoverMs'> = {},\n): Promise<{ wallet: WalletInterface; method: SignInMethod }> {\n if (opts.wallet) return { wallet: opts.wallet, method: 'wallet' };\n const found = await discoverBwalletX(opts.discoverMs);\n if (found) return { wallet: found.wallet, method: found.method };\n if (opts.reusePairing !== false) {\n const restored = await restorePairing(opts.pairing ?? {});\n if (restored) return { wallet: restored, method: 'pairing' };\n }\n if (!opts.pairing) {\n throw Object.assign(new Error('bWalletX was not found in this browser'), { code: 'NOT_FOUND' });\n }\n return { wallet: await pairBwalletX(opts.pairing), method: 'pairing' };\n}\n\n/**\n * Sign the server's challenge with the user's bWalletX identity key. Post the result's\n * identityKey, nonce and signature to your verify route.\n */\nexport async function signInWithBwalletX(opts: SignInOptions): Promise<SignInResult> {\n const { wallet, method } = await connectBwalletX(opts);\n if (method !== 'pairing') await wallet.waitForAuthentication({}).catch(() => {});\n const { publicKey: identityKey } = await atStage('identity', () => wallet.getPublicKey({ identityKey: true }));\n const c = await atStage('challenge', () => opts.challenge(identityKey));\n const { signature } = await atStage('signature', () =>\n wallet.createSignature({\n protocolID: c.protocolID ?? LOGIN_PROTOCOL,\n keyID: c.keyID,\n counterparty: 'anyone',\n data: Array.from(new TextEncoder().encode(c.message)),\n }),\n );\n return { identityKey, signature: Array.from(signature), nonce: c.nonce, method, wallet };\n}\n\n/** Where a sign-in failed: the wallet's identity prompt, the site's challenge endpoint, or the wallet's signature. */\nexport type SignInStage = 'identity' | 'challenge' | 'signature' | 'verify';\n\n/** Tags a failure with its stage (err.stage), keeping the original message, so a site can say what actually failed. */\nexport async function atStage<T>(stage: SignInStage, run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n if (!(err as { stage?: string }).stage) Object.assign(err, { stage });\n throw err;\n }\n}\n","/**\n * Browser side of the access protocol: ask the wallet to sign the site's challenge and prove the\n * keys holding the required token, using standard BRC-100 calls only (so any BRC-100 wallet works).\n */\nimport { Hash, PublicKey, Utils, type WalletInterface, type WalletProtocol } from '@bsv/sdk';\nimport {\n ACCESS_PROTOCOL,\n AccessError,\n MAX_HOLDING_PROOFS,\n challengeBytes,\n parseAccessChallenge,\n type AccessErrorBody,\n type AccessResponse,\n type HoldingProof,\n} from './access.js';\nimport { connectBwalletX, type SignInOptions } from './signin.js';\n\n/** The challenge route's answer (createAccessChallenge). */\nexport interface AccessChallengeLike {\n challenge: string;\n}\n\nexport interface RequestAccessOptions {\n /** Ask your server for a challenge. Gets the wallet's identity key. */\n challenge: (identityKey: string) => Promise<AccessChallengeLike>;\n /** Post the signed response to your server. Throw AccessError (or return an error body) to refuse. */\n verify?: (response: AccessResponse) => Promise<unknown>;\n wallet?: WalletInterface;\n pairing?: SignInOptions['pairing'];\n discoverMs?: number;\n /** Basket holding BSV-21 outputs. Default 'bsv21' (bWalletX, 1Sat wallets). */\n tokenBasket?: string;\n}\n\nexport interface RequestAccessResult {\n response: AccessResponse;\n /** Whatever `verify` returned. */\n verified?: unknown;\n wallet: WalletInterface;\n}\n\nconst ONESAT: WalletProtocol = [0, 'onesat'];\nconst LEGACY_ONESAT: WalletProtocol = [0, 'p 1sat'];\n\n/** Map a wallet / fetch failure to a protocol error. */\nexport function toAccessError(e: unknown): AccessError {\n if (e instanceof AccessError) return e;\n const err = e as { code?: string; message?: string; status?: number } | null;\n const msg = String(err?.message ?? e ?? '');\n if (err?.code === 'NOT_FOUND') return new AccessError('not_installed', msg);\n if (/reject|denied|declin|cancel|user/i.test(msg) || err?.code === 'ERR_USER_REJECTED' || err?.status === 4001) {\n return new AccessError('user_rejected', msg);\n }\n return new AccessError('bad_request', msg || 'access failed');\n}\n\n/** Read an AccessErrorBody from a server answer and throw it as AccessError. */\nexport function throwIfAccessError(body: unknown): void {\n const b = body as Partial<AccessErrorBody> | null;\n if (b && typeof b.error === 'string') throw new AccessError(b.error as AccessError['code'], b.message, { have: b.have, need: b.need });\n}\n\nfunction hash160FromP2pkh(script: string): string | null {\n const m = /^76a914([0-9a-f]{40})88ac$/i.exec(script.slice(-50));\n return m ? m[1].toLowerCase() : null;\n}\n\n/**\n * Sign the challenge with every key that locks an output of `tokenId` in the wallet's token basket.\n * Outputs whose derivation can't be reproduced are skipped (the server counts only what is proven).\n */\nexport async function proveHoldings(wallet: WalletInterface, challenge: string, tokenId: string, basket = 'bsv21'): Promise<HoldingProof[]> {\n const bare = tokenId.replace(/^bsv21:/, '');\n const list = await wallet.listOutputs({ basket, include: 'locking scripts', includeCustomInstructions: true, limit: 10000 });\n const byKey = new Map<string, HoldingProof>();\n const data = challengeBytes(challenge);\n for (const out of list.outputs) {\n if (byKey.size >= MAX_HOLDING_PROOFS) break;\n let ci: { id?: string; keyID?: string; protocolID?: WalletProtocol; counterparty?: string } = {};\n try {\n ci = JSON.parse(out.customInstructions ?? '{}');\n } catch {\n continue;\n }\n if (ci.id !== bare || !ci.keyID) continue;\n const want = out.lockingScript ? hash160FromP2pkh(out.lockingScript) : null;\n const counterparty = ci.counterparty ?? 'self';\n for (const protocolID of ci.protocolID ? [ci.protocolID] : [ONESAT, LEGACY_ONESAT]) {\n const { publicKey } = await wallet.getPublicKey({ protocolID, keyID: ci.keyID, counterparty });\n const h = Utils.toHex(Hash.hash160(PublicKey.fromString(publicKey).encode(true) as number[]));\n if (want && h !== want) continue;\n const existing = byKey.get(publicKey);\n if (existing) {\n existing.outpoints!.push(out.outpoint.replace('.', '_'));\n break;\n }\n const { signature } = await wallet.createSignature({ protocolID, keyID: ci.keyID, counterparty, data });\n byKey.set(publicKey, { pubkey: publicKey, signature: Array.from(signature), outpoints: [out.outpoint.replace('.', '_')] });\n break;\n }\n }\n return [...byKey.values()];\n}\n\n/**\n * Run the whole flow: find the wallet, get a challenge, sign it, prove holdings, post to verify.\n * Throws AccessError with a protocol code on every failure.\n */\nexport async function requestAccess(o: RequestAccessOptions): Promise<RequestAccessResult> {\n let wallet: WalletInterface;\n try {\n ({ wallet } = await connectBwalletX({ wallet: o.wallet, pairing: o.pairing, discoverMs: o.discoverMs }));\n } catch (e) {\n throw (e as { code?: string })?.code === 'NOT_FOUND' ? new AccessError('not_installed') : toAccessError(e);\n }\n try {\n const { publicKey: identityKey } = await wallet.getPublicKey({ identityKey: true });\n const { challenge } = await o.challenge(identityKey);\n const c = parseAccessChallenge(challenge);\n if (c.sub && c.sub !== identityKey.toLowerCase()) throw new AccessError('wrong_account');\n if (Date.now() / 1000 >= c.exp) throw new AccessError('expired');\n const { signature } = await wallet.createSignature({\n protocolID: ACCESS_PROTOCOL,\n keyID: c.nonce,\n counterparty: 'anyone',\n data: challengeBytes(challenge),\n });\n const response: AccessResponse = { v: 1, challenge, identityKey, signature: Array.from(signature) };\n if (c.require.token) response.holdings = await proveHoldings(wallet, challenge, c.require.token.id, o.tokenBasket);\n let verified: unknown;\n if (o.verify) {\n verified = await o.verify(response);\n throwIfAccessError(verified);\n }\n return { response, verified, wallet };\n } catch (e) {\n throw toAccessError(e);\n }\n}\n","/**\n * <bwalletx-signin>: the standard \"Sign in with bWalletX\" button as a framework-free web component.\n *\n * Design reference: the gold button in bit-sign's sign-in card (src/components/BwalletSignIn.tsx):\n * amber-300 → amber-500 vertical gradient, 12px radius, 16px/20px padding, 16px bold black label,\n * 11px subtitle at 60% black, a black 28px circle holding the gold \"b\", amber shadow.\n *\n * Attributes (all optional):\n * size lg (default) | md | sm | icon\n * theme gold (default) | dark | light\n * label signin (default) | continue | connect\n * brand bWalletX (default) | bWallet (store edition text)\n * subtitle on | off | <custom text>. Default on for lg/md, off for sm/icon and for brand=\"bWallet\"\n * full-width stretch to the container\n * loading show the spinner and set aria-busy\n * disabled disable the button\n * challenge-url / verify-url run the sign-in flow on click (POST JSON, as in the README)\n * require-token / min / min-bps with challenge-url: run the $403 access flow instead; emits\n * bwalletx-access-granted or bwalletx-access-denied { code, have, need }\n * get-url where \"Get bWalletX\" points. Default https://bwalletx.com/get\n * web-url the web wallet. Default https://web.bwalletx.com\n * discover-ms how long to wait for the wallet to answer. Default 1200\n * href plain link mode: navigate here on click\n * authorize-url (+ client-id, redirect-uri, scope) OAuth mode, for auth.bwalletx.com once it exists\n *\n * Events (bubble, composed):\n * bwalletx-signin on every click, before anything else. Cancelable: preventDefault() stops the\n * built-in behaviour so you can run your own flow.\n * bwalletx-signed-in detail { identityKey, method, nonce, signature, response }\n * bwalletx-not-found no bWalletX answered; the \"Get bWalletX\" row is shown\n * bwalletx-error detail { error }\n */\nimport { discoverBwalletX } from './discover.js';\nimport { signInWithBwalletX, type Challenge } from './signin.js';\nimport { requestAccess, type AccessChallengeLike } from './access-client.js';\nimport { AccessError } from './access.js';\n\nexport const SIGNIN_TAG = 'bwalletx-signin';\nexport const GET_URL = 'https://bwalletx.com/get';\nexport const WEB_WALLET_URL = 'https://web.bwalletx.com';\n\nexport type SigninSize = 'lg' | 'md' | 'sm' | 'icon';\nexport type SigninTheme = 'gold' | 'dark' | 'light';\nexport type SigninLabel = 'signin' | 'continue' | 'connect';\nexport type SigninBrand = 'bWalletX' | 'bWallet';\n\nconst VERBS: Record<SigninLabel, string> = { signin: 'Sign in with', continue: 'Continue with', connect: 'Connect' };\n\n/** The visible label for a label/brand pair, e.g. \"Sign in with bWalletX\". */\nexport function signinText(label: SigninLabel = 'signin', brand: SigninBrand = 'bWalletX'): string {\n return `${VERBS[label] ?? VERBS.signin} ${brand}`;\n}\n\nlet uid = 0;\n/** The gold \"b\" (bwalletx-site/logo.svg). Ids are unique per copy so several marks can share a page. */\nexport function markSvg(px = 20): string {\n const n = ++uid;\n return `<svg viewBox=\"23 8 74 100\" width=\"${Math.round(px * 0.74)}\" height=\"${px}\" aria-hidden=\"true\" focusable=\"false\"><defs><linearGradient id=\"bwxg${n}\" gradientUnits=\"userSpaceOnUse\" x1=\"0\" y1=\"12\" x2=\"0\" y2=\"105\"><stop offset=\"0\" stop-color=\"#FFE58A\"/><stop offset=\".55\" stop-color=\"#FFD24D\"/><stop offset=\"1\" stop-color=\"#C98F00\"/></linearGradient><mask id=\"bwxh${n}\"><rect width=\"140\" height=\"140\" fill=\"#fff\"/><circle cx=\"60\" cy=\"72\" r=\"15\" fill=\"#000\"/></mask></defs><g fill=\"url(#bwxg${n})\" mask=\"url(#bwxh${n})\"><polygon points=\"45,12 45,76 27,76 27,30\"/><circle cx=\"60\" cy=\"72\" r=\"33\"/></g></svg>`;\n}\n\nexport const SIGNIN_CSS = `\n:host{display:inline-block;vertical-align:middle;font-family:Inter,ui-sans-serif,system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif}\n:host([full-width]){display:block;width:100%}\n:host([hidden]){display:none}\nbutton{all:unset;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:12px;width:100%;cursor:pointer;\n padding:16px 20px;border-radius:12px;font-size:16px;font-weight:700;line-height:1.2;text-align:left;\n background:linear-gradient(180deg,#fcd34d,#f59e0b);color:#000;\n box-shadow:0 10px 15px -3px rgba(245,158,11,.2),0 4px 6px -4px rgba(245,158,11,.2);\n transition:background .15s,transform .1s,box-shadow .15s,border-color .15s;-webkit-tap-highlight-color:transparent}\nbutton:hover{background:linear-gradient(180deg,#fde68a,#fbbf24)}\nbutton:active{transform:translateY(1px);background:linear-gradient(180deg,#fbbf24,#d97706)}\nbutton:focus-visible{outline:2px solid #b45309;outline-offset:3px}\nbutton:disabled{opacity:.6;cursor:not-allowed;transform:none}\nbutton[aria-busy=true]{cursor:wait}\n.mark{display:inline-flex;align-items:center;justify-content:center;flex:none;width:28px;height:28px;border-radius:50%;background:#000}\n.txt{display:flex;flex-direction:column;align-items:flex-start;min-width:0}\n.txt b{font-weight:700;white-space:nowrap}\n.txt small{font-size:11px;font-weight:500;color:rgba(0,0,0,.65);white-space:nowrap}\n.spin{width:16px;height:16px;border-radius:50%;border:2px solid rgba(255,210,77,.35);border-top-color:#ffd24d;animation:r .8s linear infinite}\n@keyframes r{to{transform:rotate(360deg)}}\n@media (prefers-reduced-motion:reduce){button{transition:none}button:active{transform:none}.spin{animation:none;border-color:#ffd24d;border-right-color:transparent}}\n/* sizes */\n:host([size=md]) button{padding:10px 16px;border-radius:10px;font-size:15px;gap:10px}\n:host([size=md]) .mark{width:24px;height:24px}\n:host([size=md]) .txt small{font-size:10.5px}\n:host([size=sm]) button{padding:6px 12px 6px 6px;border-radius:8px;font-size:13px;gap:8px;min-height:36px}\n:host([size=sm]) .mark{width:22px;height:22px}\n:host([size=icon]) button{width:48px;height:48px;padding:0;border-radius:50%;gap:0}\n:host([size=icon]) .mark{width:34px;height:34px}\n/* themes */\n:host([theme=dark]) button{background:#0a0a0a;color:#fafafa;border:1px solid #3f3f46;box-shadow:none}\n:host([theme=dark]) button:hover{background:#18181b;border-color:rgba(251,191,36,.6)}\n:host([theme=dark]) button:active{background:#000}\n:host([theme=dark]) button:focus-visible{outline-color:#fcd34d}\n:host([theme=dark]) .mark{box-shadow:inset 0 0 0 1px #3f3f46}\n:host([theme=dark]) .txt small{color:rgba(255,255,255,.65)}\n:host([theme=light]) button{background:#fff;color:#09090b;border:1px solid #d4d4d8;box-shadow:0 1px 2px rgba(0,0,0,.06)}\n:host([theme=light]) button:hover{background:#fafafa;border-color:#f59e0b}\n:host([theme=light]) button:active{background:#f4f4f5}\n:host([theme=light]) .txt small{color:#52525b}\n/* not found */\n.nf{margin-top:8px;font-size:12px;line-height:1.4;color:#71717a;text-align:center}\n.nf a{color:inherit;font-weight:600;text-decoration:underline;text-underline-offset:2px}\n.nf a:focus-visible{outline:2px solid #b45309;outline-offset:2px;border-radius:2px}\n:host([theme=dark]) .nf,:host-context(.dark) .nf{color:#a1a1aa}\n.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}\n`;\n\n/** Optional OAuth parameters for authorize-url mode. auth.bwalletx.com is planned, not live. */\nexport interface AuthorizeParams { authorizeUrl: string; clientId?: string | null; redirectUri?: string | null; scope?: string | null }\n\nfunction b64url(bytes: Uint8Array): string {\n let s = '';\n for (const b of bytes) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/**\n * Build an OAuth 2.1 authorization-code + S256 PKCE redirect URL, and keep the verifier, state and\n * nonce in sessionStorage under \"bwalletx:oauth\" for your callback page. Matches the plan in\n * bit-sign docs/SIGN-IN-WITH-BWALLETX.md. The provider is not live yet.\n */\nexport async function buildAuthorizeUrl(p: AuthorizeParams): Promise<string> {\n const rnd = (n: number) => b64url(crypto.getRandomValues(new Uint8Array(n)));\n const verifier = rnd(32);\n const state = rnd(16);\n const nonce = rnd(16);\n const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)));\n const u = new URL(p.authorizeUrl, typeof location !== 'undefined' ? location.href : undefined);\n const set = (k: string, v: string | null | undefined) => { if (v) u.searchParams.set(k, v); };\n set('response_type', 'code');\n set('client_id', p.clientId);\n set('redirect_uri', p.redirectUri);\n set('scope', p.scope || 'openid profile');\n set('state', state);\n set('nonce', nonce);\n set('code_challenge', b64url(digest));\n set('code_challenge_method', 'S256');\n try { sessionStorage.setItem('bwalletx:oauth', JSON.stringify({ verifier, state, nonce })); } catch { /* storage blocked */ }\n return u.toString();\n}\n\nasync function postJson<T>(url: string, body: unknown): Promise<T> {\n const res = await fetch(url, { method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });\n const data = await res.json().catch(() => ({}));\n if (!res.ok) throw new Error((data as { error?: string }).error ?? `HTTP ${res.status}`);\n return data as T;\n}\n\n/** POST that returns the body even on 4xx, so access error codes reach requestAccess. */\nasync function postAccess(url: string, body: unknown): Promise<unknown> {\n const res = await fetch(url, { method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });\n return res.json().catch(() => ({ error: 'bad_request', message: `HTTP ${res.status}` }));\n}\n\nconst OBSERVED = ['size', 'theme', 'label', 'brand', 'subtitle', 'loading', 'disabled', 'full-width', 'aria-label', 'get-url', 'web-url'];\n\n/** The element class. Created lazily so importing this module on a server is harmless. */\nfunction createClass(): CustomElementConstructor {\n return class BwalletxSigninElement extends HTMLElement {\n static get observedAttributes() { return OBSERVED; }\n #root: ShadowRoot;\n #notFound = false;\n #busy = false;\n\n constructor() {\n super();\n this.#root = this.attachShadow({ mode: 'open' });\n }\n\n connectedCallback() { this.#render(); }\n attributeChangedCallback() { if (this.isConnected) this.#render(); }\n\n /** The inner <button>, for focus() and tests. */\n get button(): HTMLButtonElement | null { return this.#root.querySelector('button'); }\n get notFound() { return this.#notFound; }\n\n focus(opts?: FocusOptions) { this.button?.focus(opts); }\n\n #attr(name: string) { return this.getAttribute(name); }\n\n #render() {\n const size = (this.#attr('size') ?? 'lg') as SigninSize;\n const brand: SigninBrand = this.#attr('brand') === 'bWallet' ? 'bWallet' : 'bWalletX';\n const text = signinText((this.#attr('label') ?? 'signin') as SigninLabel, brand);\n const subAttr = this.#attr('subtitle');\n const subDefault = brand === 'bWalletX' && (size === 'lg' || size === 'md') ? 'also works with bWallet' : null;\n const subtitle = subAttr === null || subAttr === '' || subAttr === 'on' ? (subAttr === 'on' ? 'also works with bWallet' : subDefault)\n : subAttr === 'off' ? null : subAttr;\n const loading = this.hasAttribute('loading') || this.#busy;\n const disabled = this.hasAttribute('disabled');\n const markPx = size === 'icon' ? 24 : size === 'sm' ? 15 : size === 'md' ? 17 : 20;\n const aria = this.#attr('aria-label') ?? (subtitle && size !== 'icon' ? `${text}, ${subtitle}` : text);\n const getUrl = this.#attr('get-url') ?? GET_URL;\n const webUrl = this.#attr('web-url') ?? WEB_WALLET_URL;\n\n const esc = (s: string) => s.replace(/[&<>\"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '\"': '"' })[c]!);\n const label = size === 'icon' ? '' : `<span class=\"txt\" part=\"text\"><b part=\"label\">${esc(text)}</b>${subtitle ? `<small part=\"subtitle\">${esc(subtitle)}</small>` : ''}</span>`;\n const mark = loading ? '<span class=\"spin\" aria-hidden=\"true\"></span>' : markSvg(markPx);\n const nf = this.#notFound\n ? `<p class=\"nf\" part=\"not-found\" role=\"status\">bWalletX wasn't found in this browser. <a href=\"${esc(getUrl)}\" target=\"_blank\" rel=\"noopener\">Get ${brand}</a> or <a href=\"${esc(webUrl)}\" target=\"_blank\" rel=\"noopener\">use the web wallet</a>.</p>`\n : '';\n this.#root.innerHTML = `<style>${SIGNIN_CSS}</style><button type=\"button\" part=\"button\" aria-label=\"${esc(aria)}\" title=\"${esc(subtitle ? `${text} (${subtitle})` : text)}\"${disabled ? ' disabled' : ''}${loading ? ' aria-busy=\"true\"' : ''}><span class=\"mark\" part=\"mark\">${mark}</span>${label}</button>${loading ? '<span class=\"sr\" role=\"status\">Connecting to bWalletX…</span>' : ''}${nf}`;\n this.button!.addEventListener('click', () => void this.#click());\n }\n\n #emit(type: string, detail?: unknown, cancelable = false) {\n return this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true, cancelable }));\n }\n\n #setBusy(on: boolean) { this.#busy = on; this.#render(); }\n\n async #click() {\n if (this.hasAttribute('disabled') || this.hasAttribute('loading') || this.#busy) return;\n if (!this.#emit('bwalletx-signin', { element: this }, true)) return;\n\n const href = this.#attr('href');\n const authorizeUrl = this.#attr('authorize-url');\n if (authorizeUrl) {\n location.assign(await buildAuthorizeUrl({ authorizeUrl, clientId: this.#attr('client-id'), redirectUri: this.#attr('redirect-uri'), scope: this.#attr('scope') }));\n return;\n }\n if (href) { location.assign(href); return; }\n\n const challengeUrl = this.#attr('challenge-url');\n if (!challengeUrl) return; // event-only mode: the page runs its own flow\n\n this.#notFound = false;\n this.#setBusy(true);\n try {\n const ms = Number(this.#attr('discover-ms')) || 1200;\n const found = await discoverBwalletX(ms);\n if (!found) {\n this.#notFound = true;\n this.#emit('bwalletx-not-found');\n if (this.#attr('require-token')) this.#emit('bwalletx-access-denied', { code: 'not_installed', message: 'No wallet found' });\n return;\n }\n const requireToken = this.#attr('require-token');\n if (requireToken) {\n // $403 gate. The server's own config is authoritative; these attributes are passed along as a hint.\n const verifyUrl = this.#attr('verify-url');\n const min = this.#attr('min');\n const minBps = this.#attr('min-bps');\n const hint = { token: { id: requireToken, ...(minBps ? { minBps: Number(minBps) } : { min: min ?? '1' }) } };\n try {\n const a = await requestAccess({\n wallet: found.wallet,\n challenge: (identityKey) => postJson<AccessChallengeLike>(challengeUrl, { identityKey, require: hint }),\n verify: verifyUrl ? (response) => postAccess(verifyUrl, response) : undefined,\n });\n this.#emit('bwalletx-access-granted', { identityKey: a.response.identityKey, response: a.verified });\n } catch (e) {\n const err = e instanceof AccessError ? e : new AccessError('bad_request', String(e));\n this.#emit('bwalletx-access-denied', { code: err.code, message: err.message, have: err.have, need: err.need });\n }\n return;\n }\n const r = await signInWithBwalletX({ wallet: found.wallet, challenge: (identityKey) => postJson<Challenge>(challengeUrl, { identityKey }) });\n const verifyUrl = this.#attr('verify-url');\n const response = verifyUrl ? await postJson(verifyUrl, { identityKey: r.identityKey, nonce: r.nonce, signature: r.signature }) : null;\n this.#emit('bwalletx-signed-in', { identityKey: r.identityKey, method: found.method, nonce: r.nonce, signature: r.signature, response });\n } catch (error) {\n this.#emit('bwalletx-error', { error });\n } finally {\n this.#setBusy(false);\n }\n }\n };\n}\n\n/** Register <bwalletx-signin> (once). Safe to call on a server: it does nothing there. */\nexport function defineBwalletxSignin(tag = SIGNIN_TAG): CustomElementConstructor | undefined {\n if (typeof window === 'undefined' || typeof customElements === 'undefined') return undefined;\n const existing = customElements.get(tag);\n if (existing) return existing;\n const C = createClass();\n customElements.define(tag, C);\n return C;\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,cAAc,WAAiC;AAGjD,IAAM,iBAAiB;AACvB,IAAM,cAAc;AACpB,IAAM,gBAAgB,CAAC,gBAAgB,WAAW;AAgBlD,SAAS,iBAAiB,KAAK,MAAmC;AACvE,MAAI,OAAO,WAAW,YAAa,QAAO,QAAQ,QAAQ,IAAI;AAC9D,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,QAAI,OAAO;AACX,UAAM,SAAS,CAAC,MAA0B;AACxC,UAAI,KAAM;AACV,aAAO;AACP,aAAO,oBAAoB,yBAAyB,UAAU;AAC9D,cAAQ,CAAC;AAAA,IACX;AACA,UAAM,aAAa,CAAC,MAAa;AAC/B,YAAM,IAAK,EAAkB;AAC7B,YAAM,OAAO,GAAG,MAAM,QAAQ;AAC9B,UAAI,GAAG,UAAW,cAAoC,SAAS,IAAI,GAAG;AACpE,eAAO,EAAE,QAAQ,EAAE,QAAQ,QAAQ,SAAS,iBAAiB,cAAc,UAAU,KAAK,CAAC;AAAA,MAC7F;AAAA,IACF;AACA,WAAO,iBAAiB,yBAAyB,UAAU;AAC3D,WAAO,cAAc,IAAI,MAAM,sBAAsB,CAAC;AACtD,eAAW,MAAM;AACf,YAAM,MAAO,OAAgD;AAC7D,UAAI,IAAK,QAAO,OAAO,EAAE,QAAQ,KAAK,QAAQ,UAAU,MAAM,KAAK,CAAC;AAGpE,UAAI,CAAC,SAAS,EAAG,QAAO,OAAO,IAAI;AACnC,WAAK,SAAS,EAAE,EAAE,KAAK,CAAC,MAAM,OAAO,IAAI,EAAE,QAAQ,GAAG,QAAQ,UAAU,MAAM,KAAK,IAAI,IAAI,CAAC;AAAA,IAC9F,GAAG,EAAE;AAAA,EACP,CAAC;AACH;AAMA,eAAsB,aAAa,KAAK,MAAuC;AAC7E,UAAQ,MAAM,iBAAiB,E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IAAI,IAAI,YAAY,eAAe,OAAO,CAAC,CAAC;AACnF,iBAAK,MAAM,0BAA0B,EAAE,MAAM,IAAI,MAAM,SAAS,IAAI,SAAS,MAAM,IAAI,MAAM,MAAM,IAAI,KAAK,CAAC;AAAA,UAC/G;AACA;AAAA,QACF;AACA,cAAM,IAAI,MAAM,mBAAmB,EAAE,QAAQ,MAAM,QAAQ,WAAW,CAAC,gBAAgB,SAAoB,cAAc,EAAE,YAAY,CAAC,EAAE,CAAC;AAC3I,cAAM,YAAY,KAAK,MAAM,YAAY;AACzC,cAAM,WAAW,YAAY,MAAM,SAAS,WAAW,EAAE,aAAa,EAAE,aAAa,OAAO,EAAE,OAAO,WAAW,EAAE,UAAU,CAAC,IAAI;AACjI,aAAK,MAAM,sBAAsB,EAAE,aAAa,EAAE,aAAa,QAAQ,MAAM,QAAQ,OAAO,EAAE,OAAO,WAAW,EAAE,WAAW,SAAS,CAAC;AAAA,MACzI,SAAS,OAAO;AACd,aAAK,MAAM,kBAAkB,EAAE,MAAM,CAAC;AAAA,MACxC,UAAE;AACA,aAAK,SAAS,KAAK;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;AAGO,SAAS,qBAAqB,MAAM,YAAkD;AAC3F,MAAI,OAAO,WAAW,eAAe,OAAO,mBAAmB,YAAa,QAAO;AACnF,QAAM,WAAW,eAAe,IAAI,GAAG;AACvC,MAAI,SAAU,QAAO;AACrB,QAAM,IAAI,YAAY;AACtB,iBAAe,OAAO,KAAK,CAAC;AAC5B,SAAO;AACT;","names":["PrivateKey","PrivateKey","PublicKey","PublicKey","b64url","verifyUrl","response"]}
|
package/dist/chunk-PI42H3XY.js
DELETED
|
@@ -1,459 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
BWALLETX_RDNS,
|
|
3
|
-
RDNS_EXTENSION,
|
|
4
|
-
WEB_WALLET_URL,
|
|
5
|
-
pairBwalletX,
|
|
6
|
-
restorePairing
|
|
7
|
-
} from "./chunk-IUDD7YTQ.js";
|
|
8
|
-
|
|
9
|
-
// src/pay.ts
|
|
10
|
-
import { P2PKH, PublicKey, Transaction, Utils } from "@bsv/sdk";
|
|
11
|
-
var BRC29_PROTOCOL = [2, "3241645161d8"];
|
|
12
|
-
var PaymentError = class extends Error {
|
|
13
|
-
constructor(code, message, maybeSent = false, cause) {
|
|
14
|
-
super(message);
|
|
15
|
-
this.code = code;
|
|
16
|
-
this.maybeSent = maybeSent;
|
|
17
|
-
this.cause = cause;
|
|
18
|
-
this.name = "PaymentError";
|
|
19
|
-
}
|
|
20
|
-
code;
|
|
21
|
-
maybeSent;
|
|
22
|
-
cause;
|
|
23
|
-
};
|
|
24
|
-
var isLegacy = (s) => typeof s.pay === "function" && typeof s.createAction !== "function";
|
|
25
|
-
var isIdentityKeyHex = (s) => /^0[23][0-9a-fA-F]{64}$/.test(s);
|
|
26
|
-
var isPaymail = (s) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s);
|
|
27
|
-
function randomB64(n) {
|
|
28
|
-
const b = new Uint8Array(n);
|
|
29
|
-
globalThis.crypto.getRandomValues(b);
|
|
30
|
-
return Utils.toBase64(Array.from(b));
|
|
31
|
-
}
|
|
32
|
-
function opReturn(text) {
|
|
33
|
-
const d = Utils.toArray(text, "utf8");
|
|
34
|
-
const len = d.length;
|
|
35
|
-
const push = len < 76 ? [len] : len <= 255 ? [76, len] : [77, len & 255, len >> 8];
|
|
36
|
-
return Utils.toHex([0, 106, ...push, ...d]);
|
|
37
|
-
}
|
|
38
|
-
var clip = (s, n) => s.length > n ? s.slice(0, n - 1) + "\u2026" : s;
|
|
39
|
-
var describe = (s) => clip(s.length < 5 ? `${s} payment`.trim() : s, 50);
|
|
40
|
-
async function usdRate(o) {
|
|
41
|
-
if (typeof o.usdPerBsv === "number") return o.usdPerBsv;
|
|
42
|
-
try {
|
|
43
|
-
if (typeof o.usdPerBsv === "function") return await o.usdPerBsv();
|
|
44
|
-
const r = await (o.fetch ?? fetch)("https://api.whatsonchain.com/v1/bsv/main/exchangerate");
|
|
45
|
-
const j = await r.json();
|
|
46
|
-
if (!r.ok || !(Number(j.rate) > 0)) throw new Error(`status ${r.status}`);
|
|
47
|
-
return Number(j.rate);
|
|
48
|
-
} catch (e) {
|
|
49
|
-
throw new PaymentError("RATE_FAILED", `Could not get the BSV/USD rate: ${e.message}`, false, e);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
async function amountInSats(req, o = {}) {
|
|
53
|
-
if (req.sats != null) {
|
|
54
|
-
if (!Number.isSafeInteger(req.sats) || req.sats <= 0) throw new PaymentError("BAD_REQUEST", "sats must be a positive integer");
|
|
55
|
-
return req.sats;
|
|
56
|
-
}
|
|
57
|
-
if (req.usd != null) {
|
|
58
|
-
if (!(req.usd > 0)) throw new PaymentError("BAD_REQUEST", "usd must be positive");
|
|
59
|
-
return Math.max(1, Math.ceil(req.usd / await usdRate(o) * 1e8));
|
|
60
|
-
}
|
|
61
|
-
throw new PaymentError("BAD_REQUEST", "Give sats or usd");
|
|
62
|
-
}
|
|
63
|
-
async function resolvePaymailP2P(paymail, sats, f = fetch) {
|
|
64
|
-
const [alias, domain] = paymail.split("@");
|
|
65
|
-
const fail = (m, e) => new PaymentError("RESOLVE_FAILED", `Could not resolve ${paymail}: ${m}`, false, e);
|
|
66
|
-
let caps;
|
|
67
|
-
try {
|
|
68
|
-
const r = await f(`https://${domain}/.well-known/bsvalias`);
|
|
69
|
-
caps = (await r.json()).capabilities;
|
|
70
|
-
} catch (e) {
|
|
71
|
-
throw fail("no bsvalias document (or CORS blocked it; resolve on your server and pass resolvePaymail)", e);
|
|
72
|
-
}
|
|
73
|
-
const fill = (u) => u.replace("{alias}", encodeURIComponent(alias)).replace("{domain.tld}", domain);
|
|
74
|
-
const dest = caps?.["2a40af698840"];
|
|
75
|
-
if (!dest) throw fail("it does not offer P2P payment destinations");
|
|
76
|
-
let body;
|
|
77
|
-
try {
|
|
78
|
-
const r = await f(fill(dest), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ satoshis: sats }) });
|
|
79
|
-
if (!r.ok) throw new Error(`status ${r.status}`);
|
|
80
|
-
body = await r.json();
|
|
81
|
-
} catch (e) {
|
|
82
|
-
throw fail(e.message, e);
|
|
83
|
-
}
|
|
84
|
-
if (!body.outputs?.length) throw fail("no outputs returned");
|
|
85
|
-
const receive = caps["5f1323cddf31"];
|
|
86
|
-
return {
|
|
87
|
-
outputs: body.outputs.map((o) => ({ script: o.script, satoshis: o.satoshis })),
|
|
88
|
-
reference: body.reference,
|
|
89
|
-
submit: receive ? async (hex) => {
|
|
90
|
-
await f(fill(receive), {
|
|
91
|
-
method: "POST",
|
|
92
|
-
headers: { "content-type": "application/json" },
|
|
93
|
-
body: JSON.stringify({ hex, reference: body.reference, metadata: {} })
|
|
94
|
-
});
|
|
95
|
-
} : void 0
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
async function runAction(wallet, description, outputs, labels) {
|
|
99
|
-
try {
|
|
100
|
-
return await wallet.createAction({
|
|
101
|
-
description: describe(description),
|
|
102
|
-
outputs: outputs.map((o) => ({ lockingScript: o.script, satoshis: o.satoshis, outputDescription: describe(o.description ?? "payment") })),
|
|
103
|
-
labels: labels?.length ? labels : void 0,
|
|
104
|
-
options: { randomizeOutputs: false }
|
|
105
|
-
});
|
|
106
|
-
} catch (e) {
|
|
107
|
-
const msg = e?.message ?? String(e);
|
|
108
|
-
const rejected = /denied|reject|cancel|abort|user/i.test(msg) || e?.code === 4001;
|
|
109
|
-
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);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
async function pay(source, req, o = {}) {
|
|
113
|
-
const to = (req.to ?? "").trim();
|
|
114
|
-
if (!to) throw new PaymentError("BAD_REQUEST", "Give a recipient (to)");
|
|
115
|
-
if (req.memo && req.memo.length > 1e3) throw new PaymentError("BAD_REQUEST", "memo is too long");
|
|
116
|
-
const sats = await amountInSats(req, o);
|
|
117
|
-
if (isLegacy(source)) return source.pay({ ...req, to, sats });
|
|
118
|
-
let outputs;
|
|
119
|
-
let remittance;
|
|
120
|
-
let submit;
|
|
121
|
-
if (isIdentityKeyHex(to)) {
|
|
122
|
-
const derivationPrefix = randomB64(8);
|
|
123
|
-
const derivationSuffix = randomB64(8);
|
|
124
|
-
let pk;
|
|
125
|
-
let me;
|
|
126
|
-
try {
|
|
127
|
-
({ publicKey: pk } = await source.getPublicKey({ protocolID: BRC29_PROTOCOL, keyID: `${derivationPrefix} ${derivationSuffix}`, counterparty: to.toLowerCase() }));
|
|
128
|
-
({ publicKey: me } = await source.getPublicKey({ identityKey: true }));
|
|
129
|
-
} catch (e) {
|
|
130
|
-
throw new PaymentError("WALLET_ERROR", `The wallet could not derive the payment key: ${e.message}`, false, e);
|
|
131
|
-
}
|
|
132
|
-
outputs = [{ script: new P2PKH().lock(PublicKey.fromString(pk).toHash()).toHex(), satoshis: sats, description: "payment" }];
|
|
133
|
-
remittance = { senderIdentityKey: me, derivationPrefix, derivationSuffix, outputIndex: 0 };
|
|
134
|
-
} else if (isPaymail(to)) {
|
|
135
|
-
const r2 = await (o.resolvePaymail ?? ((p, s) => resolvePaymailP2P(p, s, o.fetch ?? fetch)))(to, sats);
|
|
136
|
-
outputs = r2.outputs;
|
|
137
|
-
submit = r2.submit;
|
|
138
|
-
} else {
|
|
139
|
-
try {
|
|
140
|
-
outputs = [{ script: new P2PKH().lock(to).toHex(), satoshis: sats, description: "payment" }];
|
|
141
|
-
} catch {
|
|
142
|
-
throw new PaymentError("BAD_REQUEST", `Not a paymail, address or identity key: ${to}`);
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
if (req.memo && req.memoOnChain) outputs = [...outputs, { script: opReturn(req.memo), satoshis: 0, description: "memo" }];
|
|
146
|
-
const r = await runAction(source, req.memo || `Pay ${clip(to, 30)}`, outputs, req.labels);
|
|
147
|
-
if (!r.txid) throw new PaymentError("WALLET_ERROR", "The wallet did not return a txid", true);
|
|
148
|
-
const tx = r.tx ? Array.from(r.tx) : void 0;
|
|
149
|
-
if (submit && tx) {
|
|
150
|
-
await submit(Transaction.fromAtomicBEEF(tx).toHex()).catch(() => {
|
|
151
|
-
});
|
|
152
|
-
}
|
|
153
|
-
return { txid: r.txid, tx, sats, outputs, remittance };
|
|
154
|
-
}
|
|
155
|
-
function tip(source, req, o = {}) {
|
|
156
|
-
return pay(source, { memo: "Tip", ...req, labels: [...req.labels ?? [], "tip"] }, o);
|
|
157
|
-
}
|
|
158
|
-
async function buyToken(source, req) {
|
|
159
|
-
if (isLegacy(source)) throw new PaymentError("NOT_SUPPORTED", "This wallet cannot buy tokens. Use a BRC-100 wallet such as bWalletX.");
|
|
160
|
-
const q = await req.quote({ token: req.token, amount: req.amount });
|
|
161
|
-
if (!q?.outputs?.length) throw new PaymentError("BAD_REQUEST", "The quote returned no outputs");
|
|
162
|
-
const sats = q.outputs.reduce((n, x) => n + x.satoshis, 0);
|
|
163
|
-
const r = await runAction(source, q.description ?? `Buy ${clip(req.token, 30)}`, q.outputs, [...req.labels ?? [], "token-buy"]);
|
|
164
|
-
if (!r.txid) throw new PaymentError("WALLET_ERROR", "The wallet did not return a txid", true);
|
|
165
|
-
const res = { txid: r.txid, tx: r.tx ? Array.from(r.tx) : void 0, sats, outputs: q.outputs };
|
|
166
|
-
await q.onPaid?.(res);
|
|
167
|
-
return res;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
// src/wallets.ts
|
|
171
|
-
import { WalletClient } from "@bsv/sdk";
|
|
172
|
-
async function brc100Connected(wallet, o) {
|
|
173
|
-
await wallet.waitForAuthentication({}).catch(() => {
|
|
174
|
-
});
|
|
175
|
-
const { publicKey } = await wallet.getPublicKey({ identityKey: true });
|
|
176
|
-
return { wallet, payer: wallet, identityKey: publicKey, optionId: o.id, kind: o.kind };
|
|
177
|
-
}
|
|
178
|
-
function brc100Option(wallet, info) {
|
|
179
|
-
const opt = {
|
|
180
|
-
id: info.id,
|
|
181
|
-
name: info.name,
|
|
182
|
-
icon: info.icon,
|
|
183
|
-
rdns: info.rdns,
|
|
184
|
-
kind: "brc100",
|
|
185
|
-
isBwalletX: info.isBwalletX ?? false,
|
|
186
|
-
connect: () => brc100Connected(wallet, opt)
|
|
187
|
-
};
|
|
188
|
-
return opt;
|
|
189
|
-
}
|
|
190
|
-
function pairingOption(pairing) {
|
|
191
|
-
const opt = {
|
|
192
|
-
id: "bwalletx-pairing",
|
|
193
|
-
name: "bWalletX on your phone",
|
|
194
|
-
kind: "pairing",
|
|
195
|
-
isBwalletX: true,
|
|
196
|
-
async connect() {
|
|
197
|
-
const p = typeof pairing === "function" ? pairing() : pairing;
|
|
198
|
-
const w = await restorePairing(p) ?? await pairBwalletX(p);
|
|
199
|
-
return brc100Connected(w, opt);
|
|
200
|
-
}
|
|
201
|
-
};
|
|
202
|
-
return opt;
|
|
203
|
-
}
|
|
204
|
-
function handcashAdapter(o) {
|
|
205
|
-
const opt = {
|
|
206
|
-
id: "handcash",
|
|
207
|
-
name: "HandCash",
|
|
208
|
-
icon: o.icon,
|
|
209
|
-
kind: "handcash",
|
|
210
|
-
isBwalletX: false,
|
|
211
|
-
async connect() {
|
|
212
|
-
const p = await o.login();
|
|
213
|
-
return {
|
|
214
|
-
wallet: null,
|
|
215
|
-
payer: o.pay ? { pay: o.pay } : null,
|
|
216
|
-
identityKey: p.identityKey ?? null,
|
|
217
|
-
handle: p.handle,
|
|
218
|
-
paymail: p.paymail ?? `${p.handle.replace(/^\$/, "")}@handcash.io`,
|
|
219
|
-
optionId: opt.id,
|
|
220
|
-
kind: "handcash",
|
|
221
|
-
transitional: true
|
|
222
|
-
};
|
|
223
|
-
}
|
|
224
|
-
};
|
|
225
|
-
return opt;
|
|
226
|
-
}
|
|
227
|
-
var NAMES = { [RDNS_EXTENSION]: "bWalletX", "space.bwallet.mobile": "bWalletX" };
|
|
228
|
-
async function probe(substrate, ms) {
|
|
229
|
-
try {
|
|
230
|
-
const w = new WalletClient(substrate);
|
|
231
|
-
const ok = await Promise.race([w.isAuthenticated({}).then(() => true), new Promise((r) => setTimeout(() => r(false), ms))]);
|
|
232
|
-
return ok ? w : null;
|
|
233
|
-
} catch {
|
|
234
|
-
return null;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
async function discoverWallets(o = {}) {
|
|
238
|
-
const out = [];
|
|
239
|
-
const ms = o.ms ?? 1200;
|
|
240
|
-
if (typeof window !== "undefined") {
|
|
241
|
-
const seen = /* @__PURE__ */ new Map();
|
|
242
|
-
const onAnnounce = (e) => {
|
|
243
|
-
const d = e.detail;
|
|
244
|
-
if (!d?.wallet) return;
|
|
245
|
-
const rdns = d.info?.rdns ?? d.info?.uuid ?? `wallet-${seen.size}`;
|
|
246
|
-
if (seen.has(rdns)) return;
|
|
247
|
-
const isB = BWALLETX_RDNS.includes(rdns);
|
|
248
|
-
seen.set(rdns, brc100Option(d.wallet, { id: rdns, rdns, name: NAMES[rdns] ?? d.info?.name ?? rdns, icon: d.info?.icon, isBwalletX: isB }));
|
|
249
|
-
};
|
|
250
|
-
window.addEventListener("brc100:announceWallet", onAnnounce);
|
|
251
|
-
window.dispatchEvent(new Event("brc100:requestWallet"));
|
|
252
|
-
const local = o.probeLocal ? Promise.all([probe("json-api", ms), probe("Cicada", ms)]) : Promise.resolve([null, null]);
|
|
253
|
-
await new Promise((r) => setTimeout(r, ms));
|
|
254
|
-
window.removeEventListener("brc100:announceWallet", onAnnounce);
|
|
255
|
-
out.push(...seen.values());
|
|
256
|
-
const cwi = window.CWI;
|
|
257
|
-
if (cwi && ![...seen.values()].some((x) => x.rdns === "space.bwallet.mobile")) {
|
|
258
|
-
out.push(brc100Option(cwi, { id: "window.CWI", name: "This app\u2019s wallet", isBwalletX: false }));
|
|
259
|
-
}
|
|
260
|
-
const [json, cicada] = await local;
|
|
261
|
-
if (json) out.push(brc100Option(json, { id: "localhost:3321", name: "Desktop wallet (localhost:3321)" }));
|
|
262
|
-
if (cicada) out.push(brc100Option(cicada, { id: "localhost:3301", name: "Desktop wallet (localhost:3301)" }));
|
|
263
|
-
}
|
|
264
|
-
if (o.pairing) out.push(pairingOption(o.pairing));
|
|
265
|
-
out.push(...o.extra ?? []);
|
|
266
|
-
const rank = (w) => w.isBwalletX ? 0 : w.kind === "handcash" ? 2 : 1;
|
|
267
|
-
return out.map((w, i) => ({ w, i })).sort((a, b) => rank(a.w) - rank(b.w) || a.i - b.i).map((x) => x.w);
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
// src/modal.ts
|
|
271
|
-
import qrcode from "qrcode-generator";
|
|
272
|
-
var CSS = `
|
|
273
|
-
.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}
|
|
274
|
-
.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)}
|
|
275
|
-
.bwx-box h2{margin:0 0 6px;font-size:18px;color:#e8c766}
|
|
276
|
-
.bwx-box p{margin:0 0 14px;color:#bdb6a3;font-size:14px}
|
|
277
|
-
.bwx-qr{background:#fff;border-radius:12px;padding:12px;display:flex;justify-content:center}
|
|
278
|
-
.bwx-qr svg{width:100%;height:auto;max-width:260px}
|
|
279
|
-
.bwx-code{margin:14px 0 0;text-align:center;font-size:28px;letter-spacing:.3em;color:#e8c766;font-variant-numeric:tabular-nums}
|
|
280
|
-
.bwx-row{display:flex;gap:8px;margin-top:14px}
|
|
281
|
-
.bwx-btn{flex:1;border:1px solid #3a3220;background:#15130e;color:#f4f1e8;border-radius:10px;padding:10px 12px;font:inherit;cursor:pointer}
|
|
282
|
-
.bwx-btn:hover{border-color:#e8c766}
|
|
283
|
-
a.bwx-btn{display:block;text-align:center;text-decoration:none;box-sizing:border-box}
|
|
284
|
-
.bwx-primary{background:linear-gradient(180deg,#fcd34d,#f59e0b);color:#000;border:0;font-weight:700;min-height:48px;padding:13px 12px}
|
|
285
|
-
.bwx-stack{display:flex;flex-direction:column;gap:8px}
|
|
286
|
-
.bwx-list{display:flex;flex-direction:column;gap:8px}
|
|
287
|
-
.bwx-opt{display:flex;align-items:center;gap:10px;text-align:left}
|
|
288
|
-
.bwx-opt img{width:24px;height:24px;border-radius:6px}
|
|
289
|
-
.bwx-tag{margin-left:auto;font-size:11px;color:#8d866f}
|
|
290
|
-
`;
|
|
291
|
-
function mount() {
|
|
292
|
-
const root = document.createElement("div");
|
|
293
|
-
root.className = "bwx-ov";
|
|
294
|
-
root.setAttribute("role", "dialog");
|
|
295
|
-
root.setAttribute("aria-modal", "true");
|
|
296
|
-
const style = document.createElement("style");
|
|
297
|
-
style.textContent = CSS;
|
|
298
|
-
const box = document.createElement("div");
|
|
299
|
-
box.className = "bwx-box";
|
|
300
|
-
root.append(style, box);
|
|
301
|
-
document.body.appendChild(root);
|
|
302
|
-
return { root, box, close: () => root.remove() };
|
|
303
|
-
}
|
|
304
|
-
function el(tag, cls, text) {
|
|
305
|
-
const e = document.createElement(tag);
|
|
306
|
-
if (cls) e.className = cls;
|
|
307
|
-
if (text != null) e.textContent = text;
|
|
308
|
-
return e;
|
|
309
|
-
}
|
|
310
|
-
function qrSvg(text) {
|
|
311
|
-
const q = qrcode(0, "M");
|
|
312
|
-
q.addData(text);
|
|
313
|
-
q.make();
|
|
314
|
-
return q.createSvgTag({ cellSize: 4, margin: 2, scalable: true });
|
|
315
|
-
}
|
|
316
|
-
function isTouchDevice(env = globalThis) {
|
|
317
|
-
const nav = env.navigator;
|
|
318
|
-
if (!nav) return false;
|
|
319
|
-
const ua = nav.userAgent ?? "";
|
|
320
|
-
if (/Android|iPhone|iPad|iPod|Mobile|Silk|Kindle/i.test(ua)) return true;
|
|
321
|
-
if (/Macintosh/.test(ua) && (nav.maxTouchPoints ?? 0) > 1) return true;
|
|
322
|
-
try {
|
|
323
|
-
return !!env.matchMedia?.("(pointer: coarse)").matches && !env.matchMedia?.("(hover: hover)").matches;
|
|
324
|
-
} catch {
|
|
325
|
-
return false;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
function pairingModal(o = {}) {
|
|
329
|
-
const ac = new AbortController();
|
|
330
|
-
let ui = null;
|
|
331
|
-
let codeEl = null;
|
|
332
|
-
const close = () => {
|
|
333
|
-
ui?.close();
|
|
334
|
-
ui = null;
|
|
335
|
-
};
|
|
336
|
-
ac.signal.addEventListener("abort", close);
|
|
337
|
-
return {
|
|
338
|
-
signal: ac.signal,
|
|
339
|
-
close,
|
|
340
|
-
onLink(link) {
|
|
341
|
-
if (typeof document === "undefined") return;
|
|
342
|
-
close();
|
|
343
|
-
ui = mount();
|
|
344
|
-
const app = o.mode === "app" || (o.mode ?? "auto") === "auto" && isTouchDevice();
|
|
345
|
-
const h = el("h2", "", o.title ?? "Connect bWalletX");
|
|
346
|
-
const cancel = el("button", "bwx-btn", "Cancel");
|
|
347
|
-
cancel.onclick = () => {
|
|
348
|
-
o.onCancel?.();
|
|
349
|
-
ac.abort();
|
|
350
|
-
};
|
|
351
|
-
codeEl = el("div", "bwx-code", "");
|
|
352
|
-
codeEl.setAttribute("aria-live", "polite");
|
|
353
|
-
if (app) {
|
|
354
|
-
const p2 = el("p", "", "Open bWalletX, approve, then come back to this page.");
|
|
355
|
-
const stack = el("div", "bwx-stack");
|
|
356
|
-
const open = el("a", "bwx-btn bwx-primary", "Open bWalletX");
|
|
357
|
-
open.href = link;
|
|
358
|
-
open.rel = "noopener";
|
|
359
|
-
const web = el("button", "bwx-btn", "Use web.bwalletx.com instead");
|
|
360
|
-
web.onclick = () => {
|
|
361
|
-
void navigator.clipboard?.writeText(link).catch(() => void 0);
|
|
362
|
-
window.open(WEB_WALLET_URL, "_blank", "noopener");
|
|
363
|
-
p2.textContent = "Link copied. In web.bwalletx.com tap Connect and paste it, then come back here.";
|
|
364
|
-
};
|
|
365
|
-
stack.append(open, web, cancel);
|
|
366
|
-
ui.box.append(h, p2, codeEl, stack);
|
|
367
|
-
return;
|
|
368
|
-
}
|
|
369
|
-
const p = el("p", "", "Scan with bWalletX on your phone, or paste the link into web.bwalletx.com.");
|
|
370
|
-
const qr = el("div", "bwx-qr");
|
|
371
|
-
qr.innerHTML = qrSvg(link);
|
|
372
|
-
const row = el("div", "bwx-row");
|
|
373
|
-
const copy = el("button", "bwx-btn", "Copy link");
|
|
374
|
-
copy.onclick = () => void navigator.clipboard?.writeText(link).then(() => copy.textContent = "Copied");
|
|
375
|
-
row.append(copy, cancel);
|
|
376
|
-
ui.box.append(h, p, qr, codeEl, row);
|
|
377
|
-
},
|
|
378
|
-
onCode(code) {
|
|
379
|
-
if (codeEl) {
|
|
380
|
-
codeEl.textContent = code;
|
|
381
|
-
const p = ui?.box.querySelector("p");
|
|
382
|
-
if (p) p.textContent = "Check bWalletX shows the same code, then tap Connect.";
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
};
|
|
386
|
-
}
|
|
387
|
-
function pickWallet(options, o = {}) {
|
|
388
|
-
if (typeof document === "undefined") return Promise.resolve(null);
|
|
389
|
-
return new Promise((resolve) => {
|
|
390
|
-
const ui = mount();
|
|
391
|
-
const done = (w) => {
|
|
392
|
-
ui.close();
|
|
393
|
-
resolve(w);
|
|
394
|
-
};
|
|
395
|
-
ui.box.append(el("h2", "", o.title ?? "Choose a wallet"));
|
|
396
|
-
if (!options.length) ui.box.append(el("p", "", "No wallet found. Get bWalletX at bwalletx.com."));
|
|
397
|
-
const list = el("div", "bwx-list");
|
|
398
|
-
for (const w of options) {
|
|
399
|
-
const b = el("button", "bwx-btn bwx-opt");
|
|
400
|
-
if (w.icon) {
|
|
401
|
-
const img = el("img");
|
|
402
|
-
img.src = w.icon;
|
|
403
|
-
img.alt = "";
|
|
404
|
-
b.append(img);
|
|
405
|
-
}
|
|
406
|
-
b.append(el("span", "", w.name));
|
|
407
|
-
if (w.kind === "handcash") b.append(el("span", "bwx-tag", "until BRC-100"));
|
|
408
|
-
b.onclick = () => done(w);
|
|
409
|
-
list.append(b);
|
|
410
|
-
}
|
|
411
|
-
const cancel = el("button", "bwx-btn", "Cancel");
|
|
412
|
-
cancel.onclick = () => done(null);
|
|
413
|
-
ui.root.onclick = (e) => e.target === ui.root && done(null);
|
|
414
|
-
ui.box.append(list, el("div", "bwx-row"));
|
|
415
|
-
ui.box.lastChild.append(cancel);
|
|
416
|
-
});
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
// src/theme.ts
|
|
420
|
-
var WALLET_THEME_META = "bwalletx-theme";
|
|
421
|
-
var ID = /^[a-z0-9-]{1,32}$/;
|
|
422
|
-
function declareWalletTheme(theme) {
|
|
423
|
-
if (typeof document === "undefined") return;
|
|
424
|
-
const id = (theme ?? "").trim().toLowerCase();
|
|
425
|
-
let meta = document.head.querySelector(`meta[name="${WALLET_THEME_META}"]`);
|
|
426
|
-
if (!id || !ID.test(id)) {
|
|
427
|
-
meta?.remove();
|
|
428
|
-
return;
|
|
429
|
-
}
|
|
430
|
-
if (!meta) {
|
|
431
|
-
meta = document.createElement("meta");
|
|
432
|
-
meta.name = WALLET_THEME_META;
|
|
433
|
-
document.head.appendChild(meta);
|
|
434
|
-
}
|
|
435
|
-
if (meta.content !== id) meta.content = id;
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
export {
|
|
439
|
-
BRC29_PROTOCOL,
|
|
440
|
-
PaymentError,
|
|
441
|
-
isIdentityKeyHex,
|
|
442
|
-
isPaymail,
|
|
443
|
-
amountInSats,
|
|
444
|
-
resolvePaymailP2P,
|
|
445
|
-
pay,
|
|
446
|
-
tip,
|
|
447
|
-
buyToken,
|
|
448
|
-
brc100Option,
|
|
449
|
-
pairingOption,
|
|
450
|
-
handcashAdapter,
|
|
451
|
-
discoverWallets,
|
|
452
|
-
qrSvg,
|
|
453
|
-
isTouchDevice,
|
|
454
|
-
pairingModal,
|
|
455
|
-
pickWallet,
|
|
456
|
-
WALLET_THEME_META,
|
|
457
|
-
declareWalletTheme
|
|
458
|
-
};
|
|
459
|
-
//# sourceMappingURL=chunk-PI42H3XY.js.map
|