@qntx/wallet-engine 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +1057 -20
  2. package/dist/apps-fiat24.d.mts +202 -0
  3. package/dist/apps-fiat24.mjs +1378 -0
  4. package/dist/apps-fiat24.mjs.map +1 -0
  5. package/dist/apps-hyperliquid.d.mts +549 -0
  6. package/dist/apps-hyperliquid.mjs +2742 -0
  7. package/dist/apps-hyperliquid.mjs.map +1 -0
  8. package/dist/apps-polymarket.d.mts +729 -0
  9. package/dist/apps-polymarket.mjs +3786 -0
  10. package/dist/apps-polymarket.mjs.map +1 -0
  11. package/dist/apps.d.mts +136 -0
  12. package/dist/apps.mjs +535 -0
  13. package/dist/apps.mjs.map +1 -0
  14. package/dist/connect-BY1C5ZRI.mjs +210 -0
  15. package/dist/connect-BY1C5ZRI.mjs.map +1 -0
  16. package/dist/connect.d.mts +17 -9
  17. package/dist/connect.mjs +3 -185
  18. package/dist/controller-DpNVHVsj.d.mts +2295 -0
  19. package/dist/controller-rMnaxKAH.mjs +46 -0
  20. package/dist/controller-rMnaxKAH.mjs.map +1 -0
  21. package/dist/decimal-COJ4g8qy.mjs +38 -0
  22. package/dist/decimal-COJ4g8qy.mjs.map +1 -0
  23. package/dist/eligibility-BfM9ybYZ.mjs +48 -0
  24. package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
  25. package/dist/engine-Dic_kkEr.d.mts +1829 -0
  26. package/dist/errors-B8W-hoYW.d.mts +7 -0
  27. package/dist/errors-horUy5k1.mjs +24 -0
  28. package/dist/errors-horUy5k1.mjs.map +1 -0
  29. package/dist/gateway-contract.d.mts +3 -362
  30. package/dist/gateway-contract.mjs +1531 -81
  31. package/dist/gateway-contract.mjs.map +1 -1
  32. package/dist/idb.d.mts +5 -0
  33. package/dist/idb.mjs +122 -46
  34. package/dist/idb.mjs.map +1 -1
  35. package/dist/index-vBgfOFIh.d.mts +2227 -0
  36. package/dist/index.d.mts +58 -515
  37. package/dist/index.mjs +22314 -4901
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/json-BDwV38cj.mjs +15 -0
  40. package/dist/json-BDwV38cj.mjs.map +1 -0
  41. package/dist/link-Ceq8Dggp.mjs +139 -0
  42. package/dist/link-Ceq8Dggp.mjs.map +1 -0
  43. package/dist/primitives-DbSHLZKq.mjs +31 -0
  44. package/dist/primitives-DbSHLZKq.mjs.map +1 -0
  45. package/dist/push-message-AQuzoNFY.d.mts +84 -0
  46. package/dist/push-message-kbnH1A5w.mjs +142 -0
  47. package/dist/push-message-kbnH1A5w.mjs.map +1 -0
  48. package/dist/push.d.mts +13 -0
  49. package/dist/push.mjs +70 -0
  50. package/dist/push.mjs.map +1 -0
  51. package/dist/qr.d.mts +292 -0
  52. package/dist/qr.mjs +1725 -0
  53. package/dist/qr.mjs.map +1 -0
  54. package/dist/registry-CbtwcxkX.mjs +374 -0
  55. package/dist/registry-CbtwcxkX.mjs.map +1 -0
  56. package/dist/risk-DyABgg4W.mjs +757 -0
  57. package/dist/risk-DyABgg4W.mjs.map +1 -0
  58. package/dist/session-CNJFLarP.mjs +18 -0
  59. package/dist/session-CNJFLarP.mjs.map +1 -0
  60. package/dist/socket-ChG9JRT_.mjs +110 -0
  61. package/dist/socket-ChG9JRT_.mjs.map +1 -0
  62. package/dist/spi-BrTw5s98.d.mts +3 -0
  63. package/dist/timer-Cdk5rGM2.mjs +43 -0
  64. package/dist/timer-Cdk5rGM2.mjs.map +1 -0
  65. package/dist/types-BpvioFGo.d.mts +258 -0
  66. package/dist/types-DbftVZ3I.mjs +90 -0
  67. package/dist/types-DbftVZ3I.mjs.map +1 -0
  68. package/dist/walletconnect.d.mts +86 -0
  69. package/dist/walletconnect.mjs +1507 -0
  70. package/dist/walletconnect.mjs.map +1 -0
  71. package/dist/webln-BgrtPXpG.mjs +2593 -0
  72. package/dist/webln-BgrtPXpG.mjs.map +1 -0
  73. package/dist/webln-Bllk_xJ2.d.mts +666 -0
  74. package/package.json +94 -19
  75. package/dist/connect.mjs.map +0 -1
  76. package/dist/errors-DpkJneDe.d.mts +0 -1696
  77. package/dist/registry-Deo5WQe1.d.mts +0 -25
  78. package/dist/registry-wYrcuFNc.mjs +0 -99
  79. package/dist/registry-wYrcuFNc.mjs.map +0 -1
  80. package/dist/webln-DzsI7jVb.mjs +0 -3629
  81. package/dist/webln-DzsI7jVb.mjs.map +0 -1
@@ -0,0 +1,2593 @@
1
+ import { t as Controller } from "./controller-rMnaxKAH.mjs";
2
+ import { r as errorMessage } from "./errors-horUy5k1.mjs";
3
+ import { t as readJson } from "./json-BDwV38cj.mjs";
4
+ import { a as SignInOriginError, d as walletConnectKey, i as RequestEndedError, l as isDappOrigin, r as OriginBusyError, s as dappUrl, t as InvalidTokenError } from "./types-DbftVZ3I.mjs";
5
+ import { a as networkById, r as SOLANA_NETWORKS, t as BITCOIN_NETWORKS } from "./registry-CbtwcxkX.mjs";
6
+ import { ChainError } from "@qntx/wallet-chains";
7
+ import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
8
+ import { decodeSolanaTransaction } from "@qntx/wallet-chains/solana";
9
+ import { isTronAddress, tronAddressToHex, tronRawDataFromJson, tronTypedDataFromArgs } from "@qntx/wallet-chains/tron";
10
+ import { sha256 } from "@noble/hashes/sha2.js";
11
+ import { base58, base64 } from "@scure/base";
12
+ import { bitcoinAddressScript, decodeBolt11, decodeSparkAddress, parseSparkInvoice } from "@qntx/spark";
13
+ import { decodeLnurl, lightningAddressUrl } from "@qntx/spark/lnurl";
14
+ // src/phishing/status.ts
15
+ const PHISHING_BLOCKED_MESSAGE = "origin is on the phishing list";
16
+ // src/connect/errors.ts
17
+ /** EIP-1193 / EIP-1474 / EIP-3326 error: `code` is what the page's promise rejects with. */
18
+ var ProviderError = class extends Error {
19
+ code;
20
+ constructor(code, message) {
21
+ super(message);
22
+ this.name = "ProviderError";
23
+ this.code = code;
24
+ }
25
+ };
26
+ const userRejectedRequest = (message = "user rejected the request") => new ProviderError(4001, message);
27
+ const unauthorized = (message = "not authorized") => new ProviderError(4100, message);
28
+ const unsupportedMethod = (method) => new ProviderError(4200, `${method} is not supported`);
29
+ const unrecognizedChain = (message = "unrecognized chain") => new ProviderError(4902, message);
30
+ const invalidParams = (message) => new ProviderError(-32602, message);
31
+ const requestPending = (message) => new ProviderError(-32002, message);
32
+ /** EIP-1474 "limit exceeded": the request is valid but asks for more than the wallet serves. */
33
+ const limitExceeded = (message) => new ProviderError(-32005, message);
34
+ const internalError = (message) => new ProviderError(-32603, message);
35
+ function toProviderError$1(error) {
36
+ if (error instanceof ProviderError) return error;
37
+ if (error instanceof InvalidTokenError || error instanceof SignInOriginError) return invalidParams(error.message);
38
+ if (error instanceof OriginBusyError) return userRejectedRequest(error.message);
39
+ if (error instanceof RequestEndedError) return error.stage === "failed" ? internalError(error.message) : userRejectedRequest(error.message);
40
+ if (error instanceof ChainError) return invalidParams(error.message);
41
+ return internalError(error instanceof Error ? error.message : String(error));
42
+ }
43
+ /** JSON-RPC implementation-defined server error (outside EIP-1474's assigned codes). */
44
+ const PAYMENT_PENDING_CODE = -32010;
45
+ /**
46
+ * The payment may have been made — it may still settle, or settled without a usable answer — never
47
+ * an error the page can safely retry: an lnurl dApp that retries on failure would fetch a new
48
+ * invoice and pay twice.
49
+ */
50
+ const paymentPending = (message) => new ProviderError(PAYMENT_PENDING_CODE, message);
51
+ /**
52
+ * A batch send that stopped at `stopped.index` (never the first: a first failure fails the request
53
+ * instead). `reason` is `"refused"` only when the node itself rejected those bytes — the stopped
54
+ * input and everything after it never went out — while anything else means a local failure kept it
55
+ * from being sent at all. The message lists the ids already submitted so the page does not resubmit
56
+ * them.
57
+ */
58
+ const batchStopped = (stopped, submitted) => {
59
+ const head = stopped.reason === "refused" ? `the network refused transaction ${String(stopped.index)}` : `transaction ${String(stopped.index)} was not sent`;
60
+ return internalError(`${head}: ${stopped.error} — it and every later transaction were not sent; already submitted, do not resubmit: ${submitted.join(", ")}`);
61
+ };
62
+ /** A pending connection request that nobody answers is rejected after this long. */
63
+ const CONNECTION_REQUEST_TTL_MS = 6e5;
64
+ const COLLECTION = "connections";
65
+ /** `lastUsedAt` is rewritten at most this often. */
66
+ const TOUCH_INTERVAL_MS = 6e4;
67
+ /** Granted for every network a session covers. */
68
+ const SESSION_METHODS = [
69
+ "eth_sendTransaction",
70
+ "personal_sign",
71
+ "eth_signTypedData_v4",
72
+ "wallet_watchAsset",
73
+ "wallet_getCapabilities",
74
+ "wallet_sendCalls",
75
+ "wallet_getCallsStatus",
76
+ "wallet_showCallsStatus"
77
+ ];
78
+ const SESSION_NOTIFICATIONS = ["accountsChanged", "chainChanged"];
79
+ /** The `nostr` namespace scope's granted methods — the NIP-07 surface. */
80
+ const NOSTR_METHODS = [
81
+ "getPublicKey",
82
+ "signEvent",
83
+ "nip04.encrypt",
84
+ "nip04.decrypt",
85
+ "nip44.encrypt",
86
+ "nip44.decrypt"
87
+ ];
88
+ /** The `lightning` namespace scope's granted methods — the WebLN surface. */
89
+ const LIGHTNING_METHODS = [
90
+ "enable",
91
+ "getInfo",
92
+ "sendPayment",
93
+ "makeInvoice",
94
+ "lnurl",
95
+ "getBalance"
96
+ ];
97
+ /** The `solana` namespace scope's granted methods — the Wallet Standard surface. */
98
+ const SOLANA_METHODS = [
99
+ "standard:connect",
100
+ "standard:disconnect",
101
+ "standard:events",
102
+ "solana:signTransaction",
103
+ "solana:signAndSendTransaction",
104
+ "solana:signMessage",
105
+ "solana:signIn"
106
+ ];
107
+ /** The `bip122` namespace scope's granted methods — the Bitcoin Wallet Standard surface. */
108
+ const BITCOIN_METHODS = [
109
+ "bitcoin:connect",
110
+ "standard:disconnect",
111
+ "bitcoin:events",
112
+ "bitcoin:signMessage",
113
+ "bitcoin:signTransaction",
114
+ "bitcoin:signAndSendTransaction"
115
+ ];
116
+ /** The `tron` namespace scope's granted methods — the TronLink surface. */
117
+ const TRON_METHODS = [
118
+ "eth_requestAccounts",
119
+ "tron_requestAccounts",
120
+ "wallet_switchEthereumChain",
121
+ "wallet_watchAsset",
122
+ "tron_signTransaction",
123
+ "tron_sendRawTransaction",
124
+ "tron_signMessageV2",
125
+ "tron_signTypedData"
126
+ ];
127
+ /** The `tron` namespace scope's notifications. */
128
+ const TRON_NOTIFICATIONS = ["accountsChanged", "chainChanged"];
129
+ /** The order of a `bip122` scope's two accounts. */
130
+ const BITCOIN_PURPOSES = ["payment", "ordinals"];
131
+ /** `eip155:1` → 1; `undefined` for anything that is not an EVM network. */
132
+ const evmChainId = (network) => {
133
+ const match = /^eip155:(\d+)$/.exec(network);
134
+ const id = match?.[1] === void 0 ? void 0 : Number(match[1]);
135
+ return id !== void 0 && Number.isSafeInteger(id) ? id : void 0;
136
+ };
137
+ const caip10 = (network, address) => `${network}:${address}`;
138
+ const addressOf = (account) => account.slice(account.lastIndexOf(":") + 1);
139
+ const isObject$3 = (v) => typeof v === "object" && v !== null;
140
+ const isGroup = (value) => isObject$3(value) && typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && Number.isSafeInteger(value["groupIndex"]) && value["groupIndex"] >= 0;
141
+ const isIdentity = (value) => isObject$3(value) && value["kind"] === "derived" && typeof value["walletId"] === "string" && typeof value["index"] === "number" && Number.isSafeInteger(value["index"]) && value["index"] >= 0;
142
+ const isSession = (value) => {
143
+ if (!isObject$3(value) || !isObject$3(value["scopes"])) return false;
144
+ const { origin } = value;
145
+ return typeof value["id"] === "string" && isDappOrigin(origin) && (origin.kind !== "walletconnect" || origin.origin === walletConnectKey(origin.topic)) && typeof value["currentNetwork"] === "string" && (value["tronNetwork"] === void 0 || typeof value["tronNetwork"] === "string") && typeof value["createdAt"] === "number" && typeof value["lastUsedAt"] === "number" && (value["group"] === void 0 || isGroup(value["group"])) && (value["identity"] === void 0 || isIdentity(value["identity"])) && (value["nostrPolicy"] === void 0 || isNostrPolicy(value["nostrPolicy"])) && (value["lightningPolicy"] === void 0 || isLightningPolicy(value["lightningPolicy"]));
146
+ };
147
+ const isLightningPolicy = (value) => isObject$3(value) && typeof value["balance"] === "boolean";
148
+ const isNostrPolicy = (value) => isObject$3(value) && typeof value["decrypt"] === "boolean" && (value["signing"] === "ask" || value["signing"] === "always" || isObject$3(value["signing"]) && Array.isArray(value["signing"]["kinds"]) && value["signing"]["kinds"].every((k) => typeof k === "number"));
149
+ /** `undefined` unless the session covers `network` with at least one account and has a group. */
150
+ const sessionAccounts = (session, network) => {
151
+ const scope = session?.scopes[network];
152
+ if (session?.group === void 0 || scope === void 0 || scope.accounts.length === 0) return;
153
+ return {
154
+ group: session.group,
155
+ addresses: scope.accounts.map(addressOf)
156
+ };
157
+ };
158
+ /** The identity and pubkey a session bound to its `nostr` scope; `undefined` when it has neither. */
159
+ const sessionIdentity = (session) => {
160
+ const account = session?.scopes["nostr"]?.accounts[0];
161
+ if (session?.identity === void 0 || account === void 0) return;
162
+ return {
163
+ ref: session.identity,
164
+ pubkey: addressOf(account)
165
+ };
166
+ };
167
+ const sameGroup = (a, b) => a === void 0 || b === void 0 ? a === b : a.walletId === b.walletId && a.groupIndex === b.groupIndex;
168
+ /** A scope a group signs for — chain networks and `lightning`; `nostr` belongs to the identity. */
169
+ const isChainScope = (network) => network === "lightning" || network.startsWith("eip155:") || network.startsWith("solana:") || network.startsWith("bip122:") || network.startsWith("tron:");
170
+ var ConnectionController = class extends Controller {
171
+ options;
172
+ engineStore;
173
+ waiters = /* @__PURE__ */ new Map();
174
+ expiries = /* @__PURE__ */ new Map();
175
+ identity;
176
+ unsubscribeSelection;
177
+ writeQueue = Promise.resolve();
178
+ constructor(options) {
179
+ super({
180
+ name: "connections",
181
+ defaultState: () => ({
182
+ sessions: {},
183
+ pending: {},
184
+ ready: false
185
+ })
186
+ });
187
+ this.options = options;
188
+ }
189
+ async init() {
190
+ const store = await this.options.openStore();
191
+ this.engineStore = store;
192
+ this.identity = void 0;
193
+ const collection = store.collection(COLLECTION);
194
+ const keys = await collection.list();
195
+ const rows = await Promise.all(keys.map(async (key) => collection.get(key)));
196
+ const now = this.options.now();
197
+ const sessions = {};
198
+ const expired = [];
199
+ for (const [index, raw] of rows.entries()) {
200
+ const key = keys[index];
201
+ if (raw === void 0 || key === void 0) continue;
202
+ const parsed = readJson(raw);
203
+ if (!isSession(parsed)) {
204
+ this.options.logger.warn("connection session skipped: malformed");
205
+ expired.push(key);
206
+ } else if (now - parsed.lastUsedAt > 7776e6) expired.push(key);
207
+ else sessions[parsed.id] = parsed;
208
+ }
209
+ await Promise.all(expired.map(async (key) => collection.delete(key)));
210
+ this.update(() => ({
211
+ sessions,
212
+ pending: {},
213
+ ready: true
214
+ }));
215
+ this.unsubscribeSelection = this.options.onSelectedGroup(() => {
216
+ this.options.invalidateAll();
217
+ this.repointQueued();
218
+ });
219
+ }
220
+ async destroy() {
221
+ this.lock();
222
+ await Promise.resolve();
223
+ }
224
+ /** Locking is not consent: every pending connection is rejected. */
225
+ lock() {
226
+ this.unsubscribeSelection?.();
227
+ this.unsubscribeSelection = void 0;
228
+ this.engineStore = void 0;
229
+ for (const waiter of this.waiters.values()) waiter.reject(userRejectedRequest("the wallet was locked"));
230
+ this.waiters.clear();
231
+ for (const cancel of this.expiries.values()) cancel();
232
+ this.expiries.clear();
233
+ this.update(() => ({
234
+ sessions: {},
235
+ pending: {},
236
+ ready: false
237
+ }));
238
+ }
239
+ /**
240
+ * A page navigated away (or the bridge is being disposed): the origin's pending connection
241
+ * requests are rejected and its unfinished pipeline requests voided — the live session survives
242
+ * (a refresh is not a revocation).
243
+ */
244
+ invalidateOrigin(origin) {
245
+ for (const entry of this.pending()) {
246
+ if (entry.origin.origin !== origin) continue;
247
+ this.waiters.get(entry.id)?.reject(userRejectedRequest("the page navigated away"));
248
+ this.dropPending(entry.id);
249
+ }
250
+ this.options.invalidate(origin);
251
+ }
252
+ /**
253
+ * Throws `4100` unless `origin` is `https://host[:port]` (or localhost in development) and not on
254
+ * the phishing list. A WalletConnect peer instead passes its origin object: an established
255
+ * session must carry the same session key and topic, and its unverified peer URL must not be on
256
+ * the phishing list.
257
+ */
258
+ checkOrigin(origin) {
259
+ if (typeof origin !== "string") {
260
+ if (Object.values(this.getState().sessions).find((s) => s.origin.kind === "walletconnect" && s.origin.origin === origin.origin && s.origin.topic === origin.topic) === void 0) throw unauthorized();
261
+ if (this.options.phishing.check(origin.url) === "blocked") throw unauthorized(PHISHING_BLOCKED_MESSAGE);
262
+ return origin;
263
+ }
264
+ let url;
265
+ try {
266
+ url = new URL(origin);
267
+ } catch {
268
+ throw unauthorized("invalid origin");
269
+ }
270
+ const localhost = url.protocol === "http:" && url.hostname === "localhost";
271
+ if (url.origin !== origin || url.protocol !== "https:" && !(localhost && this.options.allowLocalhost)) throw unauthorized("origin not allowed");
272
+ if (this.options.phishing.check(origin) === "blocked") throw unauthorized(PHISHING_BLOCKED_MESSAGE);
273
+ return {
274
+ kind: "browser",
275
+ origin
276
+ };
277
+ }
278
+ session(origin) {
279
+ return Object.values(this.getState().sessions).find((s) => s.origin.origin === origin);
280
+ }
281
+ pending() {
282
+ return Object.values(this.getState().pending);
283
+ }
284
+ /** What the origin's session authorized on `network` — `undefined` when nothing. */
285
+ sessionAccounts(origin, network) {
286
+ return sessionAccounts(this.session(origin), network);
287
+ }
288
+ /**
289
+ * The selected group's accounts on `network` as a grant would bind them — a preview for callers
290
+ * that sign before a session exists; nothing is persisted. `undefined` when no group is selected
291
+ * or the account cannot be derived.
292
+ */
293
+ async previewAccounts(network) {
294
+ const group = this.options.selectedGroup();
295
+ if (group === void 0) return;
296
+ const scope = (await this.repointScopes({ [network]: {
297
+ accounts: [],
298
+ methods: [],
299
+ notifications: []
300
+ } }, group))[network];
301
+ if (scope === void 0 || scope.accounts.length === 0) return;
302
+ return {
303
+ group,
304
+ addresses: scope.accounts.map(addressOf)
305
+ };
306
+ }
307
+ /** The identity the origin's `nostr` scope is bound to, with the pubkey the page sees. */
308
+ nostrIdentity(origin) {
309
+ return sessionIdentity(this.session(origin));
310
+ }
311
+ /** Whether `network` is an EVM network the wallet has enabled. */
312
+ isEnabled(network) {
313
+ return this.options.enabledNetworks().includes(network);
314
+ }
315
+ /** Throws `4100` unless the origin's session covers `method` on `network`. */
316
+ authorize(origin, network, method) {
317
+ const session = this.session(origin);
318
+ const scope = session?.scopes[network];
319
+ if (session === void 0 || scope === void 0 || !scope.methods.includes(method)) throw unauthorized();
320
+ return session;
321
+ }
322
+ /** Resolves with the session once the host approves; rejects with `4001` when it refuses. */
323
+ async request(origin, { kind, namespace = "eip155", network, activate = true }) {
324
+ if (this.engineStore === void 0) throw userRejectedRequest("the wallet is locked");
325
+ if (this.pending().some((p) => p.origin.origin === origin)) throw requestPending("a connection request is already pending");
326
+ if (this.pending().length >= 64) throw requestPending("too many pending connection requests");
327
+ const id = `conn-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
328
+ const entry = {
329
+ id,
330
+ origin: this.session(origin)?.origin ?? {
331
+ kind: "browser",
332
+ origin
333
+ },
334
+ kind,
335
+ namespace,
336
+ ...network === void 0 ? {} : { network },
337
+ ...activate ? {} : { activate },
338
+ createdAt: this.options.now()
339
+ };
340
+ return new Promise((resolve, reject) => {
341
+ this.waiters.set(id, {
342
+ resolve,
343
+ reject
344
+ });
345
+ this.expiries.set(id, this.options.setTimer(CONNECTION_REQUEST_TTL_MS, () => {
346
+ this.waiters.get(id)?.reject(userRejectedRequest("the connection request expired"));
347
+ this.dropPending(id);
348
+ }));
349
+ this.update((s) => ({
350
+ ...s,
351
+ pending: {
352
+ ...s.pending,
353
+ [id]: entry
354
+ }
355
+ }));
356
+ });
357
+ }
358
+ /**
359
+ * The host's approval, by id: the accounts granted (of the app's selected group for a
360
+ * chain/lightning grant, of the active identity for `nostr`) and the network. The whole
361
+ * derivation, merge and persist runs inside the session write queue, so a concurrent group switch
362
+ * cannot interleave.
363
+ */
364
+ async approveConnection(id, grant) {
365
+ const entry = this.getState().pending[id];
366
+ const waiter = this.waiters.get(id);
367
+ if (entry === void 0 || waiter === void 0) throw new Error(`unknown connection request ${id}`);
368
+ if (this.options.phishing.check(dappUrl(entry.origin)) === "blocked") {
369
+ const blocked = unauthorized(PHISHING_BLOCKED_MESSAGE);
370
+ this.dropPending(id);
371
+ waiter.reject(blocked);
372
+ throw blocked;
373
+ }
374
+ if (entry.kind === "network" && entry.network !== grant.network) throw new Error(`connection request ${id} is for ${String(entry.network)}`);
375
+ return this.serial(async () => {
376
+ const store = this.requireStore();
377
+ const { scopes, group, identity, tronNetwork } = await this.grantScopes(entry, grant);
378
+ if (this.getState().pending[id] === void 0) throw new Error(`connection request ${id} is no longer pending`);
379
+ const now = this.options.now();
380
+ const existing = this.session(entry.origin.origin);
381
+ const repointed = group !== void 0 && existing !== void 0 && !sameGroup(existing.group, group);
382
+ const merged = repointed ? await this.repointScopes(existing.scopes, group) : { ...existing?.scopes };
383
+ const sessionGroup = group ?? existing?.group;
384
+ const sessionIdentity = identity ?? existing?.identity;
385
+ const sessionTronNetwork = tronNetwork ?? existing?.tronNetwork;
386
+ const nostrPolicy = grant.nostr?.policy ?? existing?.nostrPolicy;
387
+ const lightningPolicy = grant.lightning?.policy ?? existing?.lightningPolicy;
388
+ const session = {
389
+ id: existing?.id ?? this.newSessionId(),
390
+ origin: entry.origin,
391
+ scopes: {
392
+ ...merged,
393
+ ...scopes
394
+ },
395
+ currentNetwork: entry.activate === false && existing !== void 0 ? existing.currentNetwork : grant.network,
396
+ ...sessionGroup === void 0 ? {} : { group: sessionGroup },
397
+ ...sessionIdentity === void 0 ? {} : { identity: sessionIdentity },
398
+ ...sessionTronNetwork === void 0 ? {} : { tronNetwork: sessionTronNetwork },
399
+ ...nostrPolicy === void 0 ? {} : { nostrPolicy },
400
+ ...lightningPolicy === void 0 ? {} : { lightningPolicy },
401
+ createdAt: existing?.createdAt ?? now,
402
+ lastUsedAt: now
403
+ };
404
+ await this.persist(store, session);
405
+ this.dropPending(id);
406
+ if (repointed || existing !== void 0 && existing.currentNetwork !== session.currentNetwork) this.options.invalidate(entry.origin.origin);
407
+ waiter.resolve(session);
408
+ return session;
409
+ });
410
+ }
411
+ rejectConnection(id) {
412
+ const waiter = this.waiters.get(id);
413
+ if (this.getState().pending[id] === void 0 || waiter === void 0) throw new Error(`unknown connection request ${id}`);
414
+ this.dropPending(id);
415
+ waiter.reject(userRejectedRequest());
416
+ }
417
+ /**
418
+ * Establishes a WalletConnect peer's session inside the session write queue: each network's scope
419
+ * is bound to the selected group's accounts, `settle` receives the bound scopes and settles the
420
+ * peer on the relay, returning its origin, and the session is persisted under that origin — a
421
+ * group switch cannot interleave between the accounts the peer is given and the ones recorded.
422
+ * Nothing is persisted when `settle` throws.
423
+ */
424
+ async establishWalletConnect(scopes, settle) {
425
+ return this.serial(async () => {
426
+ const store = this.requireStore();
427
+ const group = this.options.selectedGroup();
428
+ if (group === void 0) throw userRejectedRequest("no account group is selected");
429
+ const enabled = this.options.enabledNetworks();
430
+ const boundable = (network) => (network.startsWith("eip155:") || network.startsWith("solana:") || network.startsWith("bip122:")) && enabled.includes(network);
431
+ const requested = Object.keys(scopes);
432
+ const [first] = requested;
433
+ if (first === void 0 || !requested.every(boundable)) throw invalidParams("every scope must name an enabled eip155, solana or bip122 network");
434
+ const bound = await this.repointScopes(Object.fromEntries(Object.entries(scopes).map(([network, scope]) => [network, {
435
+ ...scope,
436
+ accounts: []
437
+ }])), group);
438
+ if (Object.values(bound).some((scope) => scope.accounts.length === 0)) throw internalError("an account could not be derived for a granted network");
439
+ const origin = await settle(bound);
440
+ const existing = this.session(origin.origin);
441
+ const now = this.options.now();
442
+ const session = {
443
+ id: existing?.id ?? this.newSessionId(),
444
+ origin,
445
+ scopes: bound,
446
+ group,
447
+ currentNetwork: requested.find((network) => network.startsWith("eip155:")) ?? first,
448
+ createdAt: existing?.createdAt ?? now,
449
+ lastUsedAt: now
450
+ };
451
+ await this.persist(store, session);
452
+ return session;
453
+ });
454
+ }
455
+ /** Ends the origin's session; its pending connection and unfinished requests are void. */
456
+ async revoke(origin) {
457
+ await this.serial(async () => {
458
+ const store = this.requireStore();
459
+ for (const p of this.pending().filter((x) => x.origin.origin === origin)) {
460
+ const waiter = this.waiters.get(p.id);
461
+ this.dropPending(p.id);
462
+ waiter?.reject(userRejectedRequest("the connection was revoked"));
463
+ }
464
+ const session = this.session(origin);
465
+ if (session !== void 0) {
466
+ await store.collection(COLLECTION).delete(session.id);
467
+ this.update((s) => {
468
+ const { [session.id]: _gone, ...sessions } = s.sessions;
469
+ return {
470
+ ...s,
471
+ sessions
472
+ };
473
+ });
474
+ }
475
+ this.options.invalidate(origin);
476
+ });
477
+ }
478
+ /** Switches within the session's scope; the origin's unfinished requests are void. */
479
+ async setCurrentNetwork(origin, network) {
480
+ await this.serial(async () => {
481
+ const store = this.requireStore();
482
+ const session = this.session(origin);
483
+ if (session === void 0 || session.scopes[network] === void 0) throw unauthorized();
484
+ await this.persist(store, {
485
+ ...session,
486
+ currentNetwork: network
487
+ });
488
+ this.options.invalidate(origin);
489
+ });
490
+ }
491
+ /** Switches the session's TRON network; the origin's unfinished requests are void. */
492
+ async setTronNetwork(origin, network) {
493
+ await this.serial(async () => {
494
+ const store = this.requireStore();
495
+ const session = this.session(origin);
496
+ if (session === void 0 || session.scopes[network] === void 0) throw unauthorized();
497
+ await this.persist(store, {
498
+ ...session,
499
+ tronNetwork: network
500
+ });
501
+ this.options.invalidate(origin);
502
+ });
503
+ }
504
+ async touch(origin) {
505
+ await this.serial(async () => {
506
+ const store = this.engineStore;
507
+ const session = this.session(origin);
508
+ const now = this.options.now();
509
+ if (store === void 0 || session === void 0 || now - session.lastUsedAt < TOUCH_INTERVAL_MS) return;
510
+ await this.persist(store, {
511
+ ...session,
512
+ lastUsedAt: now
513
+ });
514
+ });
515
+ }
516
+ /** The active Nostr identity — `undefined` until the host picks one. */
517
+ activeIdentity() {
518
+ return this.identity;
519
+ }
520
+ /** The origin's persisted Nostr policy — `undefined` until it is nostr-authorized. */
521
+ nostrPolicy(origin) {
522
+ return this.session(origin)?.nostrPolicy;
523
+ }
524
+ /** The origin's persisted Lightning policy — `undefined` until it is lightning-authorized. */
525
+ lightningPolicy(origin) {
526
+ return this.session(origin)?.lightningPolicy;
527
+ }
528
+ async bitcoinScope(group, network) {
529
+ return {
530
+ accounts: (await Promise.all(BITCOIN_PURPOSES.map(async (purpose) => this.options.bitcoinAddress(group, network, purpose)))).map((address) => caip10(network, address)),
531
+ methods: BITCOIN_METHODS,
532
+ notifications: ["change"]
533
+ };
534
+ }
535
+ /**
536
+ * The host's Nostr identity selection: the pubkey is derived first, then every session with a
537
+ * non-empty `nostr` scope is re-pointed — `identity` and the scope's account written together —
538
+ * and the origin's unfinished requests voided. No event — NIP-07 has none.
539
+ */
540
+ async setActiveIdentity(ref) {
541
+ await this.serial(async () => {
542
+ const store = this.requireStore();
543
+ let pubkey;
544
+ if (ref !== void 0) pubkey = (await this.options.nostrPubkey(ref)).toLowerCase();
545
+ this.identity = ref;
546
+ for (const session of Object.values(this.getState().sessions)) {
547
+ const scope = session.scopes["nostr"];
548
+ if (scope === void 0 || scope.accounts.length === 0) continue;
549
+ const { identity: _gone, ...rest } = session;
550
+ await this.persist(store, {
551
+ ...rest,
552
+ scopes: {
553
+ ...session.scopes,
554
+ nostr: {
555
+ ...scope,
556
+ accounts: pubkey === void 0 ? [] : [`nostr:${pubkey}`]
557
+ }
558
+ },
559
+ ...ref === void 0 ? {} : { identity: ref }
560
+ });
561
+ this.options.invalidate(session.origin.origin);
562
+ }
563
+ });
564
+ }
565
+ /**
566
+ * Every session write — a re-point, a grant's merge and persist, a revoke, a network switch, a
567
+ * touch — queues here so one writer runs at a time and reads the latest session at its turn. A
568
+ * failed task does not break the chain.
569
+ */
570
+ async serial(task) {
571
+ const previous = this.writeQueue;
572
+ let release;
573
+ this.writeQueue = new Promise((resolve) => {
574
+ release = resolve;
575
+ });
576
+ await previous;
577
+ try {
578
+ return await task();
579
+ } finally {
580
+ release?.();
581
+ }
582
+ }
583
+ async repointQueued() {
584
+ try {
585
+ await this.serial(async () => this.repoint());
586
+ } catch (error) {
587
+ this.options.logger.warn("connection re-point failed", error);
588
+ }
589
+ }
590
+ /**
591
+ * Re-binds every session's chain/lightning scopes to the app's current group selection: each
592
+ * scope's accounts become the target's (empty when the selection is cleared or a derivation
593
+ * fails), `group` written together with them. The origin's unfinished requests are voided.
594
+ */
595
+ async repoint() {
596
+ const store = this.requireStore();
597
+ const target = this.options.selectedGroup();
598
+ for (const session of Object.values(this.getState().sessions)) {
599
+ if (!Object.keys(session.scopes).some(isChainScope) || sameGroup(session.group, target)) continue;
600
+ const scopes = await this.repointScopes(session.scopes, target);
601
+ const { group: _gone, ...rest } = session;
602
+ await this.persist(store, {
603
+ ...rest,
604
+ scopes,
605
+ ...target === void 0 ? {} : { group: target }
606
+ });
607
+ this.options.invalidate(session.origin.origin);
608
+ }
609
+ }
610
+ /**
611
+ * A session's scopes re-computed for `target`: EVM and Solana scope accounts are the group's
612
+ * address, `bip122` its two purpose addresses, `lightning` its `spark:` ref; `nostr` is the
613
+ * identity's and passes through. `target` undefined or a failed derivation → empty accounts.
614
+ */
615
+ async repointScopes(scopes, target) {
616
+ const entries = await Promise.all(Object.entries(scopes).map(async ([network, scope]) => {
617
+ if (network === "nostr") return [network, scope];
618
+ if (target === void 0) return [network, {
619
+ ...scope,
620
+ accounts: []
621
+ }];
622
+ try {
623
+ if (network === "lightning") return [network, {
624
+ ...scope,
625
+ accounts: [`spark:${target.walletId}:${String(target.groupIndex)}`]
626
+ }];
627
+ if (network.startsWith("bip122:")) {
628
+ const bound = await this.bitcoinScope(target, network);
629
+ return [network, {
630
+ ...scope,
631
+ accounts: bound.accounts
632
+ }];
633
+ }
634
+ if (network.startsWith("solana:")) {
635
+ const address = await this.options.solanaAddress(target, network);
636
+ return [network, {
637
+ ...scope,
638
+ accounts: [caip10(network, address)]
639
+ }];
640
+ }
641
+ if (network.startsWith("tron:")) {
642
+ const address = await this.options.tronAddress(target, network);
643
+ return [network, {
644
+ ...scope,
645
+ accounts: [caip10(network, address)]
646
+ }];
647
+ }
648
+ if (network.startsWith("eip155:")) {
649
+ const address = await this.options.evmAddress(target, network);
650
+ return [network, {
651
+ ...scope,
652
+ accounts: [caip10(network, address.toLowerCase())]
653
+ }];
654
+ }
655
+ return [network, scope];
656
+ } catch (error) {
657
+ this.options.logger.warn("connection account unavailable in the new group", error);
658
+ return [network, {
659
+ ...scope,
660
+ accounts: []
661
+ }];
662
+ }
663
+ }));
664
+ return Object.fromEntries(entries);
665
+ }
666
+ /**
667
+ * The scopes a grant produces, bound to the app's selected group (chain/lightning namespaces) or
668
+ * the active identity (`nostr`) — read at write-queue turn, not request time.
669
+ */
670
+ async grantScopes(entry, grant) {
671
+ const scopes = {};
672
+ if (entry.namespace === "nostr") {
673
+ if (grant.nostr === void 0) throw invalidParams("a nostr connection needs the identity's pubkey and policy");
674
+ const identity = this.activeIdentity();
675
+ if (identity === void 0) throw userRejectedRequest("no nostr identity is selected");
676
+ const identityPubkey = (await this.options.nostrPubkey(identity)).toLowerCase();
677
+ if (grant.nostr.pubkey.toLowerCase() !== identityPubkey) throw invalidParams("only the active identity can be granted");
678
+ scopes["nostr"] = {
679
+ accounts: [`nostr:${identityPubkey}`],
680
+ methods: NOSTR_METHODS,
681
+ notifications: []
682
+ };
683
+ return {
684
+ scopes,
685
+ identity
686
+ };
687
+ }
688
+ if (entry.namespace === "lightning") {
689
+ if (grant.lightning === void 0) throw invalidParams("a lightning connection needs the origin's policy");
690
+ const group = this.options.selectedGroup();
691
+ if (group === void 0) throw new Error("no account group is selected");
692
+ scopes["lightning"] = {
693
+ accounts: [`spark:${group.walletId}:${String(group.groupIndex)}`],
694
+ methods: LIGHTNING_METHODS,
695
+ notifications: []
696
+ };
697
+ return {
698
+ scopes,
699
+ group
700
+ };
701
+ }
702
+ const group = this.options.selectedGroup();
703
+ if (group === void 0) throw new Error("no account group is selected");
704
+ if (entry.namespace === "solana") {
705
+ const solanaNetworks = this.options.enabledNetworks().filter((n) => n.startsWith("solana:"));
706
+ const solanaEntries = await Promise.all(solanaNetworks.map(async (network) => {
707
+ const address = await this.options.solanaAddress(group, network);
708
+ return [network, {
709
+ accounts: [caip10(network, address)],
710
+ methods: SOLANA_METHODS,
711
+ notifications: ["change"]
712
+ }];
713
+ }));
714
+ Object.assign(scopes, Object.fromEntries(solanaEntries));
715
+ return {
716
+ scopes,
717
+ group
718
+ };
719
+ }
720
+ if (entry.namespace === "tron") {
721
+ const tronNetworks = this.options.enabledNetworks().filter((n) => n.startsWith("tron:"));
722
+ if (!tronNetworks.includes(grant.network)) throw invalidParams(`${grant.network} is not an enabled TRON network`);
723
+ const tronEntries = await Promise.all(tronNetworks.map(async (network) => {
724
+ const address = await this.options.tronAddress(group, network);
725
+ return [network, {
726
+ accounts: [caip10(network, address)],
727
+ methods: TRON_METHODS,
728
+ notifications: TRON_NOTIFICATIONS
729
+ }];
730
+ }));
731
+ Object.assign(scopes, Object.fromEntries(tronEntries));
732
+ return {
733
+ scopes,
734
+ group,
735
+ tronNetwork: grant.network
736
+ };
737
+ }
738
+ if (entry.namespace === "bip122") {
739
+ const bitcoinNetworks = this.options.enabledNetworks().filter((n) => n.startsWith("bip122:"));
740
+ const bitcoinEntries = await Promise.all(bitcoinNetworks.map(async (network) => [network, await this.bitcoinScope(group, network)]));
741
+ Object.assign(scopes, Object.fromEntries(bitcoinEntries));
742
+ return {
743
+ scopes,
744
+ group
745
+ };
746
+ }
747
+ if (evmChainId(grant.network) === void 0 || !this.options.enabledNetworks().includes(grant.network)) throw invalidParams(`${grant.network} is not an enabled EVM network`);
748
+ const own = (await this.options.evmAddress(group, grant.network)).toLowerCase();
749
+ if (grant.accounts.length === 0 || grant.accounts.some((a) => a.toLowerCase() !== own)) throw invalidParams("only the selected group's account can be granted");
750
+ scopes[grant.network] = {
751
+ accounts: [caip10(grant.network, own)],
752
+ methods: SESSION_METHODS,
753
+ notifications: SESSION_NOTIFICATIONS
754
+ };
755
+ return {
756
+ scopes,
757
+ group
758
+ };
759
+ }
760
+ newSessionId() {
761
+ return `session-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
762
+ }
763
+ dropPending(id) {
764
+ this.expiries.get(id)?.();
765
+ this.expiries.delete(id);
766
+ this.waiters.delete(id);
767
+ this.update((s) => {
768
+ const { [id]: _gone, ...pending } = s.pending;
769
+ return {
770
+ ...s,
771
+ pending
772
+ };
773
+ });
774
+ }
775
+ async persist(store, session) {
776
+ try {
777
+ await store.collection(COLLECTION).put(session.id, new TextEncoder().encode(JSON.stringify(session)));
778
+ } catch (error) {
779
+ throw internalError(error instanceof Error ? error.message : String(error));
780
+ }
781
+ this.update((s) => ({
782
+ ...s,
783
+ sessions: {
784
+ ...s.sessions,
785
+ [session.id]: session
786
+ }
787
+ }));
788
+ }
789
+ requireStore() {
790
+ if (this.engineStore === void 0) throw userRejectedRequest("the wallet is locked");
791
+ return this.engineStore;
792
+ }
793
+ };
794
+ // src/transactions/route.ts
795
+ /** In a block but not final yet: tracked at the finality interval. */
796
+ const awaitingFinality = (tx) => tx.block !== void 0 && tx.final !== true && (tx.state === "confirmed" || tx.state === "failed");
797
+ /**
798
+ * The recheck answer for a transaction already in `tx.block`: `undefined` when state, block and
799
+ * finality are unchanged. Hashes compare lowercase.
800
+ */
801
+ const includedPoll = (tx, state, block, final, error) => tx.state === state && tx.final === final && tx.block?.height === block.height && tx.block.hash?.toLowerCase() === block.hash?.toLowerCase() ? void 0 : {
802
+ kind: "included",
803
+ state,
804
+ block,
805
+ final,
806
+ ...error === void 0 ? {} : { error }
807
+ };
808
+ const hexId = (prefix, random) => `${prefix}-${[...random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
809
+ const newId = (random) => hexId("tx", random);
810
+ /** The account's address; signer-dependent checks fail closed when an account carries none. */
811
+ const accountAddress = (account) => {
812
+ const { address } = account;
813
+ if (typeof address !== "string" || address === "") throw new Error("account carries no address");
814
+ return address;
815
+ };
816
+ const newRequestId = (random) => hexId("req", random);
817
+ /**
818
+ * The chain binding of signed bytes (a TRON reference block, a Solana recent blockhash) is the only
819
+ * thing keeping a transaction off the wrong chain. On a mainnet the binding needs no second source:
820
+ * a binding from another chain makes the signature invalid on the mainnet, so nothing of more value
821
+ * than the user chose can move — the build goes ahead flagged `reads-unverified`. On a testnet the
822
+ * same attack inverts: a binding taken from the mainnet produces a signature valid on the mainnet
823
+ * and moves real value, so a gateway-only testnet build is refused and a host endpoint must be
824
+ * configured.
825
+ */
826
+ const assertGatewayOnlyBinding = (info, binding) => {
827
+ if (info.testnet) throw new ChainError("invalid-request", gatewayOnlyBindingMessage(info, binding));
828
+ };
829
+ /** The refusal {@link assertGatewayOnlyBinding} throws — shared by typed binding errors. */
830
+ const gatewayOnlyBindingMessage = (info, binding) => `only the gateway vouches for the ${binding} on ${info.id}; on a testnet a signature over another network's ${binding} could be valid there — configure a host endpoint in EngineOptions.rpc["${info.id}"]`;
831
+ const TEMPLATE_FAMILY = {
832
+ "evm.bip44": "evm",
833
+ "solana.bip44-change": "solana",
834
+ "tron.bip44": "tron"
835
+ };
836
+ /**
837
+ * The signer address for a send/sign account ref: HD refs derive through the chains proxy; an
838
+ * imported ref resolves its stored address from `wallet.keys` — the ref's family and the key's
839
+ * listed family must both match the network's family or the request is refused.
840
+ */
841
+ const accountAddressOf = async (ctx, account, template, network) => {
842
+ const family = TEMPLATE_FAMILY[template];
843
+ if (account.kind === "imported") {
844
+ if (account.family !== family) throw new ChainError("invalid-request", `an imported ${account.family} key cannot sign on a ${family} network`);
845
+ const key = (await ctx.options.wallet.keys.list()).find((entry) => entry.keyId === account.keyId);
846
+ if (key === void 0) throw new ChainError("invalid-request", "the imported key is not in the vault");
847
+ if (key.family !== family) throw new ChainError("invalid-request", `the imported key is a ${key.family} key, not ${family}`);
848
+ return key.address;
849
+ }
850
+ const apis = ctx.options.chains;
851
+ return accountAddress(await apis.account({
852
+ walletId: account.walletId,
853
+ groupIndex: account.groupIndex,
854
+ template,
855
+ network
856
+ }));
857
+ };
858
+ const LIVE_REPLACEMENT_STATES = /* @__PURE__ */ new Set([
859
+ "draft",
860
+ "signed",
861
+ "submitted",
862
+ "pending"
863
+ ]);
864
+ /**
865
+ * Approval-time check for a replacement: the original must still be unconfirmed and no other
866
+ * replacement of it may already be on its way.
867
+ */
868
+ const replacementStaleReason = (ctx, originalId) => {
869
+ const txs = ctx.txs();
870
+ const original = txs[originalId];
871
+ if (original?.state !== "submitted" && original?.state !== "pending") return "original transaction already finished — nothing to replace";
872
+ return Object.values(txs).some((t) => t.replaces === originalId && LIVE_REPLACEMENT_STATES.has(t.state)) ? "original transaction was already replaced — start over" : void 0;
873
+ };
874
+ const submitTx = async (ctx, tx, hash) => {
875
+ const tracked = await ctx.transition(tx, {
876
+ state: "submitted",
877
+ hash,
878
+ submittedAt: ctx.options.now()
879
+ });
880
+ ctx.track(tracked.id, hash);
881
+ return tracked;
882
+ };
883
+ const failTx = async (ctx, tx, error) => {
884
+ const failed = tx.state === "signed" ? "failed" : "rejected";
885
+ await ctx.transition(tx, {
886
+ state: failed,
887
+ error: errorMessage(error)
888
+ });
889
+ };
890
+ // src/connect/subscription.ts
891
+ /**
892
+ * Fans events derived from session changes out to listeners. The store subscription is created with
893
+ * the first listener and dropped with the last; `derive` may be async (its events are then
894
+ * delivered once it settles).
895
+ */
896
+ var SessionEvents = class {
897
+ listeners = /* @__PURE__ */ new Set();
898
+ unsubscribe;
899
+ connections;
900
+ derive;
901
+ constructor(connections, derive) {
902
+ this.connections = connections;
903
+ this.derive = derive;
904
+ }
905
+ subscribe(listener) {
906
+ this.listeners.add(listener);
907
+ if (this.unsubscribe === void 0) {
908
+ let previous = this.connections.getState().sessions;
909
+ this.unsubscribe = this.connections.store.subscribe((state) => {
910
+ const events = this.derive(previous, state.sessions);
911
+ previous = state.sessions;
912
+ if (Array.isArray(events)) this.emit(events);
913
+ else (async () => {
914
+ this.emit(await events);
915
+ })();
916
+ });
917
+ }
918
+ return () => {
919
+ this.listeners.delete(listener);
920
+ if (this.listeners.size === 0) {
921
+ this.unsubscribe?.();
922
+ this.unsubscribe = void 0;
923
+ }
924
+ };
925
+ }
926
+ emit(events) {
927
+ for (const event of events) for (const listener of this.listeners) listener(event);
928
+ }
929
+ };
930
+ // src/transactions/broadcast.ts
931
+ /**
932
+ * Broadcast with an outcome that is never guessed. The signed bytes and their locally computed id
933
+ * are persisted, and what the transaction consumes (nonce, inputs) is held, before anything leaves;
934
+ * a failed send then fails the transaction only when the node itself refuses those bytes — and that
935
+ * refusal is persisted durably, so bytes the user was told failed are never broadcast again. Any
936
+ * other failure — transport error, 5xx, timeout, an endpoint naming another id — may have reached
937
+ * the mempool, so the transaction stays `submitted` and the tracker resolves it by id.
938
+ */
939
+ /**
940
+ * How long the network may not know a transaction before its row turns `stuck` — never terminal:
941
+ * the bytes may still land, so the nonce or inputs stay held and the poll drops to the finality
942
+ * interval until a chain answer resolves it.
943
+ */
944
+ const STUCK_AFTER_MS = 18e5;
945
+ /** The note a stuck row carries; its remedies are speed-up and cancel. */
946
+ const STUCK_NOTE = "the network has not seen this transaction for 30 minutes — speed up or cancel it";
947
+ /** Rebroadcast backoff for a transaction the node does not know: base doubling up to the cap. */
948
+ const RESUBMIT_BASE_MS = 15e3;
949
+ const RESUBMIT_MAX_MS = 6e5;
950
+ const broadcastOutcome = async (attempt) => {
951
+ let reported;
952
+ try {
953
+ reported = await attempt.send();
954
+ } catch (error) {
955
+ const verdict = attempt.verdict(error);
956
+ if (verdict === "held") return { kind: "accepted" };
957
+ if (verdict === void 0) return {
958
+ kind: "unknown",
959
+ error
960
+ };
961
+ let known;
962
+ try {
963
+ known = await attempt.known();
964
+ } catch {
965
+ return {
966
+ kind: "unknown",
967
+ error
968
+ };
969
+ }
970
+ return known ? { kind: "accepted" } : {
971
+ kind: "refused",
972
+ error
973
+ };
974
+ }
975
+ return reported === attempt.id ? { kind: "accepted" } : {
976
+ kind: "unknown",
977
+ error: /* @__PURE__ */ new Error(`the endpoint reported ${reported} for ${attempt.id}`)
978
+ };
979
+ };
980
+ /**
981
+ * The node refused the signed bytes it was shown: nothing went out, so the request may fail. Every
982
+ * other error `submitSigned` can raise happens before the broadcast.
983
+ */
984
+ var BroadcastRefusedError = class extends Error {
985
+ constructor(nodeError) {
986
+ super(errorMessage(nodeError), { cause: nodeError });
987
+ this.name = "BroadcastRefusedError";
988
+ }
989
+ };
990
+ /**
991
+ * Submits `count` signed transactions in order; stops at the first that does not go out — a later
992
+ * one may depend on it, so it is never sent, and each is persisted by its own `submitSigned` just
993
+ * before its own send so an unsent later item is never rebroadcast after a restart. Throws that
994
+ * error when the first one does not go out (nothing was sent).
995
+ */
996
+ const submitInOrder = async (count, submit) => {
997
+ const ids = [];
998
+ for (let index = 0; index < count; index += 1) try {
999
+ ids.push(await submit(index));
1000
+ } catch (error) {
1001
+ if (index === 0) throw error;
1002
+ return {
1003
+ ids,
1004
+ stopped: {
1005
+ index,
1006
+ reason: error instanceof BroadcastRefusedError ? "refused" : "not-sent",
1007
+ error: errorMessage(error)
1008
+ }
1009
+ };
1010
+ }
1011
+ return { ids };
1012
+ };
1013
+ /**
1014
+ * Persists the signed bytes and id on `tx` — throwing, with nothing sent, when the vault locked
1015
+ * first — holds what it consumes, then broadcasts. Accepted or unknown → `submitted` and tracked;
1016
+ * refused → released, `failed` is written durably so the refused bytes can never be recovered as
1017
+ * `signed` later — a `signed` row the failed write lost would resurrect them — and a
1018
+ * `BroadcastRefusedError` is thrown. A locked vault or failed write cannot block the refusal: the
1019
+ * terminal row then lands through the bookkeeping retry like any other. The refusal is the only
1020
+ * error allowed out once the send was attempted: anything else happens before bytes leave.
1021
+ */
1022
+ const submitSigned = async (ctx, tx, signed) => {
1023
+ let persisted;
1024
+ try {
1025
+ persisted = await ctx.transition(tx, {
1026
+ ...signed.record,
1027
+ hash: signed.id,
1028
+ raw: signed.raw
1029
+ }, true);
1030
+ } catch (error) {
1031
+ signed.release();
1032
+ throw error;
1033
+ }
1034
+ signed.hold();
1035
+ const outcome = await broadcastOutcome(signed);
1036
+ if (outcome.kind === "refused") {
1037
+ signed.release();
1038
+ const failed = {
1039
+ state: "failed",
1040
+ hash: void 0,
1041
+ raw: void 0,
1042
+ error: errorMessage(outcome.error)
1043
+ };
1044
+ try {
1045
+ await ctx.transition(persisted, failed, true);
1046
+ } catch {
1047
+ await ctx.transition(persisted, failed);
1048
+ }
1049
+ throw new BroadcastRefusedError(outcome.error);
1050
+ }
1051
+ if (outcome.kind === "unknown") ctx.options.logger.warn(`transaction ${tx.id}: broadcast outcome unknown, tracking ${signed.id}`, outcome.error);
1052
+ return submitTx(ctx, persisted, signed.id);
1053
+ };
1054
+ // src/connect/text.ts
1055
+ /** What a handler answers with (`4200`) for sign-message bytes that are not UTF-8 text. */
1056
+ const BLIND_SIGNING_MESSAGE = "blind signing is not enabled: the message is not UTF-8 text";
1057
+ const decoder = new TextDecoder("utf-8", {
1058
+ fatal: true,
1059
+ ignoreBOM: true
1060
+ });
1061
+ /** The bytes as UTF-8 text, or `undefined` when they are not valid UTF-8. */
1062
+ function utf8Text(bytes) {
1063
+ try {
1064
+ return decoder.decode(bytes);
1065
+ } catch {
1066
+ return;
1067
+ }
1068
+ }
1069
+ // src/connect/bitcoin.ts
1070
+ const bitcoinId = (name) => {
1071
+ const entry = BITCOIN_NETWORKS.find((n) => n.name === name);
1072
+ if (entry === void 0) throw new Error(`no bitcoin network named ${name} in the registry`);
1073
+ return entry.id;
1074
+ };
1075
+ /**
1076
+ * The Bitcoin Wallet Standard chain ids to the registry's CAIP-2 ids: `bitcoin:testnet` is the
1077
+ * registry's default test network (Testnet4 — the registry has no Testnet3).
1078
+ */
1079
+ const BITCOIN_CHAIN_IDS = Object.freeze({
1080
+ "bitcoin:mainnet": bitcoinId("Bitcoin"),
1081
+ "bitcoin:testnet": bitcoinId("Bitcoin Testnet4")
1082
+ });
1083
+ /** The Wallet Standard chain id of a registry network, or `undefined` when it has none. */
1084
+ const bitcoinStandardChain = (network) => Object.entries(BITCOIN_CHAIN_IDS).find(([, id]) => id === network)?.[0];
1085
+ /** The kernel tags a BIP-322 simple signature `smp` + base64 of the witness. */
1086
+ const SIMPLE_PREFIX = "smp";
1087
+ const TEMPLATES = {
1088
+ payment: "btc.bip84",
1089
+ ordinals: "btc.bip86"
1090
+ };
1091
+ /**
1092
+ * The Bitcoin Wallet Standard handler: `bitcoin:connect` authorizes the `bip122` scope (both the
1093
+ * `payment` and the `ordinals` account) and returns the requested purposes in order;
1094
+ * `bitcoin:signMessage` goes through `bitcoin-sign` (BIP-322 simple); `bitcoinAccountsChanged`
1095
+ * carries the re-pointed accounts the bridge forwards as `bitcoin:events` `change` on a group
1096
+ * switch.
1097
+ */
1098
+ var BitcoinWalletHandler = class {
1099
+ options;
1100
+ events;
1101
+ constructor(options) {
1102
+ this.options = options;
1103
+ this.events = new SessionEvents(options.connections, async (before, after) => Promise.all(diffSessions$2(before, after).map(async ({ origin, session }) => ({
1104
+ name: "bitcoinAccountsChanged",
1105
+ origin,
1106
+ accounts: await this.sessionAccountsChanged(session)
1107
+ }))));
1108
+ }
1109
+ subscribe(listener) {
1110
+ return this.events.subscribe(listener);
1111
+ }
1112
+ async handle(origin, request) {
1113
+ const caller = this.options.connections.checkOrigin(origin);
1114
+ if (request.method === "bitcoin:connect") return this.connect(caller, request);
1115
+ if (request.method === "standard:disconnect") {
1116
+ await this.options.connections.revoke(caller.origin);
1117
+ return {};
1118
+ }
1119
+ if (request.method === "bitcoin:signMessage") return this.signMessage(caller, request);
1120
+ if (request.method === "bitcoin:signTransaction") return this.signTransactions(caller, request, false);
1121
+ if (request.method === "bitcoin:signAndSendTransaction") return this.signTransactions(caller, request, true);
1122
+ throw invalidParams(`unsupported bitcoin method ${request.method}`);
1123
+ }
1124
+ async connect(caller, request) {
1125
+ const purposes = purposesOf(request.params);
1126
+ const network = request.network ?? this.options.bitcoinNetwork();
1127
+ let binding = this.options.connections.sessionAccounts(caller.origin, network);
1128
+ await (binding === void 0 ? this.options.connections.request(caller.origin, {
1129
+ kind: "connect",
1130
+ namespace: "bip122"
1131
+ }) : this.options.connections.touch(caller.origin));
1132
+ binding = this.options.connections.sessionAccounts(caller.origin, network);
1133
+ if (binding === void 0) throw new ProviderError(4100, "the wallet is not connected");
1134
+ const { group } = binding;
1135
+ return { accounts: await Promise.all(purposes.map(async (purpose) => {
1136
+ const account = await this.walletAccount(group, network, purpose);
1137
+ if (account.address !== binding.addresses[BITCOIN_PURPOSES.indexOf(purpose)]) throw new ProviderError(-32603, "the session's account does not derive for its group");
1138
+ return account;
1139
+ })) };
1140
+ }
1141
+ async walletAccount(group, network, purpose) {
1142
+ const chain = bitcoinStandardChain(network);
1143
+ if (chain === void 0) throw new ProviderError(-32603, `network ${network} has no Wallet Standard chain id`);
1144
+ const account = await this.options.bitcoinAccount(group, network, purpose);
1145
+ return {
1146
+ address: account.address,
1147
+ publicKey: account.publicKey,
1148
+ chains: [chain],
1149
+ features: BITCOIN_METHODS.filter((m) => m.startsWith("bitcoin:"))
1150
+ };
1151
+ }
1152
+ /**
1153
+ * Signs `message` (UTF-8 text only — `bitcoin.message` takes text, so there is no blind path) for
1154
+ * one of the session's accounts. The signature is the BIP-322 simple witness serialization
1155
+ * (witness item count, then each item length-prefixed) — the kernel's `smp` + base64 string
1156
+ * decoded to bytes, which is what MetaMask's Bitcoin Wallet Standard wallet hands out.
1157
+ */
1158
+ async signMessage(caller, request) {
1159
+ const network = request.network ?? this.options.bitcoinNetwork();
1160
+ this.options.connections.authorize(caller.origin, network, "bitcoin:signMessage");
1161
+ const binding = this.options.connections.sessionAccounts(caller.origin, network);
1162
+ if (binding === void 0) throw new ProviderError(4100, "no bitcoin account for this origin");
1163
+ const { address, message } = signMessageParams(request.params);
1164
+ const purpose = BITCOIN_PURPOSES.find((p) => binding.addresses[BITCOIN_PURPOSES.indexOf(p)] === address);
1165
+ if (purpose === void 0) throw new ProviderError(4100, "account is not a connected account");
1166
+ const text = utf8Text(message);
1167
+ if (text === void 0) throw new ProviderError(4200, BLIND_SIGNING_MESSAGE);
1168
+ const account = {
1169
+ ...binding.group,
1170
+ address,
1171
+ template: TEMPLATES[purpose]
1172
+ };
1173
+ let outcome;
1174
+ try {
1175
+ const pending = await this.options.requests.prepare({
1176
+ method: "bitcoin-sign",
1177
+ origin: caller,
1178
+ account,
1179
+ network,
1180
+ request: {
1181
+ kind: "message",
1182
+ message: text
1183
+ }
1184
+ });
1185
+ outcome = await this.options.requests.outcome(pending.id);
1186
+ } catch (error) {
1187
+ throw toProviderError$1(error);
1188
+ }
1189
+ if (!("kind" in outcome) || outcome.kind !== "bitcoin.message") throw new ProviderError(-32603, "the bitcoin-sign request settled unexpectedly");
1190
+ if (!outcome.signature.startsWith(SIMPLE_PREFIX)) throw new ProviderError(-32603, "the kernel returned an unrecognized signature encoding");
1191
+ return {
1192
+ signedMessage: message,
1193
+ signature: base64.decode(outcome.signature.slice(3))
1194
+ };
1195
+ }
1196
+ /**
1197
+ * Signs (and with `send` broadcasts) a batch of dApp PSBTs under one approval. Every account
1198
+ * named must be a session account — inputs of both purposes may mix in one PSBT, each sign entry
1199
+ * carries its account's template — and `chain`, when given, must be the session's network.
1200
+ */
1201
+ async signTransactions(caller, request, send) {
1202
+ const network = request.network ?? this.options.bitcoinNetwork();
1203
+ this.options.connections.authorize(caller.origin, network, request.method);
1204
+ const binding = this.options.connections.sessionAccounts(caller.origin, network);
1205
+ if (binding === void 0) throw new ProviderError(4100, "no bitcoin account for this origin");
1206
+ const inputs = transactionInputs(request.params);
1207
+ if (send && inputs.some((input) => input.chain === void 0)) throw invalidParams("chain is required for bitcoin:signAndSendTransaction");
1208
+ if (inputs.some((input) => input.chain !== void 0 && BITCOIN_CHAIN_IDS[input.chain] !== network)) throw invalidParams("chain is not the connected network");
1209
+ const templateOf = (address) => {
1210
+ const purpose = BITCOIN_PURPOSES.find((p) => binding.addresses[BITCOIN_PURPOSES.indexOf(p)] === address);
1211
+ if (purpose === void 0) throw new ProviderError(4100, "account is not a connected account");
1212
+ return TEMPLATES[purpose];
1213
+ };
1214
+ let outcome;
1215
+ try {
1216
+ const pending = await this.options.requests.prepare({
1217
+ method: "bitcoin-sign",
1218
+ origin: caller,
1219
+ account: binding.group,
1220
+ network,
1221
+ request: {
1222
+ kind: "psbt",
1223
+ psbts: inputs.map(({ psbt, inputsToSign }) => ({
1224
+ psbt,
1225
+ sign: inputsToSign.flatMap(({ address, signingIndexes, sigHash }) => signingIndexes.map((index) => ({
1226
+ index,
1227
+ sigHash,
1228
+ template: templateOf(address)
1229
+ })))
1230
+ })),
1231
+ send
1232
+ }
1233
+ });
1234
+ outcome = await this.options.requests.outcome(pending.id);
1235
+ } catch (error) {
1236
+ throw toProviderError$1(error);
1237
+ }
1238
+ if (!("kind" in outcome) || outcome.kind !== "bitcoin.psbts") throw new ProviderError(-32603, "the bitcoin-sign request settled unexpectedly");
1239
+ if (send && outcome.stopped !== void 0) throw batchStopped(outcome.stopped, outcome.txids);
1240
+ return send ? outcome.txids.map((txId, index) => {
1241
+ const signedPsbt = outcome.signedPsbts[index];
1242
+ if (signedPsbt === void 0) throw internalError("a broadcast transaction has no signed PSBT");
1243
+ return {
1244
+ txId,
1245
+ signedPsbt
1246
+ };
1247
+ }) : outcome.signedPsbts.map((signedPsbt) => ({ signedPsbt }));
1248
+ }
1249
+ /**
1250
+ * A `change` event's accounts, derived only from the session after the write: the binding's
1251
+ * `payment` and `ordinals` accounts — empty when the session is gone or none are bound.
1252
+ */
1253
+ async sessionAccountsChanged(session) {
1254
+ const network = this.options.bitcoinNetwork();
1255
+ const binding = sessionAccounts(session, network);
1256
+ if (binding === void 0) return [];
1257
+ try {
1258
+ return (await Promise.all(BITCOIN_PURPOSES.map(async (purpose, index) => {
1259
+ const account = await this.walletAccount(binding.group, network, purpose);
1260
+ return account.address === binding.addresses[index] ? account : void 0;
1261
+ }))).filter((account) => account !== void 0);
1262
+ } catch {
1263
+ return [];
1264
+ }
1265
+ }
1266
+ };
1267
+ const isBytesEnvelope$2 = (v) => typeof v === "object" && v !== null && typeof v.__bytes === "string";
1268
+ const purposesOf = (params) => {
1269
+ const raw = typeof params === "object" && params !== null ? params.purposes : void 0;
1270
+ if (!Array.isArray(raw) || raw.length === 0) throw invalidParams("bitcoin:connect needs a non-empty purposes array");
1271
+ return raw.map((purpose) => {
1272
+ const found = BITCOIN_PURPOSES.find((p) => p === purpose);
1273
+ if (found === void 0) throw invalidParams("unknown purpose");
1274
+ return found;
1275
+ });
1276
+ };
1277
+ const signMessageParams = (params) => {
1278
+ const { account, message } = typeof params === "object" && params !== null ? params : {};
1279
+ if (typeof account !== "string") throw invalidParams("bitcoin:signMessage needs the account address");
1280
+ if (message instanceof Uint8Array) return {
1281
+ address: account,
1282
+ message
1283
+ };
1284
+ if (isBytesEnvelope$2(message) && /^(?:[0-9a-fA-F]{2})*$/.test(message.__bytes)) return {
1285
+ address: account,
1286
+ message: hexToBytes(message.__bytes)
1287
+ };
1288
+ throw invalidParams("bitcoin:signMessage needs Uint8Array message bytes");
1289
+ };
1290
+ const bytesOf$1 = (value) => {
1291
+ if (value instanceof Uint8Array) return value;
1292
+ return isBytesEnvelope$2(value) && /^(?:[0-9a-fA-F]{2})*$/.test(value.__bytes) ? hexToBytes(value.__bytes) : void 0;
1293
+ };
1294
+ const sigHashOf = (value) => {
1295
+ if (value === void 0 || value === "ALL") return "ALL";
1296
+ if (value === "SINGLE|ANYONECANPAY") return value;
1297
+ throw invalidParams("sigHash must be ALL or SINGLE|ANYONECANPAY");
1298
+ };
1299
+ /** The wire shape of `bitcoin:signTransaction` inputs: accounts arrive as their addresses. */
1300
+ const transactionInputs = (params) => {
1301
+ const raw = typeof params === "object" && params !== null ? params.inputs : void 0;
1302
+ if (!Array.isArray(raw) || raw.length === 0) throw invalidParams("a bitcoin transaction call needs a non-empty inputs array");
1303
+ return raw.map((entry) => {
1304
+ const { psbt, chain, inputsToSign } = typeof entry === "object" && entry !== null ? entry : {};
1305
+ const bytes = bytesOf$1(psbt);
1306
+ if (bytes === void 0 || !Array.isArray(inputsToSign) || inputsToSign.length === 0) throw invalidParams("each input needs psbt bytes and inputsToSign");
1307
+ if (chain !== void 0 && typeof chain !== "string") throw invalidParams("chain must be a string");
1308
+ return {
1309
+ psbt: bytes,
1310
+ chain,
1311
+ inputsToSign: inputsToSign.map((item) => {
1312
+ const { address, signingIndexes, sigHash } = typeof item === "object" && item !== null ? item : {};
1313
+ if (typeof address !== "string" || !Array.isArray(signingIndexes) || signingIndexes.length === 0 || !signingIndexes.every((i) => Number.isSafeInteger(i) && i >= 0)) throw invalidParams("inputsToSign needs an account and signing indexes");
1314
+ return {
1315
+ address,
1316
+ signingIndexes: signingIndexes.map(Number),
1317
+ sigHash: sigHashOf(sigHash)
1318
+ };
1319
+ })
1320
+ };
1321
+ });
1322
+ };
1323
+ const byOrigin$2 = (sessions) => new Map(Object.values(sessions).map((s) => [s.origin.origin, s]));
1324
+ const bitcoinAccountList = (session) => Object.entries(session.scopes).filter(([network]) => network.startsWith("bip122:")).flatMap(([, scope]) => scope.accounts.map((a) => a.slice(a.lastIndexOf(":") + 1)));
1325
+ /**
1326
+ * The origins whose `bip122` scope's accounts changed between the two snapshots, each with the
1327
+ * session after the write (`undefined` when the session is gone).
1328
+ */
1329
+ function diffSessions$2(before, after) {
1330
+ const events = [];
1331
+ const prev = byOrigin$2(before);
1332
+ const next = byOrigin$2(after);
1333
+ for (const [origin, session] of prev) {
1334
+ const now = next.get(origin);
1335
+ if (bitcoinAccountList(session).join(",") !== (now === void 0 ? "" : bitcoinAccountList(now).join(","))) events.push({
1336
+ origin,
1337
+ session: now
1338
+ });
1339
+ }
1340
+ for (const [origin, session] of next) if (!prev.has(origin) && bitcoinAccountList(session).length > 0) events.push({
1341
+ origin,
1342
+ session
1343
+ });
1344
+ return events;
1345
+ }
1346
+ // src/connect/nip07.ts
1347
+ /**
1348
+ * `signEvent` of these kinds always asks for explicit confirmation, whatever the policy allows:
1349
+ * metadata/contact-list/deletion plus every replaceable, ephemeral and addressable event —
1350
+ * ephemeral events are by convention authentication and remote-control messages, not content.
1351
+ */
1352
+ const forcesConfirmation = (kind) => kind === 0 || kind === 3 || kind === 5 || kind >= 1e4 && kind < 4e4;
1353
+ const MAX_TAGS = 64;
1354
+ const MAX_TAG_ITEMS = 32;
1355
+ const MAX_TAG_ITEM_LENGTH = 1024;
1356
+ const MAX_CONTENT_LENGTH = 131072;
1357
+ const isObject$2 = (v) => typeof v === "object" && v !== null;
1358
+ /**
1359
+ * Strict event validation: `kind` is an integer 0–65535, `created_at` a safe integer, `tags` a
1360
+ * bounded `string[][]`, `content` a bounded string and `pubkey` — when present — a string.
1361
+ */
1362
+ function checkEvent(value) {
1363
+ if (!isObject$2(value)) throw invalidParams("event is not an object");
1364
+ const { kind, content, pubkey, tags, created_at: createdAt } = value;
1365
+ if (typeof kind !== "number" || !Number.isSafeInteger(kind) || kind < 0 || kind > 65535) throw invalidParams("event.kind must be an integer 0–65535");
1366
+ if (typeof content !== "string" || content.length > MAX_CONTENT_LENGTH) throw invalidParams("event.content must be a string");
1367
+ if (pubkey !== void 0 && typeof pubkey !== "string") throw invalidParams("event.pubkey must be a string");
1368
+ if (typeof createdAt !== "number" || !Number.isSafeInteger(createdAt)) throw invalidParams("event.created_at must be a safe integer");
1369
+ if (!Array.isArray(tags) || tags.length > MAX_TAGS) throw invalidParams("event.tags must be a bounded array of string arrays");
1370
+ const checkedTags = [];
1371
+ for (const tag of tags) {
1372
+ if (!Array.isArray(tag) || tag.length > MAX_TAG_ITEMS) throw invalidParams("event.tags items must be bounded string arrays");
1373
+ const checkedTag = [];
1374
+ for (const item of tag) {
1375
+ if (typeof item !== "string" || item.length > MAX_TAG_ITEM_LENGTH) throw invalidParams("event.tags items must contain bounded strings");
1376
+ checkedTag.push(item);
1377
+ }
1378
+ checkedTags.push(checkedTag);
1379
+ }
1380
+ return {
1381
+ kind,
1382
+ content,
1383
+ created_at: createdAt,
1384
+ tags: checkedTags,
1385
+ ...pubkey === void 0 ? {} : { pubkey }
1386
+ };
1387
+ }
1388
+ /** NIP-04/NIP-44 encrypt/decrypt take `[peerPubkey, text]`. */
1389
+ function peerText(params) {
1390
+ if (!Array.isArray(params) || typeof params[0] !== "string" || typeof params[1] !== "string") throw invalidParams("expected [peerPubkey, text]");
1391
+ return {
1392
+ peer: params[0],
1393
+ text: params[1]
1394
+ };
1395
+ }
1396
+ var Nip07Handler = class {
1397
+ options;
1398
+ constructor(options) {
1399
+ this.options = options;
1400
+ }
1401
+ async handle(origin, request) {
1402
+ const { connections } = this.options;
1403
+ connections.checkOrigin(origin);
1404
+ switch (request.method) {
1405
+ case "getPublicKey": return this.publicKey(origin);
1406
+ case "signEvent": return this.signEvent(origin, request.params);
1407
+ case "nip04.encrypt":
1408
+ case "nip04.decrypt":
1409
+ case "nip44.encrypt":
1410
+ case "nip44.decrypt": {
1411
+ connections.authorize(origin, "nostr", request.method);
1412
+ const { peer, text } = peerText(request.params);
1413
+ return this.crypt(origin, request.method, peer, text);
1414
+ }
1415
+ default: throw unauthorized();
1416
+ }
1417
+ }
1418
+ /** The session's bound identity pubkey — a `nostr` connection approval when none yet. */
1419
+ async publicKey(origin) {
1420
+ const { connections } = this.options;
1421
+ if (connections.nostrIdentity(origin) === void 0) await connections.request(origin, {
1422
+ kind: "connect",
1423
+ namespace: "nostr"
1424
+ });
1425
+ await connections.touch(origin);
1426
+ const granted = connections.nostrIdentity(origin);
1427
+ if (granted === void 0) throw unauthorized();
1428
+ return granted.pubkey;
1429
+ }
1430
+ async signEvent(origin, params) {
1431
+ const { connections, requests, signerFor } = this.options;
1432
+ const session = connections.authorize(origin, "nostr", "signEvent");
1433
+ const bound = connections.nostrIdentity(origin);
1434
+ if (bound === void 0) throw unauthorized();
1435
+ const { pubkey } = bound;
1436
+ const event = checkEvent(Array.isArray(params) ? params[0] : params);
1437
+ if (event.pubkey !== void 0 && event.pubkey !== pubkey) throw invalidParams("event.pubkey does not match the connected identity");
1438
+ const policy = session.nostrPolicy ?? {
1439
+ signing: "ask",
1440
+ decrypt: false
1441
+ };
1442
+ const direct = policy.signing === "always" || typeof policy.signing === "object" && policy.signing.kinds.includes(event.kind);
1443
+ const signing = {
1444
+ ...event,
1445
+ pubkey
1446
+ };
1447
+ if (direct && !forcesConfirmation(event.kind)) {
1448
+ await connections.touch(origin);
1449
+ return signerFor(bound.ref).signEvent(signing);
1450
+ }
1451
+ const pending = await requests.prepare({
1452
+ method: "nostr-sign",
1453
+ origin: {
1454
+ kind: "browser",
1455
+ origin
1456
+ },
1457
+ ref: bound.ref,
1458
+ event: signing
1459
+ });
1460
+ const outcome = await requests.outcome(pending.id);
1461
+ if (outcome === void 0 || !("event" in outcome)) throw unauthorized();
1462
+ return outcome.event;
1463
+ }
1464
+ async crypt(origin, method, peer, text) {
1465
+ const { connections, signerFor } = this.options;
1466
+ if (method.endsWith(".decrypt") && connections.nostrPolicy(origin)?.decrypt !== true) throw unauthorized();
1467
+ const bound = connections.nostrIdentity(origin);
1468
+ if (bound === void 0) throw unauthorized();
1469
+ await connections.touch(origin);
1470
+ const signer = signerFor(bound.ref);
1471
+ const fn = method === "nip04.encrypt" ? signer.nip04Encrypt : method === "nip04.decrypt" ? signer.nip04Decrypt : method === "nip44.encrypt" ? signer.nip44Encrypt : signer.nip44Decrypt;
1472
+ if (fn === void 0) throw unauthorized();
1473
+ return fn(peer, text);
1474
+ }
1475
+ };
1476
+ // src/connect/siws.ts
1477
+ const STATEMENT_MAX = 1024;
1478
+ const FIELD_MAX = 256;
1479
+ const RESOURCES_MAX = 32;
1480
+ const STRING_FIELDS = [
1481
+ "domain",
1482
+ "address",
1483
+ "statement",
1484
+ "uri",
1485
+ "version",
1486
+ "chainId",
1487
+ "nonce",
1488
+ "issuedAt",
1489
+ "expirationTime",
1490
+ "notBefore",
1491
+ "requestId"
1492
+ ];
1493
+ const checkString$1 = (name, value, max) => {
1494
+ if (typeof value !== "string") throw invalidParams(`${name} must be a string`);
1495
+ if (value.includes("\n") || value.includes("\r")) throw invalidParams(`${name} must not contain line breaks`);
1496
+ if (value.length > max) throw invalidParams(`${name} is longer than ${String(max)} characters`);
1497
+ return value;
1498
+ };
1499
+ /** Validates a dApp's sign-in input: types, no line breaks, length caps. */
1500
+ function checkSignInInput(raw) {
1501
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw invalidParams("the sign-in input must be an object");
1502
+ const record = new Map(Object.entries(raw));
1503
+ const out = {};
1504
+ for (const name of STRING_FIELDS) {
1505
+ const value = record.get(name);
1506
+ if (value !== void 0) out[name] = checkString$1(name, value, name === "statement" ? STATEMENT_MAX : FIELD_MAX);
1507
+ }
1508
+ const resources = record.get("resources");
1509
+ if (resources !== void 0) {
1510
+ if (!Array.isArray(resources) || resources.length > RESOURCES_MAX) throw invalidParams(`resources must be an array of at most ${String(RESOURCES_MAX)} strings`);
1511
+ out["resources"] = resources.map((resource) => checkString$1("resources", resource, FIELD_MAX));
1512
+ }
1513
+ return out;
1514
+ }
1515
+ /**
1516
+ * The EIP-4361-style message, byte for byte `createSignInMessageText` of
1517
+ * `@solana/wallet-standard-util` 1.2.0 (an empty `resources` array still prints `Resources:`).
1518
+ */
1519
+ function signInMessageText(input) {
1520
+ let message = `${input.domain} wants you to sign in with your Solana account:\n${input.address}`;
1521
+ if (input.statement !== void 0 && input.statement !== "") message += `\n\n${input.statement}`;
1522
+ const fields = [];
1523
+ const optional = [
1524
+ ["URI", input.uri],
1525
+ ["Version", input.version],
1526
+ ["Chain ID", input.chainId],
1527
+ ["Nonce", input.nonce],
1528
+ ["Issued At", input.issuedAt],
1529
+ ["Expiration Time", input.expirationTime],
1530
+ ["Not Before", input.notBefore],
1531
+ ["Request ID", input.requestId]
1532
+ ];
1533
+ for (const [label, value] of optional) if (value !== void 0 && value !== "") fields.push(`${label}: ${value}`);
1534
+ if (input.resources !== void 0) {
1535
+ fields.push("Resources:");
1536
+ for (const resource of input.resources) fields.push(`- ${resource}`);
1537
+ }
1538
+ if (fields.length > 0) message += `\n\n${fields.join("\n")}`;
1539
+ return message;
1540
+ }
1541
+ // src/connect/solana.ts
1542
+ const solanaId = (name) => {
1543
+ const entry = SOLANA_NETWORKS.find((n) => n.name === name);
1544
+ if (entry === void 0) throw new Error(`no solana network named ${name} in the registry`);
1545
+ return entry.id;
1546
+ };
1547
+ /**
1548
+ * The Wallet Standard short chain ids to the registry's CAIP-2 genesis-hash ids, derived from the
1549
+ * solana network registry by name.
1550
+ */
1551
+ const SOLANA_CHAIN_IDS = Object.freeze({
1552
+ "solana:mainnet": solanaId("Solana"),
1553
+ "solana:devnet": solanaId("Solana Devnet")
1554
+ });
1555
+ /** The Wallet Standard short id of a registry network, or `undefined` when it has none. */
1556
+ const walletStandardChain = (network) => Object.entries(SOLANA_CHAIN_IDS).find(([, id]) => id === network)?.[0];
1557
+ /**
1558
+ * The Wallet Standard handler: `standard:connect` authorizes the `solana` scope, `solana:*` sign
1559
+ * requests go through `solana-sign`, `solanaAccountsChanged` returns the re-pointed accounts the
1560
+ * bridge forwards as `standard:events` `change` on a group switch.
1561
+ */
1562
+ var SolanaWalletHandler = class {
1563
+ options;
1564
+ events;
1565
+ constructor(options) {
1566
+ this.options = options;
1567
+ this.events = new SessionEvents(options.connections, async (before, after) => Promise.all(diffSessions$1(before, after).map(async ({ origin, session }) => ({
1568
+ name: "solanaAccountsChanged",
1569
+ origin,
1570
+ accounts: await this.sessionAccountsChanged(session)
1571
+ }))));
1572
+ }
1573
+ /** `standard:events` `change` per origin — derived from changes to the sessions. */
1574
+ subscribe(listener) {
1575
+ return this.events.subscribe(listener);
1576
+ }
1577
+ async handle(origin, request) {
1578
+ const caller = this.options.connections.checkOrigin(origin);
1579
+ if (request.method === "standard:connect") return this.connect(caller, request);
1580
+ if (request.method === "standard:disconnect") {
1581
+ await this.options.connections.revoke(caller.origin);
1582
+ return {};
1583
+ }
1584
+ if (request.method === "solana:signTransaction") return this.signTransactions(caller, request, false);
1585
+ if (request.method === "solana:signAndSendTransaction") return this.signTransactions(caller, request, true);
1586
+ if (request.method === "solana:signMessage") return this.signMessage(caller, request);
1587
+ if (request.method === "solana:signIn") return this.signIn(caller, request);
1588
+ throw invalidParams(`unsupported solana method ${request.method}`);
1589
+ }
1590
+ async connect(caller, request) {
1591
+ const silent = (typeof request.params === "object" && request.params !== null ? request.params : {}).silent === true;
1592
+ const network = request.network ?? this.options.solanaNetwork();
1593
+ let binding = this.options.connections.sessionAccounts(caller.origin, network);
1594
+ if (binding === void 0) {
1595
+ if (silent) throw new ProviderError(4100, "the wallet is not connected");
1596
+ await this.options.connections.request(caller.origin, {
1597
+ kind: "connect",
1598
+ namespace: "solana"
1599
+ });
1600
+ binding = this.options.connections.sessionAccounts(caller.origin, network);
1601
+ if (binding === void 0) throw new ProviderError(4100, "the wallet is not connected");
1602
+ } else await this.options.connections.touch(caller.origin);
1603
+ const account = await this.options.solanaAccount(binding.group, network);
1604
+ if (account.address !== binding.addresses[0]) throw new ProviderError(-32603, "the session's account does not derive for its group");
1605
+ return { accounts: [this.walletAccount(account, network)] };
1606
+ }
1607
+ walletAccount(account, network) {
1608
+ const chain = walletStandardChain(network);
1609
+ if (chain === void 0) throw new ProviderError(-32603, `network ${network} has no Wallet Standard chain id`);
1610
+ return {
1611
+ address: account.address,
1612
+ publicKey: account.publicKey,
1613
+ chains: [chain],
1614
+ features: SOLANA_METHODS.filter((m) => m.startsWith("solana:"))
1615
+ };
1616
+ }
1617
+ async signTransactions(caller, request, send) {
1618
+ const network = this.networkOf(request.params, send, request.network);
1619
+ this.options.connections.authorize(caller.origin, network, request.method);
1620
+ const binding = this.options.connections.sessionAccounts(caller.origin, network);
1621
+ const address = binding?.addresses[0];
1622
+ if (binding === void 0 || address === void 0) throw new ProviderError(4100, "no solana account for this origin");
1623
+ checkAccounts(request.params, address);
1624
+ const txs = transactionsOf(request.params);
1625
+ for (const tx of txs) try {
1626
+ const { unsigned } = decodeSolanaTransaction(tx, address);
1627
+ if (send && unsigned.length > 0) throw invalidParams(`the transaction still needs signatures from ${unsigned.join(", ")}`);
1628
+ } catch (error) {
1629
+ throw error instanceof ChainError ? invalidParams(error.message) : error;
1630
+ }
1631
+ const outcome = await this.signRequest(caller, network, binding.group, address, {
1632
+ kind: "transactions",
1633
+ transactions: txs,
1634
+ send
1635
+ });
1636
+ if (!("kind" in outcome) || outcome.kind !== "solana.transactions") throw new ProviderError(-32603, "the solana-sign request settled unexpectedly");
1637
+ if (send && outcome.stopped !== void 0) throw batchStopped(outcome.stopped, outcome.signatures ?? []);
1638
+ return send ? { signatures: (outcome.signatures ?? []).map((signature) => base58.decode(signature)) } : { signedTransactions: outcome.signedTransactions };
1639
+ }
1640
+ /**
1641
+ * The network a transaction call targets: `network` (a WalletConnect request names its CAIP-2
1642
+ * chain) or the wallet's default when no input names a chain, otherwise the one chain every input
1643
+ * agrees on (`chain` is required for sign-and-send).
1644
+ */
1645
+ networkOf(params, requireChain, network) {
1646
+ const chains = paramList(params, "chains");
1647
+ if (requireChain && (chains.length === 0 || chains.some((chain) => chain === void 0))) throw invalidParams("chain is required for solana:signAndSendTransaction");
1648
+ const named = new Set(chains.filter((chain) => chain !== void 0));
1649
+ if (named.size === 0) return network ?? this.options.solanaNetwork();
1650
+ if (named.size > 1 || chains.some((chain) => chain === void 0)) throw invalidParams("every input must use the same chain");
1651
+ const [chain] = [...named];
1652
+ const resolved = typeof chain === "string" ? SOLANA_CHAIN_IDS[chain] : void 0;
1653
+ if (resolved === void 0) throw invalidParams("unknown chain");
1654
+ return resolved;
1655
+ }
1656
+ async signMessage(caller, request) {
1657
+ const network = request.network ?? this.options.solanaNetwork();
1658
+ this.options.connections.authorize(caller.origin, network, "solana:signMessage");
1659
+ const binding = this.options.connections.sessionAccounts(caller.origin, network);
1660
+ if (binding !== void 0 && binding.addresses[0] !== void 0) checkAccounts(request.params, binding.addresses[0]);
1661
+ const message = messageOf(request.params);
1662
+ return {
1663
+ signature: await this.signMessageRequest(caller, network, message),
1664
+ signedMessage: message
1665
+ };
1666
+ }
1667
+ /**
1668
+ * Sign In With Solana: connects first when needed, binds the message to the page's host and the
1669
+ * session's account, and signs the exact text the user is shown.
1670
+ */
1671
+ async signIn(caller, request) {
1672
+ const { input: raw } = typeof request.params === "object" && request.params !== null ? request.params : {};
1673
+ const input = checkSignInInput(raw === void 0 ? {} : raw);
1674
+ const { host } = new URL(dappUrl(caller));
1675
+ if (input.domain !== void 0 && input.domain !== host) throw invalidParams("domain does not match the page");
1676
+ const { accounts } = await this.connect(caller, request);
1677
+ const [walletAccount] = accounts;
1678
+ const network = request.network ?? this.options.solanaNetwork();
1679
+ this.options.connections.authorize(caller.origin, network, "solana:signIn");
1680
+ if (walletAccount === void 0) throw new ProviderError(4100, "no solana account for this origin");
1681
+ if (input.address !== void 0 && input.address !== walletAccount.address) throw new ProviderError(4100, "address is not the connected account");
1682
+ const fields = {
1683
+ ...input,
1684
+ domain: host,
1685
+ address: walletAccount.address
1686
+ };
1687
+ const message = new TextEncoder().encode(signInMessageText(fields));
1688
+ return [{
1689
+ account: walletAccount,
1690
+ signedMessage: message,
1691
+ signature: await this.signMessageRequest(caller, network, message, fields),
1692
+ signatureType: "ed25519"
1693
+ }];
1694
+ }
1695
+ async signMessageRequest(caller, network, message, signIn) {
1696
+ const binding = this.options.connections.sessionAccounts(caller.origin, network);
1697
+ const address = binding?.addresses[0];
1698
+ if (binding === void 0 || address === void 0) throw new ProviderError(4100, "no solana account for this origin");
1699
+ const outcome = await this.signRequest(caller, network, binding.group, address, {
1700
+ kind: "message",
1701
+ message,
1702
+ ...signIn === void 0 ? {} : { signIn }
1703
+ });
1704
+ if (!("kind" in outcome) || outcome.kind !== "solana.message") throw new ProviderError(-32603, "the solana-sign request settled unexpectedly");
1705
+ return outcome.signature;
1706
+ }
1707
+ /** One `solana-sign` request for the session's bound group, resolved to its outcome. */
1708
+ async signRequest(caller, network, group, address, request) {
1709
+ try {
1710
+ const pending = await this.options.requests.prepare({
1711
+ method: "solana-sign",
1712
+ origin: caller,
1713
+ account: {
1714
+ walletId: group.walletId,
1715
+ groupIndex: group.groupIndex,
1716
+ address
1717
+ },
1718
+ network,
1719
+ request
1720
+ });
1721
+ return await this.options.requests.outcome(pending.id);
1722
+ } catch (error) {
1723
+ throw toProviderError$1(error);
1724
+ }
1725
+ }
1726
+ /**
1727
+ * A `change` event's accounts, derived only from the session after the write: the binding's
1728
+ * account — empty when the session is gone or no Solana account is bound.
1729
+ */
1730
+ async sessionAccountsChanged(session) {
1731
+ const network = this.options.solanaNetwork();
1732
+ const binding = sessionAccounts(session, network);
1733
+ const address = binding?.addresses[0];
1734
+ if (binding === void 0 || address === void 0) return [];
1735
+ try {
1736
+ const account = await this.options.solanaAccount(binding.group, network);
1737
+ return account.address === address ? [this.walletAccount(account, network)] : [];
1738
+ } catch {
1739
+ return [];
1740
+ }
1741
+ }
1742
+ };
1743
+ const paramList = (params, name) => {
1744
+ const value = typeof params === "object" && params !== null ? new Map(Object.entries(params)).get(name) : void 0;
1745
+ if (value === void 0) return [];
1746
+ if (!Array.isArray(value)) throw invalidParams(`${name} must be an array`);
1747
+ return value;
1748
+ };
1749
+ /** Every account the page names must be the session's Solana account. */
1750
+ const checkAccounts = (params, address) => {
1751
+ if (paramList(params, "accounts").some((account) => account !== address)) throw new ProviderError(4100, "account is not the connected account");
1752
+ };
1753
+ const isBytesEnvelope$1 = (v) => typeof v === "object" && v !== null && typeof v.__bytes === "string";
1754
+ const transactionsOf = (params) => {
1755
+ const raw = typeof params === "object" && params !== null ? params.transactions : void 0;
1756
+ if (!Array.isArray(raw)) throw invalidParams("solana:signTransaction needs a transactions array");
1757
+ return raw.map((tx) => {
1758
+ if (tx instanceof Uint8Array) return tx;
1759
+ if (typeof tx === "string" && /^[0-9a-fA-F]+$/.test(tx)) return hexToBytes(tx);
1760
+ if (isBytesEnvelope$1(tx)) return hexToBytes(tx.__bytes);
1761
+ throw invalidParams("each transaction must be Uint8Array bytes or hex");
1762
+ });
1763
+ };
1764
+ const messageOf = (params) => {
1765
+ const message = typeof params === "object" && params !== null ? params.message : void 0;
1766
+ if (message instanceof Uint8Array) return message;
1767
+ if (typeof message === "string" && /^[0-9a-fA-F]+$/.test(message)) return hexToBytes(message);
1768
+ if (isBytesEnvelope$1(message)) return hexToBytes(message.__bytes);
1769
+ throw invalidParams("solana:signMessage needs Uint8Array bytes or hex");
1770
+ };
1771
+ const byOrigin$1 = (sessions) => new Map(Object.values(sessions).map((s) => [s.origin.origin, s]));
1772
+ const solanaAccounts = (session) => Object.entries(session.scopes).filter(([network]) => network.startsWith("solana:")).flatMap(([, scope]) => scope.accounts.map((a) => a.slice(a.lastIndexOf(":") + 1)));
1773
+ /**
1774
+ * The origins whose Solana scope's accounts changed between the two snapshots, each with the
1775
+ * session after the write (`undefined` when the session is gone).
1776
+ */
1777
+ function diffSessions$1(before, after) {
1778
+ const events = [];
1779
+ const prev = byOrigin$1(before);
1780
+ const next = byOrigin$1(after);
1781
+ for (const [origin, session] of prev) {
1782
+ const now = next.get(origin);
1783
+ if (solanaAccounts(session).join(",") !== (now === void 0 ? "" : solanaAccounts(now).join(","))) events.push({
1784
+ origin,
1785
+ session: now
1786
+ });
1787
+ }
1788
+ for (const [origin, session] of next) if (!prev.has(origin) && solanaAccounts(session).length > 0) events.push({
1789
+ origin,
1790
+ session
1791
+ });
1792
+ return events;
1793
+ }
1794
+ // src/connect/tron.ts
1795
+ /** `raw_data_hex` must fit a broadcastable TRON transaction; 500 KiB is far above the node limit. */
1796
+ const TRON_RAW_DATA_HEX_MAX = 1024e3;
1797
+ const isObject$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1798
+ const isBytesEnvelope = (v) => isObject$1(v) && typeof v["__bytes"] === "string";
1799
+ /** `tron:728126428` → `0x2b6653dc` — the CAIP-2 decimal reference in lowercase hex. */
1800
+ const tronChainId = (network) => {
1801
+ const ref = /^tron:(\d+)$/.exec(network)?.[1];
1802
+ return ref === void 0 ? void 0 : `0x${BigInt(ref).toString(16)}`;
1803
+ };
1804
+ const bytesOf = (value, name) => {
1805
+ if (value instanceof Uint8Array) return value;
1806
+ if (typeof value === "string" && /^[0-9a-fA-F]+$/.test(value)) return hexToBytes(value);
1807
+ if (isBytesEnvelope(value) && /^[0-9a-fA-F]+$/.test(value.__bytes)) return hexToBytes(value.__bytes);
1808
+ throw invalidParams(`${name} must be Uint8Array bytes or hex`);
1809
+ };
1810
+ const toProviderError = (error) => {
1811
+ if (error instanceof ProviderError) return error;
1812
+ if (error instanceof InvalidTokenError || error instanceof SignInOriginError) return invalidParams(error.message);
1813
+ if (error instanceof OriginBusyError) return userRejectedRequest(error.message);
1814
+ if (error instanceof RequestEndedError) return error.stage === "failed" ? internalError(error.message) : userRejectedRequest(error.message);
1815
+ if (error instanceof ChainError) return invalidParams(error.message);
1816
+ return internalError(error instanceof Error ? error.message : String(error));
1817
+ };
1818
+ /**
1819
+ * The Wallet-Standard-like TronLink handler: `tron_requestAccounts`/`eth_requestAccounts` authorize
1820
+ * the `tron` scope, signing goes through `tron-sign`, `tronStateChanged` carries the provider state
1821
+ * the injected script turns into `accountsChanged`/`chainChanged`/`connect`.
1822
+ */
1823
+ var TronWalletHandler = class {
1824
+ options;
1825
+ events;
1826
+ constructor(options) {
1827
+ this.options = options;
1828
+ this.events = new SessionEvents(options.connections, (before, after) => diffSessions(before, after).map(({ origin, session }) => ({
1829
+ name: "tronStateChanged",
1830
+ origin,
1831
+ state: this.providerState(session)
1832
+ })));
1833
+ }
1834
+ /** `tronStateChanged` per origin — derived from changes to the sessions. */
1835
+ subscribe(listener) {
1836
+ return this.events.subscribe(listener);
1837
+ }
1838
+ async handle(origin, request) {
1839
+ const checked = this.options.connections.checkOrigin(origin);
1840
+ switch (request.method) {
1841
+ case "tron_getProviderState": return this.providerState(this.options.connections.session(checked.origin));
1842
+ case "eth_requestAccounts": return this.requestAccounts(checked, false);
1843
+ case "tron_requestAccounts": return this.requestAccounts(checked, true);
1844
+ case "wallet_switchEthereumChain": return this.switchChain(checked, request.params);
1845
+ case "wallet_watchAsset": return this.watchAsset(checked, request.params);
1846
+ case "tron_signTransaction": return this.signTransaction(checked, request.params);
1847
+ case "tron_sendRawTransaction": return this.sendRawTransaction(checked, request.params);
1848
+ case "tron_signMessageV2": return this.signMessage(checked, request.params);
1849
+ case "tron_signTypedData": return this.signTypedData(checked, request.params);
1850
+ default: throw unsupportedMethod(request.method);
1851
+ }
1852
+ }
1853
+ /** The injected provider's state for the session's TRON network (or the default when absent). */
1854
+ providerState(session) {
1855
+ const network = session?.tronNetwork ?? this.options.tronNetwork();
1856
+ const base58 = sessionAccounts(session, network)?.addresses[0];
1857
+ return {
1858
+ address: base58 === void 0 ? false : {
1859
+ base58,
1860
+ hex: tronAddressToHex(base58).toLowerCase()
1861
+ },
1862
+ chainId: tronChainId(network) ?? "0x0",
1863
+ genesis: networkById(network)?.genesisHash ?? ""
1864
+ };
1865
+ }
1866
+ /**
1867
+ * `eth_requestAccounts` resolves `[base58]`; the legacy `tron_requestAccounts` resolves a `{code,
1868
+ * message}` result instead of rejecting — 200 on success, 4001 when the user refused, 4000 for
1869
+ * anything else (TronLink's own convention).
1870
+ */
1871
+ async requestAccounts(checked, legacy) {
1872
+ try {
1873
+ const network = this.options.connections.session(checked.origin)?.tronNetwork;
1874
+ const address = (network === void 0 ? void 0 : this.options.connections.sessionAccounts(checked.origin, network))?.addresses[0];
1875
+ if (address !== void 0) {
1876
+ await this.options.connections.touch(checked.origin);
1877
+ return legacy ? {
1878
+ code: 200,
1879
+ message: "wallet authorized"
1880
+ } : [address];
1881
+ }
1882
+ await this.options.connections.request(checked.origin, {
1883
+ kind: "connect",
1884
+ namespace: "tron"
1885
+ });
1886
+ const grantedNetwork = this.options.connections.session(checked.origin)?.tronNetwork;
1887
+ const grantedAddress = (grantedNetwork === void 0 ? void 0 : this.options.connections.sessionAccounts(checked.origin, grantedNetwork))?.addresses[0];
1888
+ if (grantedAddress === void 0) throw unauthorized("the wallet is not connected");
1889
+ return legacy ? {
1890
+ code: 200,
1891
+ message: "wallet authorized"
1892
+ } : [grantedAddress];
1893
+ } catch (error) {
1894
+ if (!legacy) throw toProviderError(error);
1895
+ return {
1896
+ code: error instanceof ProviderError && error.code === 4001 ? 4001 : 4e3,
1897
+ message: error instanceof Error ? error.message : String(error)
1898
+ };
1899
+ }
1900
+ }
1901
+ /** The session's current TRON network and its binding — every signing method requires both. */
1902
+ signingSession(checked, method) {
1903
+ const network = this.options.connections.session(checked.origin)?.tronNetwork;
1904
+ if (network === void 0) throw unauthorized("the wallet is not connected");
1905
+ this.options.connections.authorize(checked.origin, network, method);
1906
+ const binding = this.options.connections.sessionAccounts(checked.origin, network);
1907
+ if (binding === void 0 || binding.addresses[0] === void 0) throw unauthorized("no TRON account is bound to the session");
1908
+ return {
1909
+ network,
1910
+ binding
1911
+ };
1912
+ }
1913
+ /**
1914
+ * A `wallet_switchEthereumChain` on `window.tron` switches the session's TRON network: a chain id
1915
+ * that names no enabled TRON network is 4902, no session is 4100.
1916
+ */
1917
+ async switchChain(checked, params) {
1918
+ const param = Array.isArray(params) ? params[0] : void 0;
1919
+ const chainId = isObject$1(param) ? param["chainId"] : void 0;
1920
+ if (typeof chainId !== "string" || !/^0x[0-9a-fA-F]+$/.test(chainId)) throw invalidParams("params must be [{ chainId: '0x…' }]");
1921
+ const network = this.options.tronNetworks().find((n) => tronChainId(n)?.toLowerCase() === chainId.toLowerCase());
1922
+ if (network === void 0) throw unrecognizedChain(`${chainId} is not an enabled TRON chain`);
1923
+ if (this.options.connections.session(checked.origin) === void 0) throw unauthorized("the wallet is not connected");
1924
+ await this.options.connections.setTronNetwork(checked.origin, network);
1925
+ return null;
1926
+ }
1927
+ /** The TRC-20 `wallet_watchAsset`: other token kinds are 4200, malformed params invalid. */
1928
+ async watchAsset(checked, params) {
1929
+ if (!isObject$1(params) || params["type"] !== "trc20" || !isObject$1(params["options"])) {
1930
+ if (isObject$1(params) && (params["type"] === "trc10" || params["type"] === "trc721")) throw unsupportedMethod(`${params["type"]} watch-asset`);
1931
+ throw invalidParams("params must be { type: 'trc20', options: { address } }");
1932
+ }
1933
+ const { address } = params["options"];
1934
+ if (typeof address !== "string" || !isTronAddress(address)) throw invalidParams("options.address must be a TRON address");
1935
+ const { network, binding } = this.signingSession(checked, "wallet_watchAsset");
1936
+ if (this.options.isTracked(network, address)) return;
1937
+ try {
1938
+ const pending = await this.options.requests.prepare({
1939
+ method: "watch-asset",
1940
+ origin: checked,
1941
+ account: {
1942
+ kind: "hd",
1943
+ ...binding.group,
1944
+ template: "tron.bip44"
1945
+ },
1946
+ network,
1947
+ address
1948
+ });
1949
+ await this.options.requests.outcome(pending.id);
1950
+ await this.options.connections.touch(checked.origin);
1951
+ } catch (error) {
1952
+ throw toProviderError(error);
1953
+ }
1954
+ }
1955
+ /**
1956
+ * The dApp transaction shape checks every `tron_sign*`/`tron_send*` call shares: the declared
1957
+ * `txID` must be the sha256 of `raw_data_hex`, and a `raw_data` JSON must encode to exactly those
1958
+ * bytes — the wallet never signs bytes the page could misrepresent.
1959
+ */
1960
+ transactionOf(params, signaturePolicy) {
1961
+ if (!isObject$1(params) || !isObject$1(params["transaction"])) throw invalidParams("params must be { transaction }");
1962
+ const { transaction } = params;
1963
+ if (signaturePolicy === "absent" && transaction["signature"] !== void 0) throw invalidParams("the transaction is already signed");
1964
+ const signatures = transaction["signature"];
1965
+ if (signaturePolicy === "one" && (!Array.isArray(signatures) || signatures.length !== 1 || signatures.some((s) => typeof s !== "string" || !/^[0-9a-fA-F]{130}$/.test(s)))) throw invalidParams("transaction.signature must be exactly one 65-byte hex signature");
1966
+ const rawDataHex = transaction["raw_data_hex"];
1967
+ if (typeof rawDataHex !== "string" || rawDataHex.length % 2 !== 0 || rawDataHex.length > TRON_RAW_DATA_HEX_MAX || !/^[0-9a-fA-F]*$/.test(rawDataHex)) throw invalidParams("transaction.raw_data_hex must be even-length hex within 500 KiB");
1968
+ const { txID } = transaction;
1969
+ if (typeof txID !== "string" || !/^[0-9a-fA-F]{64}$/.test(txID)) throw invalidParams("transaction.txID must be 64 hex characters");
1970
+ if (transaction["visible"] !== void 0 && typeof transaction["visible"] !== "boolean") throw invalidParams("transaction.visible must be a boolean");
1971
+ const rawData = hexToBytes(rawDataHex);
1972
+ if (bytesToHex(sha256(rawData)) !== txID.toLowerCase()) throw invalidParams("transaction.txID does not match raw_data_hex");
1973
+ if (transaction["raw_data"] !== void 0) {
1974
+ if (!isObject$1(transaction["raw_data"])) throw invalidParams("transaction.raw_data must be an object");
1975
+ let encoded;
1976
+ try {
1977
+ encoded = tronRawDataFromJson(transaction["raw_data"], transaction["visible"] === true);
1978
+ } catch (error) {
1979
+ throw error instanceof ChainError ? invalidParams(error.message) : error;
1980
+ }
1981
+ if (bytesToHex(encoded) !== rawDataHex.toLowerCase()) throw invalidParams("raw_data does not match raw_data_hex");
1982
+ }
1983
+ return {
1984
+ transaction,
1985
+ rawData,
1986
+ signature: Array.isArray(signatures) && typeof signatures[0] === "string" ? signatures[0] : void 0
1987
+ };
1988
+ }
1989
+ async tronSign(checked, network, binding, request) {
1990
+ try {
1991
+ const pending = await this.options.requests.prepare({
1992
+ method: "tron-sign",
1993
+ origin: checked,
1994
+ account: {
1995
+ kind: "hd",
1996
+ ...binding.group,
1997
+ template: "tron.bip44"
1998
+ },
1999
+ network,
2000
+ request
2001
+ });
2002
+ return await this.options.requests.outcome(pending.id);
2003
+ } catch (error) {
2004
+ throw toProviderError(error);
2005
+ }
2006
+ }
2007
+ /** `trx.sign(tx)` — signs the exact `raw_data` bytes; the page broadcasts them itself. */
2008
+ async signTransaction(checked, params) {
2009
+ const { transaction, rawData } = this.transactionOf(params, "absent");
2010
+ const { network, binding } = this.signingSession(checked, "tron_signTransaction");
2011
+ const outcome = await this.tronSign(checked, network, binding, {
2012
+ kind: "tron.transaction",
2013
+ network,
2014
+ account: {
2015
+ kind: "hd",
2016
+ ...binding.group,
2017
+ template: "tron.bip44"
2018
+ },
2019
+ rawData
2020
+ });
2021
+ const signature = "tron" in outcome && outcome.tron !== void 0 ? outcome.tron.dappSignature : void 0;
2022
+ if (typeof signature !== "string") throw internalError("the tron-sign request settled unexpectedly");
2023
+ return {
2024
+ ...transaction,
2025
+ signature: [signature]
2026
+ };
2027
+ }
2028
+ /** `trx.sendRawTransaction(tx)` — broadcasts a transaction this wallet already signed. */
2029
+ async sendRawTransaction(checked, params) {
2030
+ const { transaction, rawData, signature } = this.transactionOf(params, "one");
2031
+ const { network } = this.signingSession(checked, "tron_sendRawTransaction");
2032
+ const txid = typeof transaction["txID"] === "string" ? transaction["txID"] : "";
2033
+ try {
2034
+ await this.options.transactions.submitDappTron(network, rawData, hexToBytes(signature ?? ""));
2035
+ return {
2036
+ result: true,
2037
+ txid,
2038
+ transaction
2039
+ };
2040
+ } catch (error) {
2041
+ if (error instanceof BroadcastRefusedError) {
2042
+ const { cause } = error;
2043
+ return {
2044
+ result: false,
2045
+ code: isObject$1(cause) && typeof cause["code"] === "string" ? cause["code"] : "REFUSED",
2046
+ message: error.message,
2047
+ txid,
2048
+ transaction
2049
+ };
2050
+ }
2051
+ throw toProviderError(error);
2052
+ }
2053
+ }
2054
+ /** `trx.signMessageV2(m)` — a TIP-191 personal-sign of arbitrary bytes. */
2055
+ async signMessage(checked, params) {
2056
+ const message = isObject$1(params) ? params["message"] : void 0;
2057
+ if (message === void 0) throw invalidParams("params must be { message }");
2058
+ const bytes = bytesOf(message, "message");
2059
+ const { network, binding } = this.signingSession(checked, "tron_signMessageV2");
2060
+ const outcome = await this.tronSign(checked, network, binding, {
2061
+ kind: "tron.message",
2062
+ network,
2063
+ account: {
2064
+ kind: "hd",
2065
+ ...binding.group,
2066
+ template: "tron.bip44"
2067
+ },
2068
+ message: bytes
2069
+ });
2070
+ if (!("signature" in outcome) || !(outcome.signature instanceof Uint8Array)) throw internalError("the tron-sign request settled unexpectedly");
2071
+ return `0x${bytesToHex(outcome.signature)}`;
2072
+ }
2073
+ /** `trx.signTypedData`/`_signTypedData` — a TIP-712 typed-data signature. */
2074
+ async signTypedData(checked, params) {
2075
+ if (!isObject$1(params) || !isObject$1(params["domain"]) || !isObject$1(params["types"]) || params["message"] === void 0) throw invalidParams("params must be { domain, types, message }");
2076
+ let typedData;
2077
+ try {
2078
+ typedData = tronTypedDataFromArgs(params["domain"], params["types"], params["message"]);
2079
+ } catch (error) {
2080
+ throw error instanceof ChainError ? invalidParams(error.message) : error;
2081
+ }
2082
+ const { network, binding } = this.signingSession(checked, "tron_signTypedData");
2083
+ const outcome = await this.tronSign(checked, network, binding, {
2084
+ kind: "tron.typed-data",
2085
+ network,
2086
+ account: {
2087
+ kind: "hd",
2088
+ ...binding.group,
2089
+ template: "tron.bip44"
2090
+ },
2091
+ typedData
2092
+ });
2093
+ if (!("signature" in outcome) || !(outcome.signature instanceof Uint8Array)) throw internalError("the tron-sign request settled unexpectedly");
2094
+ return `0x${bytesToHex(outcome.signature)}`;
2095
+ }
2096
+ };
2097
+ const byOrigin = (sessions) => new Map(Object.values(sessions).map((s) => [s.origin.origin, s]));
2098
+ const tronAccounts = (session) => Object.entries(session.scopes).filter(([network]) => network.startsWith("tron:")).flatMap(([, scope]) => scope.accounts.map((a) => a.slice(a.lastIndexOf(":") + 1)));
2099
+ const tronFingerprint = (session) => `${tronAccounts(session).join(",")}@${session.tronNetwork ?? ""}`;
2100
+ /**
2101
+ * The origins whose TRON scope accounts or current TRON network changed between the two snapshots,
2102
+ * each with the session after the write (`undefined` when the session is gone).
2103
+ */
2104
+ function diffSessions(before, after) {
2105
+ const events = [];
2106
+ const prev = byOrigin(before);
2107
+ const next = byOrigin(after);
2108
+ for (const [origin, session] of prev) {
2109
+ const now = next.get(origin);
2110
+ if (now === void 0 || tronFingerprint(session) !== tronFingerprint(now)) events.push({
2111
+ origin,
2112
+ session: now
2113
+ });
2114
+ }
2115
+ for (const [origin, session] of next) if (!prev.has(origin) && tronAccounts(session).length > 0) events.push({
2116
+ origin,
2117
+ session
2118
+ });
2119
+ return events;
2120
+ }
2121
+ // src/payments/parse.ts
2122
+ /** Invoices with less than this much life left are treated as already expired. */
2123
+ const BOLT11_EXPIRY_GRACE_MS = 6e4;
2124
+ const invalid = (reason) => ({
2125
+ kind: "invalid",
2126
+ reason
2127
+ });
2128
+ /** BTC decimal `amount` → sats. At most 8 decimal places; must fit a safe integer. */
2129
+ function btcAmountSats(text) {
2130
+ const match = /^(\d+)(?:\.(\d{1,8}))?$/.exec(text);
2131
+ if (match === null) return;
2132
+ const [, whole] = match;
2133
+ if (whole === void 0) return;
2134
+ const sats = BigInt(whole) * 100000000n + BigInt((match[2] ?? "").padEnd(8, "0") || "0");
2135
+ return sats <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(sats) : void 0;
2136
+ }
2137
+ /**
2138
+ * BOLT11 → fields, network- and expiry-checked. `undefined` = not a bolt11 string; `"network"` /
2139
+ * `"expired"` / `"malformed"` are the failure modes.
2140
+ */
2141
+ function bolt11Fields(text, options) {
2142
+ let decoded;
2143
+ try {
2144
+ decoded = decodeBolt11(text);
2145
+ } catch {
2146
+ return;
2147
+ }
2148
+ const network = decoded.network === "mainnet" ? "mainnet" : decoded.network === "regtest" ? "regtest" : void 0;
2149
+ if (network === void 0) return "network";
2150
+ if (network !== options.network) return "network";
2151
+ const expiresAt = (decoded.timestamp + decoded.expirySeconds) * 1e3;
2152
+ if (expiresAt <= options.now + BOLT11_EXPIRY_GRACE_MS) return "expired";
2153
+ return {
2154
+ ...decoded.amountMsat === void 0 ? {} : { amountSats: Math.ceil(Number(decoded.amountMsat) / 1e3) },
2155
+ paymentHash: bytesToHex(decoded.paymentHash),
2156
+ ...decoded.description === void 0 ? {} : { description: decoded.description },
2157
+ expiresAt
2158
+ };
2159
+ }
2160
+ /** Spark address or sats/token invoice → options. `null` means not a spark input. */
2161
+ function sparkOptions(text, options) {
2162
+ let decoded;
2163
+ try {
2164
+ decoded = decodeSparkAddress(text);
2165
+ } catch {
2166
+ return;
2167
+ }
2168
+ if (decoded.network !== options.network) return "network";
2169
+ if (decoded.invoice === void 0) return [{
2170
+ kind: "spark",
2171
+ address: text
2172
+ }];
2173
+ if (decoded.invoice.expiresAt !== void 0 && decoded.invoice.expiresAt <= options.now) return "expired";
2174
+ if (decoded.invoice.payment?.type === "tokens") return "token";
2175
+ let parsed;
2176
+ try {
2177
+ parsed = parseSparkInvoice(text, {
2178
+ network: options.network,
2179
+ now: options.now
2180
+ });
2181
+ } catch {
2182
+ return "malformed";
2183
+ }
2184
+ const { payment } = parsed.fields;
2185
+ return [{
2186
+ kind: "spark-invoice",
2187
+ invoice: text,
2188
+ ...payment?.type === "sats" && payment.amount !== void 0 ? { amountSats: payment.amount } : {},
2189
+ ...parsed.fields.memo === void 0 ? {} : { memo: parsed.fields.memo },
2190
+ ...parsed.fields.expiresAt === void 0 ? {} : { expiresAt: parsed.fields.expiresAt }
2191
+ }];
2192
+ }
2193
+ /** Does `address` decode under the other network? Used only to classify a rejection. */
2194
+ function decodesOnOtherNetwork(address, options) {
2195
+ try {
2196
+ bitcoinAddressScript(address, options.network === "mainnet" ? "regtest" : "mainnet");
2197
+ return true;
2198
+ } catch {
2199
+ return false;
2200
+ }
2201
+ }
2202
+ /** BIP-21 URI → request. Only the `spark=` and `lightning=` payment methods are supported. */
2203
+ function bip21Parse(text, options) {
2204
+ const q = text.indexOf("?");
2205
+ const address = text.slice(8, q === -1 ? void 0 : q);
2206
+ const params = /* @__PURE__ */ new Map();
2207
+ if (q !== -1) for (const pair of text.slice(q + 1).split("&")) {
2208
+ const eq = pair.indexOf("=");
2209
+ if (eq === -1) return invalid("malformed");
2210
+ let key;
2211
+ let value;
2212
+ try {
2213
+ key = decodeURIComponent(pair.slice(0, eq)).toLowerCase();
2214
+ value = decodeURIComponent(pair.slice(eq + 1));
2215
+ } catch {
2216
+ return invalid("malformed");
2217
+ }
2218
+ if (params.has(key)) return invalid("malformed");
2219
+ if (key.startsWith("req-") && !BIP21_KNOWN_REQ_PARAMS.has(key)) return invalid("malformed");
2220
+ params.set(key, value);
2221
+ }
2222
+ const options_ = [];
2223
+ let declaredSats;
2224
+ const spark = params.get("spark");
2225
+ if (spark !== void 0) {
2226
+ const parsed = sparkOptions(spark, options);
2227
+ if (parsed === void 0 || parsed === "malformed") return invalid("malformed");
2228
+ if (parsed === "token") return {
2229
+ kind: "unsupported",
2230
+ format: "spark-token-invoice"
2231
+ };
2232
+ if (parsed === "network" || parsed === "expired") return invalid(parsed);
2233
+ options_.push(...parsed);
2234
+ const sats = parsed.find((o) => o.kind === "spark-invoice")?.amountSats;
2235
+ if (sats !== void 0) {
2236
+ if (declaredSats !== void 0 && declaredSats !== sats) return invalid("amount-mismatch");
2237
+ declaredSats = sats;
2238
+ }
2239
+ }
2240
+ const lightning = params.get("lightning");
2241
+ if (lightning !== void 0) {
2242
+ const parsed = bolt11Fields(lightning, options);
2243
+ if (parsed === void 0 || parsed === "malformed") return invalid("malformed");
2244
+ if (parsed === "network" || parsed === "expired") return invalid(parsed);
2245
+ options_.push({
2246
+ kind: "lightning",
2247
+ invoice: lightning,
2248
+ ...parsed.amountSats === void 0 ? {} : { amountSats: parsed.amountSats },
2249
+ paymentHash: parsed.paymentHash,
2250
+ ...parsed.description === void 0 ? {} : { description: parsed.description },
2251
+ expiresAt: parsed.expiresAt
2252
+ });
2253
+ if (parsed.amountSats !== void 0) {
2254
+ if (declaredSats !== void 0 && declaredSats !== parsed.amountSats) return invalid("amount-mismatch");
2255
+ declaredSats = parsed.amountSats;
2256
+ }
2257
+ }
2258
+ if (address.length > 0) {
2259
+ try {
2260
+ bitcoinAddressScript(address, options.network);
2261
+ } catch {
2262
+ return invalid(decodesOnOtherNetwork(address, options) ? "network" : "malformed");
2263
+ }
2264
+ options_.push({
2265
+ kind: "bitcoin",
2266
+ address
2267
+ });
2268
+ }
2269
+ const declaredAmount = params.get("amount");
2270
+ if (declaredAmount !== void 0) {
2271
+ const sats = btcAmountSats(declaredAmount);
2272
+ if (sats === void 0) return invalid("malformed");
2273
+ if (declaredSats !== void 0 && declaredSats !== sats) return invalid("amount-mismatch");
2274
+ declaredSats = sats;
2275
+ }
2276
+ if (options_.length === 0) {
2277
+ if (params.has("lno")) return {
2278
+ kind: "unsupported",
2279
+ format: "bolt12"
2280
+ };
2281
+ if (params.has("sp")) return {
2282
+ kind: "unsupported",
2283
+ format: "silent-payment"
2284
+ };
2285
+ return invalid("malformed");
2286
+ }
2287
+ return {
2288
+ kind: "request",
2289
+ request: {
2290
+ options: options_,
2291
+ ...declaredSats === void 0 ? {} : { amountSats: declaredSats },
2292
+ ...params.get("label") === void 0 ? {} : { label: params.get("label") ?? "" },
2293
+ ...params.get("message") === void 0 ? {} : { message: params.get("message") ?? "" }
2294
+ }
2295
+ };
2296
+ }
2297
+ const BIP21_KNOWN_REQ_PARAMS = /* @__PURE__ */ new Set([
2298
+ "req-amount",
2299
+ "req-label",
2300
+ "req-message"
2301
+ ]);
2302
+ /** `input` → PaymentParse. Never throws: every failure is a structured result. */
2303
+ function parsePayment(input, options) {
2304
+ try {
2305
+ const text = input.trim();
2306
+ if (/^wc:[0-9a-f]{64}@2\?/i.test(text)) return {
2307
+ kind: "walletconnect",
2308
+ uri: text
2309
+ };
2310
+ if (/^nostr\+walletconnect:/i.test(text)) return {
2311
+ kind: "unsupported",
2312
+ format: "nostr-wallet-connect"
2313
+ };
2314
+ const stripped = text.toLowerCase().startsWith("lightning:") ? text.slice(10) : text;
2315
+ if (/^bitcoin:/i.test(stripped)) return bip21Parse(`bitcoin:${stripped.slice(stripped.indexOf(":") + 1)}`, options);
2316
+ const bolt11 = bolt11Fields(stripped, options);
2317
+ if (bolt11 === "network" || bolt11 === "expired" || bolt11 === "malformed") return invalid(bolt11);
2318
+ if (bolt11 !== void 0) return {
2319
+ kind: "request",
2320
+ request: {
2321
+ options: [{
2322
+ kind: "lightning",
2323
+ invoice: stripped,
2324
+ ...bolt11.amountSats === void 0 ? {} : { amountSats: bolt11.amountSats },
2325
+ paymentHash: bolt11.paymentHash,
2326
+ ...bolt11.description === void 0 ? {} : { description: bolt11.description },
2327
+ expiresAt: bolt11.expiresAt
2328
+ }],
2329
+ ...bolt11.amountSats === void 0 ? {} : { amountSats: bolt11.amountSats }
2330
+ }
2331
+ };
2332
+ const spark = sparkOptions(stripped, options);
2333
+ if (spark === "token") return {
2334
+ kind: "unsupported",
2335
+ format: "spark-token-invoice"
2336
+ };
2337
+ if (spark === "network" || spark === "expired" || spark === "malformed") return invalid(spark);
2338
+ if (spark !== void 0) return {
2339
+ kind: "request",
2340
+ request: { options: spark }
2341
+ };
2342
+ if (/^(lnurlp|lnurlw):/i.test(stripped)) {
2343
+ const rest = stripped.slice(stripped.indexOf("://") + 3);
2344
+ const url = `${(rest.split(/[/?#]/, 1)[0] ?? "").toLowerCase().endsWith(".onion") ? "http" : "https"}://${rest}`;
2345
+ if (new URL(url).searchParams.get("tag") === "login") return {
2346
+ kind: "unsupported",
2347
+ format: "lnurl-auth"
2348
+ };
2349
+ return {
2350
+ kind: "lnurl",
2351
+ url
2352
+ };
2353
+ }
2354
+ if (/^keyauth:/i.test(stripped)) return {
2355
+ kind: "unsupported",
2356
+ format: "lnurl-auth"
2357
+ };
2358
+ if (!stripped.includes(":") && stripped.includes("@")) return {
2359
+ kind: "lnurl",
2360
+ url: lightningAddressUrl(stripped),
2361
+ address: stripped
2362
+ };
2363
+ if (/^lno1[02-9ac-hj-np-z]+$/i.test(stripped)) return {
2364
+ kind: "unsupported",
2365
+ format: "bolt12"
2366
+ };
2367
+ try {
2368
+ const url = decodeLnurl(stripped);
2369
+ if (new URL(url).searchParams.get("tag") === "login") return {
2370
+ kind: "unsupported",
2371
+ format: "lnurl-auth"
2372
+ };
2373
+ return {
2374
+ kind: "lnurl",
2375
+ url
2376
+ };
2377
+ } catch {}
2378
+ try {
2379
+ bitcoinAddressScript(stripped, options.network);
2380
+ return {
2381
+ kind: "request",
2382
+ request: { options: [{
2383
+ kind: "bitcoin",
2384
+ address: stripped
2385
+ }] }
2386
+ };
2387
+ } catch {
2388
+ if (decodesOnOtherNetwork(stripped, options)) return invalid("network");
2389
+ }
2390
+ return { kind: "unrecognized" };
2391
+ } catch {
2392
+ return invalid("malformed");
2393
+ }
2394
+ }
2395
+ // src/connect/webln.ts
2396
+ /**
2397
+ * The WebLN (`window.webln`) handler — the bridge routes `provider: "webln"` messages here.
2398
+ * `enable` asks for a `lightning` connection approval when the origin is not yet authorized;
2399
+ * `sendPayment` and `lnurl` pay through the request pipeline's `pay` (a funds request with a
2400
+ * factor) and then poll `paymentStatus` for the settled preimage; `makeInvoice` goes through the
2401
+ * factor-free `webln-invoice`; `getBalance` additionally needs the session's
2402
+ * `lightningPolicy.balance`; `getInfo` exposes only the configured alias and methods.
2403
+ */
2404
+ const MAX_MEMO_LENGTH = 640;
2405
+ const PREIMAGE_POLL_START_MS = 1e3;
2406
+ const PREIMAGE_POLL_MAX_MS = 8e3;
2407
+ const PREIMAGE_POLL_BUDGET_MS = 6e4;
2408
+ const NOT_SETTLED = "the payment has not settled yet and may still settle; do not retry it";
2409
+ /** A committed payment whose answer was lost: it may still settle under its transfer id. */
2410
+ const unknownOutcome = (transferId) => paymentPending(`the payment outcome is unknown: it may still settle under transfer ${transferId}; do not retry it`);
2411
+ const isObject = (v) => typeof v === "object" && v !== null;
2412
+ const checkString = (value, name) => {
2413
+ if (typeof value !== "string" || value === "") throw invalidParams(`${name} must be a non-empty string`);
2414
+ return value;
2415
+ };
2416
+ const checkAmount = (value, name) => {
2417
+ if (value === void 0) return;
2418
+ const n = typeof value === "string" ? Number(value) : value;
2419
+ if (typeof n !== "number" || !Number.isSafeInteger(n) || n < 0) throw invalidParams(`${name} must be a non-negative safe integer`);
2420
+ return n;
2421
+ };
2422
+ const checkInvoiceArgs = (params) => {
2423
+ const args = isObject(params) ? params : {};
2424
+ const amount = checkAmount(args["amount"], "makeInvoice amount") ?? checkAmount(args["defaultAmount"], "makeInvoice defaultAmount");
2425
+ checkAmount(args["minimumAmount"], "makeInvoice minimumAmount");
2426
+ checkAmount(args["maximumAmount"], "makeInvoice maximumAmount");
2427
+ if (amount === void 0) throw invalidParams("makeInvoice needs an amount or a defaultAmount");
2428
+ const memo = args["defaultMemo"];
2429
+ if (memo !== void 0 && (typeof memo !== "string" || memo.length > MAX_MEMO_LENGTH)) throw invalidParams("makeInvoice defaultMemo must be a string at most 640 characters");
2430
+ return {
2431
+ amountSats: amount,
2432
+ ...typeof memo === "string" ? { memo } : {}
2433
+ };
2434
+ };
2435
+ const checkMaxFee = (fn, amountSats) => {
2436
+ const maxFee = fn(amountSats);
2437
+ if (!Number.isSafeInteger(maxFee) || maxFee < 0) throw new ProviderError(-32603, "invalid lightning fee cap");
2438
+ return maxFee;
2439
+ };
2440
+ var WeblnHandler = class {
2441
+ options;
2442
+ constructor(options) {
2443
+ this.options = options;
2444
+ }
2445
+ /** The session's `lightning` binding as a Spark ref — the group the session authorized. */
2446
+ ref(origin) {
2447
+ const group = this.options.connections.sessionAccounts(origin, "lightning")?.group;
2448
+ if (group === void 0) throw unauthorized("no lightning account is bound to the session");
2449
+ return {
2450
+ ...group,
2451
+ network: this.options.sparkNetwork
2452
+ };
2453
+ }
2454
+ async handle(origin, request) {
2455
+ if (request.method === "enable") {
2456
+ if (this.options.connections.lightningPolicy(origin) === void 0) await this.options.connections.request(origin, {
2457
+ kind: "connect",
2458
+ namespace: "lightning"
2459
+ });
2460
+ await this.options.connections.touch(origin);
2461
+ return true;
2462
+ }
2463
+ this.options.connections.authorize(origin, "lightning", request.method);
2464
+ await this.options.connections.touch(origin);
2465
+ const ref = this.ref(origin);
2466
+ switch (request.method) {
2467
+ case "getInfo": return {
2468
+ node: { alias: this.options.alias },
2469
+ methods: [...LIGHTNING_METHODS]
2470
+ };
2471
+ case "sendPayment": return this.sendPayment(origin, ref, request.params);
2472
+ case "makeInvoice": return this.makeInvoice(origin, ref, request.params);
2473
+ case "lnurl": return this.lnurl(origin, ref, request.params);
2474
+ case "getBalance": return this.getBalance(origin);
2475
+ default: throw unsupportedMethod(request.method);
2476
+ }
2477
+ }
2478
+ async sendPayment(origin, ref, params) {
2479
+ const invoice = checkString(params, "sendPayment invoice");
2480
+ const option = this.lightningOption(ref, invoice);
2481
+ if (option.amountSats === void 0) throw invalidParams("sendPayment needs a fixed-amount invoice");
2482
+ const maxFeeSats = checkMaxFee(this.options.lightningMaxFee, option.amountSats);
2483
+ const pending = await this.options.requests.prepare({
2484
+ method: "pay",
2485
+ origin: {
2486
+ kind: "browser",
2487
+ origin
2488
+ },
2489
+ account: ref,
2490
+ option,
2491
+ maxFeeSats
2492
+ });
2493
+ const outcome = await this.options.requests.outcome(pending.id);
2494
+ if (!("kind" in outcome) || outcome.kind !== "lightning") {
2495
+ if ("kind" in outcome && outcome.kind === "pending") throw unknownOutcome(outcome.payment.id);
2496
+ throw new ProviderError(-32603, "the lightning payment settled unexpectedly");
2497
+ }
2498
+ return this.preimage(ref, outcome.payment);
2499
+ }
2500
+ async makeInvoice(origin, ref, params) {
2501
+ const { amountSats, memo } = checkInvoiceArgs(params);
2502
+ const pending = await this.options.requests.prepare({
2503
+ method: "webln-invoice",
2504
+ origin: {
2505
+ kind: "browser",
2506
+ origin
2507
+ },
2508
+ ref,
2509
+ amountSats,
2510
+ ...memo === void 0 ? {} : { memo }
2511
+ });
2512
+ const outcome = await this.options.requests.outcome(pending.id);
2513
+ if (!("kind" in outcome) || outcome.kind !== "lightning.invoice") throw new ProviderError(-32603, "the invoice request settled unexpectedly");
2514
+ return { paymentRequest: outcome.paymentRequest };
2515
+ }
2516
+ async lnurl(origin, ref, params) {
2517
+ const parsed = parsePayment(checkString(params, "lnurl"), {
2518
+ network: ref.network,
2519
+ now: this.options.now()
2520
+ });
2521
+ if (parsed.kind !== "request") throw invalidParams("lnurl is not an LNURL-pay request");
2522
+ if (parsed.request.options.some((o) => o.kind === "lnurl-withdraw")) throw unsupportedMethod("lnurl-withdraw");
2523
+ const option = parsed.request.options.find((o) => o.kind === "lnurl-pay");
2524
+ if (option === void 0 || option.kind !== "lnurl-pay") throw invalidParams("lnurl is not an LNURL-pay request");
2525
+ const amountSats = Math.ceil(option.request.minSendableMsat / 1e3);
2526
+ const maxFeeSats = checkMaxFee(this.options.lightningMaxFee, amountSats);
2527
+ const pending = await this.options.requests.prepare({
2528
+ method: "pay",
2529
+ origin: {
2530
+ kind: "browser",
2531
+ origin
2532
+ },
2533
+ account: ref,
2534
+ option,
2535
+ amountSats,
2536
+ maxFeeSats,
2537
+ amountFromServiceMinimum: true
2538
+ });
2539
+ const outcome = await this.options.requests.outcome(pending.id);
2540
+ if (!("kind" in outcome) || outcome.kind !== "lightning") {
2541
+ if ("kind" in outcome && outcome.kind === "pending") throw unknownOutcome(outcome.payment.id);
2542
+ throw new ProviderError(-32603, "the lnurl payment settled unexpectedly");
2543
+ }
2544
+ return this.preimage(ref, outcome.payment);
2545
+ }
2546
+ async preimage(ref, payment) {
2547
+ let delay = PREIMAGE_POLL_START_MS;
2548
+ let waited = 0;
2549
+ while (true) {
2550
+ let status;
2551
+ try {
2552
+ status = await this.options.spark.paymentStatus(ref, {
2553
+ requestId: payment.requestId,
2554
+ paymentHash: payment.paymentHash
2555
+ });
2556
+ } catch {
2557
+ throw paymentPending(NOT_SETTLED);
2558
+ }
2559
+ if (status.outcome === "failed" || status.outcome === "returned") throw new ProviderError(-32603, "payment failed");
2560
+ if (status.outcome === "succeeded") {
2561
+ if (status.preimage === void 0) throw paymentPending("the payment settled but its preimage is unavailable; do not retry it");
2562
+ return { preimage: bytesToHex(status.preimage) };
2563
+ }
2564
+ if (waited >= PREIMAGE_POLL_BUDGET_MS) throw paymentPending(NOT_SETTLED);
2565
+ const step = Math.min(delay, PREIMAGE_POLL_MAX_MS);
2566
+ await this.options.sleep(step);
2567
+ waited += step;
2568
+ delay *= 2;
2569
+ }
2570
+ }
2571
+ lightningOption(ref, invoice) {
2572
+ const parsed = parsePayment(invoice, {
2573
+ network: ref.network,
2574
+ now: this.options.now()
2575
+ });
2576
+ if (parsed.kind !== "request") throw invalidParams("sendPayment invoice is not a BOLT11 invoice");
2577
+ const option = parsed.request.options.find((o) => o.kind === "lightning");
2578
+ if (option === void 0 || option.kind !== "lightning") throw invalidParams("sendPayment invoice is not a BOLT11 invoice");
2579
+ return option;
2580
+ }
2581
+ getBalance(origin) {
2582
+ if (this.options.connections.lightningPolicy(origin)?.balance !== true) throw unauthorized("balance access is not granted");
2583
+ const balance = this.options.spark.accountBalance(this.ref(origin));
2584
+ if (balance === void 0) throw new ProviderError(-32603, "no cached balance for the active spark account");
2585
+ return {
2586
+ balance,
2587
+ currency: "sats"
2588
+ };
2589
+ }
2590
+ };
2591
+ export { evmChainId as A, failTx as C, newRequestId as D, newId as E, toProviderError$1 as F, unauthorized as I, unrecognizedChain as L, internalError as M, invalidParams as N, replacementStaleReason as O, limitExceeded as P, unsupportedMethod as R, awaitingFinality as S, includedPoll as T, submitSigned as _, SolanaWalletHandler as a, accountAddressOf as b, BITCOIN_CHAIN_IDS as c, utf8Text as d, RESUBMIT_BASE_MS as f, submitInOrder as g, STUCK_NOTE as h, SOLANA_CHAIN_IDS as i, ProviderError as j, ConnectionController as k, BitcoinWalletHandler as l, STUCK_AFTER_MS as m, parsePayment as n, walletStandardChain as o, RESUBMIT_MAX_MS as p, TronWalletHandler as r, Nip07Handler as s, WeblnHandler as t, bitcoinStandardChain as u, SessionEvents as v, gatewayOnlyBindingMessage as w, assertGatewayOnlyBinding as x, accountAddress as y, PHISHING_BLOCKED_MESSAGE as z };
2592
+
2593
+ //# sourceMappingURL=webln-BgrtPXpG.mjs.map