@qntx/wallet-engine 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,15 +1,16 @@
1
- import { A as rpcPath, C as EVM_RPC_METHODS, I as parseWith, c as networkById, i as servedNetworksResponse, t as networksPath, u as esploraBasePath, v as INSTALL_ID_HEADER } from "./contract-CEsgLme3.mjs";
2
- import { createStore } from "zustand/vanilla";
1
+ import { a as Nip07Handler, c as ProviderError, d as unauthorized, f as unrecognizedChain, h as Controller, i as SolanaWalletHandler, l as internalError, m as userRejectedRequest, n as parsePayment, o as ConnectionController, p as unsupportedMethod, r as SOLANA_CHAIN_IDS, s as evmChainId, t as WeblnHandler, u as invalidParams } from "./webln-CHjBMRcv.mjs";
2
+ import { i as networkById } from "./registry-CHiAn88k.mjs";
3
+ import { EVM_RPC_METHODS, INSTALL_ID_HEADER, esploraBasePath, networksPath, parseWith, rpcPath, servedNetworksResponse } from "./gateway-contract.mjs";
3
4
  import { bytesToHex, hexToBytes, utf8ToBytes } from "@noble/hashes/utils.js";
4
5
  import { ChainError } from "@qntx/wallet-chains";
5
6
  import { WalletError, parseBackupHeader } from "@qntx/wallet";
7
+ import { PROGRAM_IDS, decodeSolana, isSolanaAddress, netAfterTransferFee, normalizeSolana, parseMintExtensions } from "@qntx/wallet-chains/solana";
6
8
  import { Address, OutScript, Transaction } from "@scure/btc-signer";
7
- import { SparkInputError, bitcoinAddressScript, createSparkClient, decodeBolt11, decodeSparkAddress, encodeSparkAddress, parseSparkInvoice, uuidv7 } from "@qntx/spark";
9
+ import { SparkInputError, SparkRequestError, bitcoinAddressScript, createSparkClient, decodeBolt11, decodeSparkAddress, encodeSparkAddress, parseSparkInvoice, uuidv7 } from "@qntx/spark";
8
10
  import { BITCOIN_NETWORKS, bitcoinAddressFromXpub, bitcoinNetwork, bitcoinPubkeyFromXpub, decodeBitcoinPsbt } from "@qntx/wallet-chains/bitcoin";
9
11
  import { checksumEvmAddress, decodeEvm, isEvmAddress, normalizeEvm } from "@qntx/wallet-chains/evm";
10
- import { PROGRAM_IDS, decodeSolana, isSolanaAddress, netAfterTransferFee, parseMintExtensions } from "@qntx/wallet-chains/solana";
11
- import { decodeLnurl, encodeLnurl, lightningAddressUrl, registerLightningAddress, requestInvoice, resolveLnurl, submitWithdraw, unregisterLightningAddress } from "@qntx/spark/lnurl";
12
- import { signedMatchesUnsigned, verifyEvent } from "@qntx/nostr";
12
+ import { encodeLnurl, lightningAddressUrl, registerLightningAddress, requestInvoice, resolveLnurl, submitWithdraw, unregisterLightningAddress } from "@qntx/spark/lnurl";
13
+ import { signedMatchesUnsigned } from "@qntx/nostr";
13
14
  import { makeZapRequest } from "@qntx/nostr/nips/nip57";
14
15
  import { chains } from "@qntx/wallet/chains";
15
16
  import { nostr } from "@qntx/wallet/nostr";
@@ -17,32 +18,12 @@ import { spark } from "@qntx/wallet/spark";
17
18
  import { createPublicClient, decodeFunctionResult, encodeFunctionData, fallback, http, isAddress, isHex, numberToHex } from "viem";
18
19
  import { sha256 } from "@noble/hashes/sha2.js";
19
20
  import { base64, hex } from "@scure/base";
20
- import { p2wpkh } from "@scure/btc-signer/payment.js";
21
- import { selectUTXO } from "@scure/btc-signer/utxo.js";
22
21
  import { getSetComputeUnitLimitInstruction, getSetComputeUnitPriceInstruction } from "@solana-program/compute-budget";
23
22
  import { getTransferSolInstruction } from "@solana-program/system";
24
23
  import { TOKEN_PROGRAM_ADDRESS, findAssociatedTokenPda, getCreateAssociatedTokenIdempotentInstruction, getTransferCheckedInstruction } from "@solana-program/token";
25
24
  import { address, appendTransactionMessageInstructions, blockhash, compileTransactionMessage, createNoopSigner, createTransactionMessage, getCompiledTransactionMessageEncoder, setTransactionMessageFeePayer, setTransactionMessageLifetimeUsingBlockhash } from "@solana/kit";
26
- // src/controller.ts
27
- /**
28
- * Controller base: a zustand vanilla store plus lifecycle. `update` applies a recipe that must
29
- * return a NEW state object; returning the same reference is a no-op (no set, no notification).
30
- * Persistence and migrations layer on later — this package carries only what its first user needs.
31
- */
32
- var Controller = class {
33
- name;
34
- store;
35
- constructor(options) {
36
- this.name = options.name;
37
- this.store = createStore(options.defaultState);
38
- }
39
- getState() {
40
- return this.store.getState();
41
- }
42
- update(recipe) {
43
- this.store.setState((state) => recipe(state));
44
- }
45
- };
25
+ import { p2wpkh } from "@scure/btc-signer/payment.js";
26
+ import { selectUTXO } from "@scure/btc-signer/utxo.js";
46
27
  // src/events.ts
47
28
  function createEventBus(logger) {
48
29
  const listeners = /* @__PURE__ */ new Map();
@@ -130,330 +111,6 @@ function createMemoryEngineStore(backing) {
130
111
  }
131
112
  };
132
113
  }
133
- // src/connect/errors.ts
134
- /** EIP-1193 / EIP-1474 / EIP-3326 error: `code` is what the page's promise rejects with. */
135
- var ProviderError = class extends Error {
136
- code;
137
- constructor(code, message) {
138
- super(message);
139
- this.name = "ProviderError";
140
- this.code = code;
141
- }
142
- };
143
- const userRejectedRequest = (message = "user rejected the request") => new ProviderError(4001, message);
144
- const unauthorized = (message = "not authorized") => new ProviderError(4100, message);
145
- const unsupportedMethod = (method) => new ProviderError(4200, `${method} is not supported`);
146
- const unrecognizedChain = (message = "unrecognized chain") => new ProviderError(4902, message);
147
- const invalidParams = (message) => new ProviderError(-32602, message);
148
- const requestPending = (message) => new ProviderError(-32002, message);
149
- const internalError = (message) => new ProviderError(-32603, message);
150
- // src/connect/controller.ts
151
- /**
152
- * DApp connections (CAIP-25 style sessions): one session per origin, authorization by network,
153
- * account and method, persisted in the engine store and cleared from memory on lock. A connection
154
- * is approved from a pending queue, by id, like any other request; locking rejects all of it.
155
- */
156
- const COLLECTION$4 = "connections";
157
- /** `lastUsedAt` is rewritten at most this often. */
158
- const TOUCH_INTERVAL_MS = 6e4;
159
- /** Granted for every network a session covers. */
160
- const SESSION_METHODS = [
161
- "eth_sendTransaction",
162
- "personal_sign",
163
- "eth_signTypedData_v4"
164
- ];
165
- const SESSION_NOTIFICATIONS = ["accountsChanged", "chainChanged"];
166
- /** `eip155:1` → 1; `undefined` for anything that is not an EVM network. */
167
- const evmChainId = (network) => {
168
- const match = /^eip155:(\d+)$/.exec(network);
169
- const id = match?.[1] === void 0 ? void 0 : Number(match[1]);
170
- return id !== void 0 && Number.isSafeInteger(id) ? id : void 0;
171
- };
172
- const caip10 = (network, address) => `${network}:${address}`;
173
- const addressOf$1 = (account) => account.slice(account.lastIndexOf(":") + 1);
174
- const isObject$14 = (v) => typeof v === "object" && v !== null;
175
- const isSession = (value) => {
176
- if (!isObject$14(value) || !isObject$14(value["origin"]) || !isObject$14(value["scopes"])) return false;
177
- return typeof value["id"] === "string" && value["origin"]["kind"] === "browser" && typeof value["origin"]["origin"] === "string" && typeof value["currentNetwork"] === "string" && typeof value["createdAt"] === "number" && typeof value["lastUsedAt"] === "number";
178
- };
179
- var ConnectionController = class extends Controller {
180
- options;
181
- engineStore;
182
- waiters = /* @__PURE__ */ new Map();
183
- group;
184
- constructor(options) {
185
- super({
186
- name: "connections",
187
- defaultState: () => ({
188
- sessions: {},
189
- pending: {}
190
- })
191
- });
192
- this.options = options;
193
- }
194
- async init() {
195
- const store = await this.options.openStore();
196
- this.engineStore = store;
197
- this.group = void 0;
198
- const collection = store.collection(COLLECTION$4);
199
- const keys = await collection.list();
200
- const rows = await Promise.all(keys.map(async (key) => collection.get(key)));
201
- const now = this.options.now();
202
- const sessions = {};
203
- const expired = [];
204
- for (const [index, raw] of rows.entries()) {
205
- const key = keys[index];
206
- if (raw === void 0 || key === void 0) continue;
207
- const parsed = JSON.parse(new TextDecoder().decode(raw));
208
- if (!isSession(parsed)) {
209
- this.options.logger.warn("connection session skipped: malformed");
210
- expired.push(key);
211
- } else if (now - parsed.lastUsedAt > 7776e6) expired.push(key);
212
- else sessions[parsed.id] = parsed;
213
- }
214
- await Promise.all(expired.map(async (key) => collection.delete(key)));
215
- this.update(() => ({
216
- sessions,
217
- pending: {}
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.engineStore = void 0;
227
- this.group = void 0;
228
- for (const waiter of this.waiters.values()) waiter.reject(userRejectedRequest("the wallet was locked"));
229
- this.waiters.clear();
230
- this.update(() => ({
231
- sessions: {},
232
- pending: {}
233
- }));
234
- }
235
- /** Throws `4100` unless `origin` is `https://host[:port]` (or localhost in development). */
236
- checkOrigin(origin) {
237
- let url;
238
- try {
239
- url = new URL(origin);
240
- } catch {
241
- throw unauthorized("invalid origin");
242
- }
243
- const localhost = url.protocol === "http:" && url.hostname === "localhost";
244
- if (url.origin !== origin || url.protocol !== "https:" && !(localhost && this.options.allowLocalhost)) throw unauthorized("origin not allowed");
245
- return {
246
- kind: "browser",
247
- origin
248
- };
249
- }
250
- session(origin) {
251
- return Object.values(this.getState().sessions).find((s) => s.origin.origin === origin);
252
- }
253
- pending() {
254
- return Object.values(this.getState().pending);
255
- }
256
- /** The group sessions are bound to: the host's last `setActiveGroup`, else the app's selection. */
257
- activeGroup() {
258
- return this.group ?? this.options.selectedGroup();
259
- }
260
- /** Whether `network` is an EVM network the wallet has enabled. */
261
- isEnabled(network) {
262
- return this.options.enabledNetworks().includes(network);
263
- }
264
- /** The origin's authorized addresses on its current network; empty when not connected. */
265
- accounts(origin) {
266
- const session = this.session(origin);
267
- return session?.scopes[session.currentNetwork]?.accounts.map(addressOf$1) ?? [];
268
- }
269
- /** Throws `4100` unless the origin's session covers `method` on `network`. */
270
- authorize(origin, network, method) {
271
- const session = this.session(origin);
272
- const scope = session?.scopes[network];
273
- if (session === void 0 || scope === void 0 || !scope.methods.includes(method)) throw unauthorized();
274
- return session;
275
- }
276
- /** Resolves with the session once the host approves; rejects with `4001` when it refuses. */
277
- async request(origin, kind, network) {
278
- if (this.engineStore === void 0) throw userRejectedRequest("the wallet is locked");
279
- if (this.pending().some((p) => p.origin.origin === origin)) throw requestPending("a connection request is already pending");
280
- const id = `conn-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
281
- const entry = {
282
- id,
283
- origin: {
284
- kind: "browser",
285
- origin
286
- },
287
- kind,
288
- ...network === void 0 ? {} : { network },
289
- createdAt: this.options.now()
290
- };
291
- return new Promise((resolve, reject) => {
292
- this.waiters.set(id, {
293
- resolve,
294
- reject
295
- });
296
- this.update((s) => ({
297
- ...s,
298
- pending: {
299
- ...s.pending,
300
- [id]: entry
301
- }
302
- }));
303
- });
304
- }
305
- /**
306
- * The host's approval, by id: the accounts granted (EVM addresses of the active group) and the
307
- * network.
308
- */
309
- async approveConnection(id, grant) {
310
- const store = this.requireStore();
311
- const entry = this.getState().pending[id];
312
- const waiter = this.waiters.get(id);
313
- if (entry === void 0 || waiter === void 0) throw new Error(`unknown connection request ${id}`);
314
- if (entry.kind === "network" && entry.network !== grant.network) throw new Error(`connection request ${id} is for ${String(entry.network)}`);
315
- if (evmChainId(grant.network) === void 0 || !this.options.enabledNetworks().includes(grant.network)) throw invalidParams(`${grant.network} is not an enabled EVM network`);
316
- const group = this.activeGroup();
317
- if (group === void 0) throw new Error("no account group is selected");
318
- const own = (await this.options.evmAddress(group, grant.network)).toLowerCase();
319
- if (grant.accounts.length === 0 || grant.accounts.some((a) => a.toLowerCase() !== own)) throw invalidParams("only the active group's account can be granted");
320
- if (this.getState().pending[id] === void 0) throw new Error(`connection request ${id} is no longer pending`);
321
- const now = this.options.now();
322
- const existing = this.session(entry.origin.origin);
323
- const scope = {
324
- accounts: [caip10(grant.network, own)],
325
- methods: SESSION_METHODS,
326
- notifications: SESSION_NOTIFICATIONS
327
- };
328
- const session = {
329
- id: existing?.id ?? `session-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`,
330
- origin: entry.origin,
331
- scopes: {
332
- ...existing?.scopes,
333
- [grant.network]: scope
334
- },
335
- currentNetwork: grant.network,
336
- createdAt: existing?.createdAt ?? now,
337
- lastUsedAt: now
338
- };
339
- await this.persist(store, session);
340
- this.dropPending(id);
341
- if (existing !== void 0 && existing.currentNetwork !== grant.network) this.options.invalidate(entry.origin.origin);
342
- waiter.resolve(session);
343
- return session;
344
- }
345
- rejectConnection(id) {
346
- const waiter = this.waiters.get(id);
347
- if (this.getState().pending[id] === void 0 || waiter === void 0) throw new Error(`unknown connection request ${id}`);
348
- this.dropPending(id);
349
- waiter.reject(userRejectedRequest());
350
- }
351
- /** Ends the origin's session; its pending connection and unfinished requests are void. */
352
- async revoke(origin) {
353
- const store = this.requireStore();
354
- for (const p of this.pending().filter((x) => x.origin.origin === origin)) {
355
- const waiter = this.waiters.get(p.id);
356
- this.dropPending(p.id);
357
- waiter?.reject(userRejectedRequest("the connection was revoked"));
358
- }
359
- const session = this.session(origin);
360
- if (session !== void 0) {
361
- await store.collection(COLLECTION$4).delete(session.id);
362
- this.update((s) => {
363
- const { [session.id]: _gone, ...sessions } = s.sessions;
364
- return {
365
- ...s,
366
- sessions
367
- };
368
- });
369
- }
370
- this.options.invalidate(origin);
371
- }
372
- /** Switches within the session's scope; the origin's unfinished requests are void. */
373
- async setCurrentNetwork(origin, network) {
374
- const store = this.requireStore();
375
- const session = this.session(origin);
376
- if (session === void 0 || session.scopes[network] === void 0) throw unauthorized();
377
- await this.persist(store, {
378
- ...session,
379
- currentNetwork: network
380
- });
381
- this.options.invalidate(origin);
382
- }
383
- async touch(origin) {
384
- const store = this.engineStore;
385
- const session = this.session(origin);
386
- const now = this.options.now();
387
- if (store === void 0 || session === void 0 || now - session.lastUsedAt < TOUCH_INTERVAL_MS) return;
388
- await this.persist(store, {
389
- ...session,
390
- lastUsedAt: now
391
- });
392
- }
393
- /**
394
- * The host switched account group: every session's accounts become the new group's addresses. A
395
- * session that cannot get one (no address derivable) is left with an empty list and has to be
396
- * authorized again.
397
- */
398
- async setActiveGroup(walletId, groupIndex) {
399
- const store = this.requireStore();
400
- const group = {
401
- walletId,
402
- groupIndex
403
- };
404
- this.group = group;
405
- await Promise.all(Object.values(this.getState().sessions).map(async (session) => {
406
- const entries = await Promise.all(Object.entries(session.scopes).map(async ([network, scope]) => {
407
- if (scope.accounts.length === 0) return [network, scope];
408
- try {
409
- const address = await this.options.evmAddress(group, network);
410
- return [network, {
411
- ...scope,
412
- accounts: [caip10(network, address.toLowerCase())]
413
- }];
414
- } catch (error) {
415
- this.options.logger.warn("connection account unavailable in the new group", error);
416
- return [network, {
417
- ...scope,
418
- accounts: []
419
- }];
420
- }
421
- }));
422
- await this.persist(store, {
423
- ...session,
424
- scopes: Object.fromEntries(entries)
425
- });
426
- }));
427
- }
428
- dropPending(id) {
429
- this.waiters.delete(id);
430
- this.update((s) => {
431
- const { [id]: _gone, ...pending } = s.pending;
432
- return {
433
- ...s,
434
- pending
435
- };
436
- });
437
- }
438
- async persist(store, session) {
439
- try {
440
- await store.collection(COLLECTION$4).put(session.id, new TextEncoder().encode(JSON.stringify(session)));
441
- } catch (error) {
442
- throw internalError(error instanceof Error ? error.message : String(error));
443
- }
444
- this.update((s) => ({
445
- ...s,
446
- sessions: {
447
- ...s.sessions,
448
- [session.id]: session
449
- }
450
- }));
451
- }
452
- requireStore() {
453
- if (this.engineStore === void 0) throw userRejectedRequest("the wallet is locked");
454
- return this.engineStore;
455
- }
456
- };
457
114
  // src/addresses/normalize.ts
458
115
  /**
459
116
  * The canonical form of `address` for its family — EIP-55 for EVM, the re-encoded form for bitcoin
@@ -605,6 +262,7 @@ async function preparePay(context, params) {
605
262
  kind: "lightning",
606
263
  amountSats,
607
264
  maxFeeSats,
265
+ ...params.amountFromServiceMinimum === true ? { amountFromServiceMinimum: true } : {},
608
266
  receiver: payee,
609
267
  ...option.description === void 0 ? {} : { description: option.description }
610
268
  },
@@ -651,6 +309,7 @@ async function preparePay(context, params) {
651
309
  kind: "lightning",
652
310
  amountSats,
653
311
  maxFeeSats,
312
+ ...params.amountFromServiceMinimum === true ? { amountFromServiceMinimum: true } : {},
654
313
  receiver: payee,
655
314
  description: request.description
656
315
  },
@@ -754,7 +413,7 @@ async function prepareZap(params, context) {
754
413
  pubkey: await params.signer.getPublicKey()
755
414
  };
756
415
  const zapRequest = await params.signer.signEvent(unsigned);
757
- if (!verifyEvent(zapRequest) || !signedMatchesUnsigned(zapRequest, unsigned)) throw new PaymentError("rejected", "signer returned a zap request that does not match");
416
+ if (!context.verifyEvent(zapRequest) || !signedMatchesUnsigned(zapRequest, unsigned)) throw new PaymentError("rejected", "signer returned a zap request that does not match");
758
417
  const { invoice } = await requestInvoice(resolved, {
759
418
  fetch: context.fetch,
760
419
  network: params.network,
@@ -978,6 +637,8 @@ const METHODS = /* @__PURE__ */ new Set([
978
637
  "pay",
979
638
  "zap",
980
639
  "evm-sign",
640
+ "nostr-sign",
641
+ "webln-invoice",
981
642
  "spark-deposit",
982
643
  "spark-exit"
983
644
  ]);
@@ -997,6 +658,8 @@ const isAccount = (value) => {
997
658
  if (!isObject$13(value)) return false;
998
659
  if (value["kind"] === "hd") return typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["template"] === "string";
999
660
  if (value["kind"] === "imported") return typeof value["keyId"] === "string" && FAMILIES.has(value["family"]);
661
+ if (value["kind"] === "derived") return typeof value["walletId"] === "string" && typeof value["index"] === "number";
662
+ if (value["kind"] === void 0 && typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["address"] === "string") return true;
1000
663
  return value["kind"] === void 0 && typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["network"] === "string";
1001
664
  };
1002
665
  const isOrigin = (value) => isObject$13(value) && (value["kind"] === "internal" || value["kind"] === "browser" && typeof value["origin"] === "string");
@@ -1064,6 +727,27 @@ var OriginBusyError = class extends Error {
1064
727
  /** Requests expire this long after creation. */
1065
728
  const REQUEST_TTL_MS = 6e5;
1066
729
  const originKey = (origin) => `origin:${origin.origin}`;
730
+ /** The input's browser origin, when it carries one (`evm-sign`/`nostr-sign`/`webln-invoice`/`pay`). */
731
+ const solanaDecode = (account, network, message) => {
732
+ try {
733
+ const request = normalizeSolana({
734
+ kind: "solana.transaction",
735
+ network,
736
+ account: {
737
+ kind: "hd",
738
+ walletId: account.walletId,
739
+ groupIndex: account.groupIndex,
740
+ template: "solana.bip44-change"
741
+ },
742
+ message
743
+ }, account.address);
744
+ if (request.kind === "solana.transaction") return decodeSolana(request, account.address, void 0);
745
+ return;
746
+ } catch (error) {
747
+ return { error: errorMessage(error) };
748
+ }
749
+ };
750
+ const browserOriginOf = (input) => "origin" in input ? input.origin : void 0;
1067
751
  const LIVE = /* @__PURE__ */ new Set(["awaiting-approval", "signing"]);
1068
752
  const errorMessage = (error) => error instanceof Error ? error.message : String(error);
1069
753
  var RequestController = class extends Controller {
@@ -1120,9 +804,10 @@ var RequestController = class extends Controller {
1120
804
  const { session } = this;
1121
805
  const id = newRequestId(this.options.random);
1122
806
  const target = "txId" in input ? input.txId : void 0;
1123
- if (input.method === "evm-sign") {
1124
- const key = originKey(input.origin);
1125
- if (this.targets.has(key)) throw new OriginBusyError(input.origin.origin);
807
+ const browserOrigin = browserOriginOf(input);
808
+ if (browserOrigin !== void 0) {
809
+ const key = originKey(browserOrigin);
810
+ if (this.targets.has(key)) throw new OriginBusyError(browserOrigin.origin);
1126
811
  this.targets.set(key, id);
1127
812
  }
1128
813
  if (target !== void 0) {
@@ -1145,7 +830,7 @@ var RequestController = class extends Controller {
1145
830
  const createdAt = this.options.now();
1146
831
  const request = {
1147
832
  id,
1148
- origin: input.method === "evm-sign" ? input.origin : { kind: "internal" },
833
+ origin: browserOrigin ?? { kind: "internal" },
1149
834
  method: input.method,
1150
835
  account: built.account,
1151
836
  network: built.network,
@@ -1211,6 +896,7 @@ var RequestController = class extends Controller {
1211
896
  checks: collectChecks(action.checks),
1212
897
  risk: this.sparkRisk(action.display),
1213
898
  run: {
899
+ factor: "required",
1214
900
  staleReason: () => action.staleReason(this.options.now()),
1215
901
  submit: async (verify) => action.execute(this.options.spark, verify),
1216
902
  release: () => void 0
@@ -1249,7 +935,10 @@ var RequestController = class extends Controller {
1249
935
  display: prepared.intent,
1250
936
  checks: collectChecks([prepared.intent.verifiability === "full" ? void 0 : "decode-partial", ...prepared.checks]),
1251
937
  risk: [],
1252
- run: prepared
938
+ run: {
939
+ ...prepared,
940
+ factor: "required"
941
+ }
1253
942
  };
1254
943
  }
1255
944
  if (input.method === "spark-exit") {
@@ -1279,9 +968,79 @@ var RequestController = class extends Controller {
1279
968
  display: prepared.intent,
1280
969
  checks: collectChecks([isTransaction && prepared.intent.verifiability !== "full" ? "decode-partial" : void 0, ...prepared.checks]),
1281
970
  risk: isTransaction ? this.chainRisk(prepared.intent) : [],
1282
- run: prepared
971
+ run: {
972
+ ...prepared,
973
+ factor: "required"
974
+ }
975
+ };
976
+ }
977
+ if (input.method === "solana-sign") {
978
+ const txs = input.request.kind === "transactions" ? input.request.transactions : [];
979
+ return {
980
+ account: input.account,
981
+ network: input.network,
982
+ display: {
983
+ kind: "solana.sign",
984
+ send: input.request.kind === "transactions" ? input.request.send : false,
985
+ count: txs.length === 0 ? 1 : txs.length,
986
+ transactions: txs.map((tx) => solanaDecode(input.account, input.network, tx))
987
+ },
988
+ checks: [],
989
+ risk: [],
990
+ run: {
991
+ factor: "required",
992
+ staleReason: () => void 0,
993
+ submit: async (verify) => this.options.solanaSign(input.account, input.network, input.request, verify),
994
+ release: () => void 0
995
+ }
1283
996
  };
1284
997
  }
998
+ if (input.method === "webln-invoice") return {
999
+ account: input.ref,
1000
+ network: "",
1001
+ display: {
1002
+ kind: "lightning.invoice",
1003
+ amountSats: input.amountSats,
1004
+ ...input.memo === void 0 ? {} : { memo: input.memo }
1005
+ },
1006
+ checks: [],
1007
+ risk: [],
1008
+ run: {
1009
+ factor: "none",
1010
+ staleReason: () => void 0,
1011
+ submit: async () => {
1012
+ return {
1013
+ kind: "lightning.invoice",
1014
+ paymentRequest: (await this.options.spark.createInvoice(input.ref, {
1015
+ amountSats: input.amountSats,
1016
+ ...input.memo === void 0 ? {} : { memo: input.memo }
1017
+ })).invoice
1018
+ };
1019
+ },
1020
+ release: () => void 0
1021
+ }
1022
+ };
1023
+ if (input.method === "nostr-sign") return {
1024
+ account: input.ref,
1025
+ network: "",
1026
+ display: {
1027
+ kind: "nostr.event",
1028
+ eventKind: input.event.kind,
1029
+ preview: input.event.content.slice(0, 280),
1030
+ tagCount: input.event.tags.length
1031
+ },
1032
+ checks: [],
1033
+ risk: [],
1034
+ run: {
1035
+ factor: "none",
1036
+ staleReason: () => void 0,
1037
+ submit: async () => ({
1038
+ kind: "nostr.event",
1039
+ event: await this.options.nostrSign(input.ref, input.event)
1040
+ }),
1041
+ release: () => void 0
1042
+ }
1043
+ };
1285
1044
  const prepared = input.method === "send" ? await this.options.transactions.prepareSend(input, id) : await this.options.transactions.prepareReplacement(input, id);
1286
1045
  return {
1287
1046
  account: prepared.account,
@@ -1289,7 +1048,10 @@ var RequestController = class extends Controller {
1289
1048
  display: prepared.intent,
1290
1049
  checks: collectChecks([prepared.intent.verifiability === "full" ? void 0 : "decode-partial", ...prepared.checks]),
1291
1050
  risk: input.method === "send" ? this.chainRisk(prepared.intent) : [],
1292
- run: prepared
1051
+ run: {
1052
+ ...prepared,
1053
+ factor: "required"
1054
+ }
1293
1055
  };
1294
1056
  }
1295
1057
  async approve(id, method, verify) {
@@ -1319,7 +1081,7 @@ var RequestController = class extends Controller {
1319
1081
  throw new Error(stale);
1320
1082
  }
1321
1083
  try {
1322
- const result = await entry.prepared.submit(verify);
1084
+ const result = entry.prepared.factor === "none" ? await entry.prepared.submit() : await entry.prepared.submit(this.requireVerify(verify));
1323
1085
  if (session === this.session) {
1324
1086
  entry.stopTimer();
1325
1087
  this.entries.delete(id);
@@ -1330,7 +1092,7 @@ var RequestController = class extends Controller {
1330
1092
  ..."id" in result ? { txId: result.id } : {}
1331
1093
  };
1332
1094
  this.put(done);
1333
- this.record(done, "submitted");
1095
+ this.record(done, "submitted", void 0, result);
1334
1096
  } else this.record(request, "submitted");
1335
1097
  this.settle(id, result);
1336
1098
  return result;
@@ -1355,6 +1117,11 @@ var RequestController = class extends Controller {
1355
1117
  if (request.stage !== "awaiting-approval") throw new Error(`request ${id} is ${request.stage}, not awaiting approval`);
1356
1118
  this.finish(id, "rejected");
1357
1119
  }
1120
+ /** `approve` for a factor-required run: a missing factor is invalid input. */
1121
+ requireVerify(verify) {
1122
+ if (verify === void 0) throw new WalletError("invalid-input", "a verification factor is required");
1123
+ return verify;
1124
+ }
1358
1125
  requireRequest(id) {
1359
1126
  const request = this.getState().requests[id];
1360
1127
  if (request === void 0) throw new Error(`unknown request ${id}`);
@@ -1398,8 +1165,10 @@ var RequestController = class extends Controller {
1398
1165
  }
1399
1166
  }
1400
1167
  /** Appends the final stage to the signature record; a failed write is a warning, not an error. */
1401
- record(request, outcome, error) {
1168
+ record(request, outcome, error, result) {
1402
1169
  const { display } = request;
1170
+ const eventId = result !== void 0 && "kind" in result && result.kind === "nostr.event" ? result.event.id : void 0;
1171
+ const summary = "kind" in display && display.kind === "nostr.event" ? `nostr kind ${display.eventKind}${eventId === void 0 ? "" : ` ${eventId}`}` : "kind" in display && display.kind === "lightning.invoice" ? `lightning invoice ${display.amountSats} sats` : "kind" in display && display.kind === "solana.sign" ? display.transactions.length === 0 ? "solana message" : `solana ${display.send ? "send" : "sign"} ${String(display.count)} tx` : "summary" in display ? display.summary : `${display.kind} ${display.amountSats}`;
1403
1172
  const entry = {
1404
1173
  id: request.id,
1405
1174
  at: this.options.now(),
@@ -1407,7 +1176,7 @@ var RequestController = class extends Controller {
1407
1176
  method: request.method,
1408
1177
  account: request.account,
1409
1178
  network: request.network,
1410
- summary: "summary" in display ? display.summary : `${display.kind} ${display.amountSats}`,
1179
+ summary,
1411
1180
  verification: request.verification,
1412
1181
  checks: request.checks,
1413
1182
  risk: request.risk,
@@ -1712,11 +1481,19 @@ function diffSessions(before, after) {
1712
1481
  accounts: currentAccounts(now)
1713
1482
  });
1714
1483
  }
1715
- for (const [origin, session] of next) if (!prev.has(origin)) events.push({
1716
- name: "connect",
1717
- origin,
1718
- chainId: hexChainId(session.currentNetwork)
1719
- });
1484
+ for (const [origin, session] of next) if (!prev.has(origin)) {
1485
+ events.push({
1486
+ name: "connect",
1487
+ origin,
1488
+ chainId: hexChainId(session.currentNetwork)
1489
+ });
1490
+ const accounts = currentAccounts(session);
1491
+ if (accounts.length > 0) events.push({
1492
+ name: "accountsChanged",
1493
+ origin,
1494
+ accounts
1495
+ });
1496
+ }
1720
1497
  return events;
1721
1498
  }
1722
1499
  // src/addresses/errors.ts
@@ -3944,86 +3721,270 @@ function idFromName(name) {
3944
3721
  const id = name.slice(19, name.length - 5);
3945
3722
  return /^[0-9a-f]{32}$/.test(id) ? id : void 0;
3946
3723
  }
3947
- const NAME_MAX = 24;
3948
- const PUBKEY_RE = /^[0-9a-f]{64}$/;
3949
- const KNOWN_DOC_KEYS = /* @__PURE__ */ new Set([
3950
- "v",
3951
- "wallet",
3952
- "groups",
3953
- "contacts"
3954
- ]);
3955
- const KNOWN_WALLET_KEYS = /* @__PURE__ */ new Set(["name", "updatedAt"]);
3956
- const KNOWN_GROUP_KEYS = /* @__PURE__ */ new Set([
3957
- "index",
3958
- "name",
3959
- "hidden",
3960
- "boundPubkey",
3961
- "updatedAt"
3962
- ]);
3963
- const isObject$7 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3964
- const isNonNegativeInt = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
3965
- const validName = (v) => v === void 0 || typeof v === "string" && v.trim().length > 0 && v.trim().length <= NAME_MAX;
3966
- const trimmedName = (v) => typeof v === "string" ? v.trim() : void 0;
3967
- /**
3968
- * Strict decode — any malformed shape, unknown key, duplicate index or id, or invalid contact
3969
- * returns `undefined`; only `v: 2` is read.
3970
- */
3971
- function decodeMetaDoc(value) {
3972
- if (!isObject$7(value)) return;
3973
- for (const k of Object.keys(value)) if (!KNOWN_DOC_KEYS.has(k)) return;
3974
- if (value["v"] !== 2) return;
3975
- const { wallet } = value;
3976
- if (!isObject$7(wallet)) return;
3977
- for (const k of Object.keys(wallet)) if (!KNOWN_WALLET_KEYS.has(k)) return;
3978
- if (!validName(wallet["name"]) || !isNonNegativeInt(wallet["updatedAt"])) return;
3979
- const { groups } = value;
3980
- if (!Array.isArray(groups)) return;
3981
- const seen = /* @__PURE__ */ new Set();
3982
- const out = [];
3983
- for (const item of groups) {
3984
- if (!isObject$7(item)) return;
3985
- for (const k of Object.keys(item)) if (!KNOWN_GROUP_KEYS.has(k)) return;
3986
- const { index } = item;
3987
- if (!isNonNegativeInt(index) || seen.has(index)) return;
3988
- seen.add(index);
3989
- if (!validName(item["name"]) || item["hidden"] !== true && item["hidden"] !== false) return;
3990
- const { boundPubkey } = item;
3991
- if (boundPubkey !== void 0 && (typeof boundPubkey !== "string" || !PUBKEY_RE.test(boundPubkey))) return;
3992
- if (!isNonNegativeInt(item["updatedAt"])) return;
3993
- const gName = trimmedName(item["name"]);
3994
- out.push({
3995
- index,
3996
- hidden: item["hidden"],
3997
- updatedAt: item["updatedAt"],
3998
- ...gName === void 0 ? {} : { name: gName },
3999
- ...boundPubkey === void 0 ? {} : { boundPubkey }
4000
- });
4001
- }
4002
- out.sort((a, b) => a.index - b.index);
4003
- const { contacts } = value;
4004
- if (!Array.isArray(contacts) || contacts.length > 128) return;
4005
- const records = /* @__PURE__ */ new Map();
4006
- for (const item of contacts) {
4007
- const record = decodeRecord(item);
4008
- if (record === void 0 || records.has(record.id)) return;
4009
- records.set(record.id, record);
3724
+ PROGRAM_IDS.token2022;
3725
+ const MAX_MESSAGE_BYTES = 1232;
3726
+ const CU_SIMULATE_LIMIT = 14e5;
3727
+ const b64 = (bytes) => base64.encode(bytes);
3728
+ const isObject$7 = (v) => typeof v === "object" && v !== null;
3729
+ const obj$1 = (v) => isObject$7(v) ? v : void 0;
3730
+ const str = (v, fallback = "0") => {
3731
+ if (typeof v === "string") return v;
3732
+ return typeof v === "number" || typeof v === "bigint" ? String(v) : fallback;
3733
+ };
3734
+ var SolanaChainAdapter = class {
3735
+ async rpc(rpc, method, params) {
3736
+ return rpc.call(method, params);
4010
3737
  }
4011
- const name = trimmedName(wallet["name"]);
4012
- return {
4013
- v: 2,
4014
- contacts: [...records.values()].sort((a, b) => a.id < b.id ? -1 : 1),
4015
- wallet: {
4016
- updatedAt: wallet["updatedAt"],
4017
- ...name === void 0 ? {} : { name }
4018
- },
4019
- groups: out
4020
- };
4021
- }
4022
- /** UTF-8 JSON — `undefined` when the document exceeds the 64 KB limit. */
4023
- function encodeMetaDoc(doc) {
4024
- const bytes = new TextEncoder().encode(JSON.stringify(doc));
4025
- return bytes.byteLength <= 65536 ? bytes : void 0;
4026
- }
3738
+ async instructions(rpc, from, intent) {
3739
+ if (intent.kind === "sol") return [getTransferSolInstruction({
3740
+ source: createNoopSigner(address(from)),
3741
+ destination: address(intent.to),
3742
+ amount: intent.lamports
3743
+ })];
3744
+ const tokenProgram = intent.tokenProgram === void 0 ? TOKEN_PROGRAM_ADDRESS : address(intent.tokenProgram);
3745
+ const [sourceAta] = await findAssociatedTokenPda({
3746
+ mint: address(intent.mint),
3747
+ owner: address(from),
3748
+ tokenProgram
3749
+ });
3750
+ const [destAta] = await findAssociatedTokenPda({
3751
+ mint: address(intent.mint),
3752
+ owner: address(intent.to),
3753
+ tokenProgram
3754
+ });
3755
+ const ixs = [];
3756
+ const destInfo = await this.rpc(rpc, "getAccountInfo", [destAta, {
3757
+ encoding: "base64",
3758
+ commitment: "confirmed"
3759
+ }]);
3760
+ if (obj$1(obj$1(destInfo)?.["value"]) === void 0) ixs.push(getCreateAssociatedTokenIdempotentInstruction({
3761
+ ata: destAta,
3762
+ mint: address(intent.mint),
3763
+ owner: address(intent.to),
3764
+ payer: createNoopSigner(address(from)),
3765
+ tokenProgram
3766
+ }));
3767
+ ixs.push(getTransferCheckedInstruction({
3768
+ source: sourceAta,
3769
+ mint: address(intent.mint),
3770
+ destination: destAta,
3771
+ authority: address(from),
3772
+ amount: intent.amount,
3773
+ decimals: intent.decimals
3774
+ }, { programAddress: tokenProgram }));
3775
+ return ixs;
3776
+ }
3777
+ /** Instruction set, simulated compute units, and a fresh blockhash — fee fields come later. */
3778
+ async build(rpc, network, from, intent) {
3779
+ const instructions = await this.instructions(rpc, from, intent);
3780
+ const hashResult = obj$1(await this.rpc(rpc, "getLatestBlockhash", [{ commitment: "confirmed" }]));
3781
+ const value = obj$1(hashResult?.["value"]);
3782
+ const blockhashValue = typeof value?.["blockhash"] === "string" ? value["blockhash"] : "";
3783
+ const lastValidBlockHeight = BigInt(str(value?.["lastValidBlockHeight"], "0"));
3784
+ const compiled = this.compile(from, instructions, blockhashValue, lastValidBlockHeight);
3785
+ const units = await this.simulate(rpc, compiled.messageBytes);
3786
+ return {
3787
+ family: "solana",
3788
+ network,
3789
+ from,
3790
+ instructions,
3791
+ writable: this.writableAccounts(instructions),
3792
+ unitsConsumed: units,
3793
+ blockhash: blockhashValue,
3794
+ lastValidBlockHeight
3795
+ };
3796
+ }
3797
+ writableAccounts(instructions) {
3798
+ const out = /* @__PURE__ */ new Set();
3799
+ for (const ix of instructions) {
3800
+ const accounts = obj$1(ix)?.["accounts"];
3801
+ if (!Array.isArray(accounts)) continue;
3802
+ for (const a of accounts) {
3803
+ const record = obj$1(a);
3804
+ const role = Number(record?.["role"] ?? 0);
3805
+ if (typeof record?.["address"] === "string" && role >= 2) out.add(record["address"]);
3806
+ }
3807
+ }
3808
+ return [...out];
3809
+ }
3810
+ /** Unsigned wire bytes: shortvec(1) sig count + 64-byte zero sig + message (for simulate). */
3811
+ wireBytes(messageBytes) {
3812
+ const out = new Uint8Array(65 + messageBytes.length);
3813
+ out[0] = 1;
3814
+ out.set(messageBytes, 65);
3815
+ return out;
3816
+ }
3817
+ async simulate(rpc, messageBytes) {
3818
+ const result = obj$1(await this.rpc(rpc, "simulateTransaction", [b64(this.wireBytes(messageBytes)), {
3819
+ encoding: "base64",
3820
+ sigVerify: false,
3821
+ replaceRecentBlockhash: false
3822
+ }]));
3823
+ const value = obj$1(result?.["value"]);
3824
+ const units = Number(value?.["unitsConsumed"] ?? 0);
3825
+ return units > 0 ? units : CU_SIMULATE_LIMIT;
3826
+ }
3827
+ compile(from, instructions, blockhashValue, lastValidBlockHeight) {
3828
+ const message = createTransactionMessage({ version: 0 });
3829
+ const withPayer = setTransactionMessageFeePayer(address(from), message);
3830
+ const withLifetime = setTransactionMessageLifetimeUsingBlockhash({
3831
+ blockhash: blockhash(blockhashValue),
3832
+ lastValidBlockHeight
3833
+ }, withPayer);
3834
+ const withIxs = appendTransactionMessageInstructions([...instructions], withLifetime);
3835
+ const compiled = compileTransactionMessage(withIxs);
3836
+ const messageBytes = new Uint8Array(getCompiledTransactionMessageEncoder().encode(compiled));
3837
+ if (messageBytes.length > MAX_MESSAGE_BYTES) throw new Error(`compiled message is ${messageBytes.length} bytes (max ${MAX_MESSAGE_BYTES})`);
3838
+ return {
3839
+ messageBytes,
3840
+ instructions
3841
+ };
3842
+ }
3843
+ /** Percentile-tiered prioritization fees over the writable accounts of this transaction. */
3844
+ async estimateFee(rpc, writable) {
3845
+ const result = await this.rpc(rpc, "getRecentPrioritizationFees", [[...writable]]);
3846
+ const fees = (Array.isArray(result) ? result : []).flatMap((r) => {
3847
+ const fee = obj$1(r)?.["prioritizationFee"];
3848
+ return fee === void 0 ? [] : [Number(fee)];
3849
+ }).sort((a, b) => a - b);
3850
+ const pick = (p) => BigInt(fees[Math.min(fees.length - 1, Math.floor(fees.length * p / 100))] ?? 0);
3851
+ return [
3852
+ {
3853
+ tier: "slow",
3854
+ microLamportsPerCu: pick(50)
3855
+ },
3856
+ {
3857
+ tier: "normal",
3858
+ microLamportsPerCu: pick(75)
3859
+ },
3860
+ {
3861
+ tier: "fast",
3862
+ microLamportsPerCu: pick(90)
3863
+ }
3864
+ ];
3865
+ }
3866
+ /** Prepend CU-limit + CU-price budget instructions; returns message bytes for the sign request. */
3867
+ applyFee(tx, fee) {
3868
+ const units = Math.ceil((tx.unitsConsumed === 0 ? CU_SIMULATE_LIMIT : tx.unitsConsumed) * 1.1);
3869
+ return this.compile(tx.from, [
3870
+ getSetComputeUnitLimitInstruction({ units }),
3871
+ getSetComputeUnitPriceInstruction({ microLamports: fee.microLamportsPerCu }),
3872
+ ...tx.instructions
3873
+ ], tx.blockhash, tx.lastValidBlockHeight).messageBytes;
3874
+ }
3875
+ /** Wire transaction bytes — sigCount shortvec + each 64-byte sig + message. */
3876
+ finalize(messageBytes, signatures) {
3877
+ for (const sig of signatures) if (sig.length !== 64) throw new Error(`solana signature must be 64 bytes, got ${sig.length}`);
3878
+ const out = new Uint8Array(1 + 64 * signatures.length + messageBytes.length);
3879
+ out[0] = signatures.length;
3880
+ for (const [i, sig] of signatures.entries()) out.set(sig, 1 + 64 * i);
3881
+ out.set(messageBytes, 1 + 64 * signatures.length);
3882
+ return out;
3883
+ }
3884
+ async broadcast(rpc, wireBytes) {
3885
+ const result = await this.rpc(rpc, "sendTransaction", [b64(wireBytes), {
3886
+ encoding: "base64",
3887
+ skipPreflight: false,
3888
+ maxRetries: 0,
3889
+ preflightCommitment: "confirmed"
3890
+ }]);
3891
+ if (typeof result !== "string") throw new TypeError("sendTransaction returned a malformed signature");
3892
+ return result;
3893
+ }
3894
+ /** Processed → confirmed → finalized; an error on the status means the tx failed on-chain. */
3895
+ async status(rpc, signature) {
3896
+ const result = obj$1(await this.rpc(rpc, "getSignatureStatuses", [[signature], { searchTransactionHistory: true }]));
3897
+ const entry = Array.isArray(result?.["value"]) ? obj$1(result["value"][0]) : void 0;
3898
+ if (entry === void 0) return "pending";
3899
+ if (entry["err"] !== null && entry["err"] !== void 0) return "failed";
3900
+ const c = entry["confirmationStatus"];
3901
+ return c === "finalized" ? "finalized" : c === "confirmed" ? "confirmed" : "pending";
3902
+ }
3903
+ async blockHeight(rpc) {
3904
+ const result = await this.rpc(rpc, "getBlockHeight", [{ commitment: "confirmed" }]);
3905
+ return BigInt(str(result, "0"));
3906
+ }
3907
+ };
3908
+ const NAME_MAX = 24;
3909
+ const PUBKEY_RE = /^[0-9a-f]{64}$/;
3910
+ const KNOWN_DOC_KEYS = /* @__PURE__ */ new Set([
3911
+ "v",
3912
+ "wallet",
3913
+ "groups",
3914
+ "contacts"
3915
+ ]);
3916
+ const KNOWN_WALLET_KEYS = /* @__PURE__ */ new Set(["name", "updatedAt"]);
3917
+ const KNOWN_GROUP_KEYS = /* @__PURE__ */ new Set([
3918
+ "index",
3919
+ "name",
3920
+ "hidden",
3921
+ "boundPubkey",
3922
+ "updatedAt"
3923
+ ]);
3924
+ const isObject$6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3925
+ const isNonNegativeInt = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
3926
+ const validName = (v) => v === void 0 || typeof v === "string" && v.trim().length > 0 && v.trim().length <= NAME_MAX;
3927
+ const trimmedName = (v) => typeof v === "string" ? v.trim() : void 0;
3928
+ /**
3929
+ * Strict decode — any malformed shape, unknown key, duplicate index or id, or invalid contact
3930
+ * returns `undefined`; only `v: 2` is read.
3931
+ */
3932
+ function decodeMetaDoc(value) {
3933
+ if (!isObject$6(value)) return;
3934
+ for (const k of Object.keys(value)) if (!KNOWN_DOC_KEYS.has(k)) return;
3935
+ if (value["v"] !== 2) return;
3936
+ const { wallet } = value;
3937
+ if (!isObject$6(wallet)) return;
3938
+ for (const k of Object.keys(wallet)) if (!KNOWN_WALLET_KEYS.has(k)) return;
3939
+ if (!validName(wallet["name"]) || !isNonNegativeInt(wallet["updatedAt"])) return;
3940
+ const { groups } = value;
3941
+ if (!Array.isArray(groups)) return;
3942
+ const seen = /* @__PURE__ */ new Set();
3943
+ const out = [];
3944
+ for (const item of groups) {
3945
+ if (!isObject$6(item)) return;
3946
+ for (const k of Object.keys(item)) if (!KNOWN_GROUP_KEYS.has(k)) return;
3947
+ const { index } = item;
3948
+ if (!isNonNegativeInt(index) || seen.has(index)) return;
3949
+ seen.add(index);
3950
+ if (!validName(item["name"]) || item["hidden"] !== true && item["hidden"] !== false) return;
3951
+ const { boundPubkey } = item;
3952
+ if (boundPubkey !== void 0 && (typeof boundPubkey !== "string" || !PUBKEY_RE.test(boundPubkey))) return;
3953
+ if (!isNonNegativeInt(item["updatedAt"])) return;
3954
+ const gName = trimmedName(item["name"]);
3955
+ out.push({
3956
+ index,
3957
+ hidden: item["hidden"],
3958
+ updatedAt: item["updatedAt"],
3959
+ ...gName === void 0 ? {} : { name: gName },
3960
+ ...boundPubkey === void 0 ? {} : { boundPubkey }
3961
+ });
3962
+ }
3963
+ out.sort((a, b) => a.index - b.index);
3964
+ const { contacts } = value;
3965
+ if (!Array.isArray(contacts) || contacts.length > 128) return;
3966
+ const records = /* @__PURE__ */ new Map();
3967
+ for (const item of contacts) {
3968
+ const record = decodeRecord(item);
3969
+ if (record === void 0 || records.has(record.id)) return;
3970
+ records.set(record.id, record);
3971
+ }
3972
+ const name = trimmedName(wallet["name"]);
3973
+ return {
3974
+ v: 2,
3975
+ contacts: [...records.values()].sort((a, b) => a.id < b.id ? -1 : 1),
3976
+ wallet: {
3977
+ updatedAt: wallet["updatedAt"],
3978
+ ...name === void 0 ? {} : { name }
3979
+ },
3980
+ groups: out
3981
+ };
3982
+ }
3983
+ /** UTF-8 JSON — `undefined` when the document exceeds the 64 KB limit. */
3984
+ function encodeMetaDoc(doc) {
3985
+ const bytes = new TextEncoder().encode(JSON.stringify(doc));
3986
+ return bytes.byteLength <= 65536 ? bytes : void 0;
3987
+ }
4027
3988
  function decodeMetaDocBytes(bytes) {
4028
3989
  if (bytes.byteLength > 65536) return;
4029
3990
  try {
@@ -4157,11 +4118,11 @@ var MetaSyncController = class extends Controller {
4157
4118
  this.setStatus(walletId, { status: "synced" });
4158
4119
  if (hasEdits) await this.publishNow(walletId, gen);
4159
4120
  } else {
4160
- const plaintext = await signer.decrypt(remote.content).catch(() => void 0);
4161
- const doc = plaintext === void 0 ? void 0 : decodeMetaDocBytes(new TextEncoder().encode(plaintext));
4121
+ const plaintext = await signer.decrypt(remote.content);
4122
+ const doc = decodeMetaDocBytes(new TextEncoder().encode(plaintext));
4162
4123
  if (doc === void 0) {
4163
4124
  if (gen !== this.generation) return;
4164
- const error = plaintext !== void 0 && isUnsupportedDoc(plaintext) ? "unsupported" : "corrupt";
4125
+ const error = isUnsupportedDoc(plaintext) ? "unsupported" : "corrupt";
4165
4126
  this.setStatus(walletId, {
4166
4127
  status: "error",
4167
4128
  error
@@ -4207,7 +4168,7 @@ var MetaSyncController = class extends Controller {
4207
4168
  };
4208
4169
  }
4209
4170
  acceptableEvent(e, pubkey, tag) {
4210
- if (e.kind !== 30078 || e.pubkey !== pubkey || !verifyEvent(e)) return false;
4171
+ if (e.kind !== 30078 || e.pubkey !== pubkey || !this.options.verifyEvent(e)) return false;
4211
4172
  const dTags = e.tags.filter((t) => t[0] === "d");
4212
4173
  return dTags.length === 1 && dTags[0]?.[1] === tag;
4213
4174
  }
@@ -4287,7 +4248,7 @@ const DUST = {
4287
4248
  p2pkh: 546
4288
4249
  };
4289
4250
  const FROZEN_AMOUNTS = /* @__PURE__ */ new Set([546, 330]);
4290
- const isObject$6 = (v) => typeof v === "object" && v !== null;
4251
+ const isObject$5 = (v) => typeof v === "object" && v !== null;
4291
4252
  var EsploraError = class extends Error {
4292
4253
  /** True for request timeout/abort, network failure, 429-after-retries and 5xx — safe to retry. */
4293
4254
  transient;
@@ -4372,7 +4333,7 @@ const esplora = (endpoints, fetchFn, sleep, timeoutMs = REQUEST_TIMEOUT_MS) => {
4372
4333
  };
4373
4334
  const feeTiers = async (es) => {
4374
4335
  const res = await es.get("/fee-estimates");
4375
- const estimates = isObject$6(res) ? res : {};
4336
+ const estimates = isObject$5(res) ? res : {};
4376
4337
  const pick = (target) => Math.max(1, Math.ceil(Number(estimates[target] ?? 1)));
4377
4338
  return [
4378
4339
  {
@@ -4485,7 +4446,7 @@ const esploraSleep = async (ms) => new Promise((resolve) => {
4485
4446
  });
4486
4447
  /** Bound on the unlock-time `/v1/networks` read so a dead gateway cannot stall unlocking. */
4487
4448
  const GATEWAY_PROBE_TIMEOUT_MS = 5e3;
4488
- const isObject$5 = (v) => typeof v === "object" && v !== null;
4449
+ const isObject$4 = (v) => typeof v === "object" && v !== null;
4489
4450
  const makeClient = (info, urls, fetchFn) => createPublicClient({
4490
4451
  chain: {
4491
4452
  id: info.chainId,
@@ -4525,9 +4486,9 @@ const solanaCaller = (urls, fetchFn) => ({ call: async (method, params) => {
4525
4486
  params
4526
4487
  })
4527
4488
  })).json();
4528
- if (!isObject$5(body)) return await attempt(next, /* @__PURE__ */ new Error(`malformed response from ${url}`));
4489
+ if (!isObject$4(body)) return await attempt(next, /* @__PURE__ */ new Error(`malformed response from ${url}`));
4529
4490
  if (body["error"] !== void 0) {
4530
- const msg = isObject$5(body["error"]) ? body["error"]["message"] : void 0;
4491
+ const msg = isObject$4(body["error"]) ? body["error"]["message"] : void 0;
4531
4492
  return await attempt(next, new Error(typeof msg === "string" ? msg : method));
4532
4493
  }
4533
4494
  return body["result"];
@@ -4702,7 +4663,7 @@ var NetworkController = class extends Controller {
4702
4663
  params: []
4703
4664
  })
4704
4665
  })).json();
4705
- const genesis = isObject$5(body) ? body["result"] : void 0;
4666
+ const genesis = isObject$4(body) ? body["result"] : void 0;
4706
4667
  if (genesis !== info.genesisHash) throw new Error(`${url} reports genesis hash ${String(genesis)}, expected ${info.genesisHash ?? ""}`);
4707
4668
  const current = this.getState().customRpc[network] ?? [];
4708
4669
  const customRpc = {
@@ -4726,295 +4687,25 @@ var NetworkController = class extends Controller {
4726
4687
  method: "eth_chainId",
4727
4688
  params: []
4728
4689
  })
4729
- })).json();
4730
- const result = typeof body === "object" && body !== null && "result" in body ? body.result : void 0;
4731
- if (typeof result !== "string") throw new TypeError(`eth_chainId returned a malformed response from ${url}`);
4732
- const chainId = Number.parseInt(result, 16);
4733
- if (chainId !== info.chainId) throw new Error(`${url} reports chain id ${chainId}, expected ${info.chainId}`);
4734
- const current = this.getState().customRpc[network] ?? [];
4735
- const customRpc = {
4736
- ...this.getState().customRpc,
4737
- [network]: [url, ...current]
4738
- };
4739
- this.update((s) => ({
4740
- ...s,
4741
- customRpc
4742
- }));
4743
- this.clients.delete(network);
4744
- const store = this.engineStore;
4745
- if (store !== void 0) await store.collection("networks").put("customRpc", new TextEncoder().encode(JSON.stringify(customRpc)));
4746
- }
4747
- };
4748
- // src/payments/parse.ts
4749
- /** Invoices with less than this much life left are treated as already expired. */
4750
- const BOLT11_EXPIRY_GRACE_MS = 6e4;
4751
- const invalid = (reason) => ({
4752
- kind: "invalid",
4753
- reason
4754
- });
4755
- /** BTC decimal `amount` → sats. At most 8 decimal places; must fit a safe integer. */
4756
- function btcAmountSats(text) {
4757
- const match = /^(\d+)(?:\.(\d{1,8}))?$/.exec(text);
4758
- if (match === null) return;
4759
- const [, whole] = match;
4760
- if (whole === void 0) return;
4761
- const sats = BigInt(whole) * 100000000n + BigInt((match[2] ?? "").padEnd(8, "0") || "0");
4762
- return sats <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(sats) : void 0;
4763
- }
4764
- /**
4765
- * BOLT11 → fields, network- and expiry-checked. `undefined` = not a bolt11 string; `"network"` /
4766
- * `"expired"` / `"malformed"` are the failure modes.
4767
- */
4768
- function bolt11Fields(text, options) {
4769
- let decoded;
4770
- try {
4771
- decoded = decodeBolt11(text);
4772
- } catch {
4773
- return;
4774
- }
4775
- const network = decoded.network === "mainnet" ? "mainnet" : decoded.network === "regtest" ? "regtest" : void 0;
4776
- if (network === void 0) return "network";
4777
- if (network !== options.network) return "network";
4778
- const expiresAt = (decoded.timestamp + decoded.expirySeconds) * 1e3;
4779
- if (expiresAt <= options.now + BOLT11_EXPIRY_GRACE_MS) return "expired";
4780
- return {
4781
- ...decoded.amountMsat === void 0 ? {} : { amountSats: Math.ceil(Number(decoded.amountMsat) / 1e3) },
4782
- paymentHash: bytesToHex(decoded.paymentHash),
4783
- ...decoded.description === void 0 ? {} : { description: decoded.description },
4784
- expiresAt
4785
- };
4786
- }
4787
- /** Spark address or sats/token invoice → options. `null` means not a spark input. */
4788
- function sparkOptions(text, options) {
4789
- let decoded;
4790
- try {
4791
- decoded = decodeSparkAddress(text);
4792
- } catch {
4793
- return;
4794
- }
4795
- if (decoded.network !== options.network) return "network";
4796
- if (decoded.invoice === void 0) return [{
4797
- kind: "spark",
4798
- address: text
4799
- }];
4800
- if (decoded.invoice.expiresAt !== void 0 && decoded.invoice.expiresAt <= options.now) return "expired";
4801
- if (decoded.invoice.payment?.type === "tokens") return "token";
4802
- let parsed;
4803
- try {
4804
- parsed = parseSparkInvoice(text, {
4805
- network: options.network,
4806
- now: options.now
4807
- });
4808
- } catch {
4809
- return "malformed";
4810
- }
4811
- const { payment } = parsed.fields;
4812
- return [{
4813
- kind: "spark-invoice",
4814
- invoice: text,
4815
- ...payment?.type === "sats" && payment.amount !== void 0 ? { amountSats: payment.amount } : {},
4816
- ...parsed.fields.memo === void 0 ? {} : { memo: parsed.fields.memo },
4817
- ...parsed.fields.expiresAt === void 0 ? {} : { expiresAt: parsed.fields.expiresAt }
4818
- }];
4819
- }
4820
- /** Does `address` decode under the other network? Used only to classify a rejection. */
4821
- function decodesOnOtherNetwork(address, options) {
4822
- try {
4823
- bitcoinAddressScript(address, options.network === "mainnet" ? "regtest" : "mainnet");
4824
- return true;
4825
- } catch {
4826
- return false;
4827
- }
4828
- }
4829
- /** BIP-21 URI → request. Only the `spark=` and `lightning=` payment methods are supported. */
4830
- function bip21Parse(text, options) {
4831
- const q = text.indexOf("?");
4832
- const address = text.slice(8, q === -1 ? void 0 : q);
4833
- const params = /* @__PURE__ */ new Map();
4834
- if (q !== -1) for (const pair of text.slice(q + 1).split("&")) {
4835
- const eq = pair.indexOf("=");
4836
- if (eq === -1) return invalid("malformed");
4837
- let key;
4838
- let value;
4839
- try {
4840
- key = decodeURIComponent(pair.slice(0, eq)).toLowerCase();
4841
- value = decodeURIComponent(pair.slice(eq + 1));
4842
- } catch {
4843
- return invalid("malformed");
4844
- }
4845
- if (params.has(key)) return invalid("malformed");
4846
- if (key.startsWith("req-") && !BIP21_KNOWN_REQ_PARAMS.has(key)) return invalid("malformed");
4847
- params.set(key, value);
4848
- }
4849
- const options_ = [];
4850
- let declaredSats;
4851
- const spark = params.get("spark");
4852
- if (spark !== void 0) {
4853
- const parsed = sparkOptions(spark, options);
4854
- if (parsed === void 0 || parsed === "malformed") return invalid("malformed");
4855
- if (parsed === "token") return {
4856
- kind: "unsupported",
4857
- format: "spark-token-invoice"
4858
- };
4859
- if (parsed === "network" || parsed === "expired") return invalid(parsed);
4860
- options_.push(...parsed);
4861
- const sats = parsed.find((o) => o.kind === "spark-invoice")?.amountSats;
4862
- if (sats !== void 0) {
4863
- if (declaredSats !== void 0 && declaredSats !== sats) return invalid("amount-mismatch");
4864
- declaredSats = sats;
4865
- }
4866
- }
4867
- const lightning = params.get("lightning");
4868
- if (lightning !== void 0) {
4869
- const parsed = bolt11Fields(lightning, options);
4870
- if (parsed === void 0 || parsed === "malformed") return invalid("malformed");
4871
- if (parsed === "network" || parsed === "expired") return invalid(parsed);
4872
- options_.push({
4873
- kind: "lightning",
4874
- invoice: lightning,
4875
- ...parsed.amountSats === void 0 ? {} : { amountSats: parsed.amountSats },
4876
- paymentHash: parsed.paymentHash,
4877
- ...parsed.description === void 0 ? {} : { description: parsed.description },
4878
- expiresAt: parsed.expiresAt
4879
- });
4880
- if (parsed.amountSats !== void 0) {
4881
- if (declaredSats !== void 0 && declaredSats !== parsed.amountSats) return invalid("amount-mismatch");
4882
- declaredSats = parsed.amountSats;
4883
- }
4884
- }
4885
- if (address.length > 0) {
4886
- try {
4887
- bitcoinAddressScript(address, options.network);
4888
- } catch {
4889
- return invalid(decodesOnOtherNetwork(address, options) ? "network" : "malformed");
4890
- }
4891
- options_.push({
4892
- kind: "bitcoin",
4893
- address
4894
- });
4895
- }
4896
- const declaredAmount = params.get("amount");
4897
- if (declaredAmount !== void 0) {
4898
- const sats = btcAmountSats(declaredAmount);
4899
- if (sats === void 0) return invalid("malformed");
4900
- if (declaredSats !== void 0 && declaredSats !== sats) return invalid("amount-mismatch");
4901
- declaredSats = sats;
4902
- }
4903
- if (options_.length === 0) {
4904
- if (params.has("lno")) return {
4905
- kind: "unsupported",
4906
- format: "bolt12"
4907
- };
4908
- if (params.has("sp")) return {
4909
- kind: "unsupported",
4910
- format: "silent-payment"
4911
- };
4912
- return invalid("malformed");
4913
- }
4914
- return {
4915
- kind: "request",
4916
- request: {
4917
- options: options_,
4918
- ...declaredSats === void 0 ? {} : { amountSats: declaredSats },
4919
- ...params.get("label") === void 0 ? {} : { label: params.get("label") ?? "" },
4920
- ...params.get("message") === void 0 ? {} : { message: params.get("message") ?? "" }
4921
- }
4922
- };
4923
- }
4924
- const BIP21_KNOWN_REQ_PARAMS = /* @__PURE__ */ new Set([
4925
- "req-amount",
4926
- "req-label",
4927
- "req-message"
4928
- ]);
4929
- /** `input` → PaymentParse. Never throws: every failure is a structured result. */
4930
- function parsePayment(input, options) {
4931
- try {
4932
- const text = input.trim();
4933
- if (/^nostr\+walletconnect:/i.test(text)) return {
4934
- kind: "unsupported",
4935
- format: "nostr-wallet-connect"
4936
- };
4937
- const stripped = text.toLowerCase().startsWith("lightning:") ? text.slice(10) : text;
4938
- if (/^bitcoin:/i.test(stripped)) return bip21Parse(`bitcoin:${stripped.slice(stripped.indexOf(":") + 1)}`, options);
4939
- const bolt11 = bolt11Fields(stripped, options);
4940
- if (bolt11 === "network" || bolt11 === "expired" || bolt11 === "malformed") return invalid(bolt11);
4941
- if (bolt11 !== void 0) return {
4942
- kind: "request",
4943
- request: {
4944
- options: [{
4945
- kind: "lightning",
4946
- invoice: stripped,
4947
- ...bolt11.amountSats === void 0 ? {} : { amountSats: bolt11.amountSats },
4948
- paymentHash: bolt11.paymentHash,
4949
- ...bolt11.description === void 0 ? {} : { description: bolt11.description },
4950
- expiresAt: bolt11.expiresAt
4951
- }],
4952
- ...bolt11.amountSats === void 0 ? {} : { amountSats: bolt11.amountSats }
4953
- }
4954
- };
4955
- const spark = sparkOptions(stripped, options);
4956
- if (spark === "token") return {
4957
- kind: "unsupported",
4958
- format: "spark-token-invoice"
4959
- };
4960
- if (spark === "network" || spark === "expired" || spark === "malformed") return invalid(spark);
4961
- if (spark !== void 0) return {
4962
- kind: "request",
4963
- request: { options: spark }
4964
- };
4965
- if (/^(lnurlp|lnurlw):/i.test(stripped)) {
4966
- const rest = stripped.slice(stripped.indexOf("://") + 3);
4967
- const url = `${(rest.split(/[/?#]/, 1)[0] ?? "").toLowerCase().endsWith(".onion") ? "http" : "https"}://${rest}`;
4968
- if (new URL(url).searchParams.get("tag") === "login") return {
4969
- kind: "unsupported",
4970
- format: "lnurl-auth"
4971
- };
4972
- return {
4973
- kind: "lnurl",
4974
- url
4975
- };
4976
- }
4977
- if (/^keyauth:/i.test(stripped)) return {
4978
- kind: "unsupported",
4979
- format: "lnurl-auth"
4980
- };
4981
- if (!stripped.includes(":") && stripped.includes("@")) return {
4982
- kind: "lnurl",
4983
- url: lightningAddressUrl(stripped),
4984
- address: stripped
4985
- };
4986
- if (/^lno1[02-9ac-hj-np-z]+$/i.test(stripped)) return {
4987
- kind: "unsupported",
4988
- format: "bolt12"
4989
- };
4990
- try {
4991
- const url = decodeLnurl(stripped);
4992
- if (new URL(url).searchParams.get("tag") === "login") return {
4993
- kind: "unsupported",
4994
- format: "lnurl-auth"
4995
- };
4996
- return {
4997
- kind: "lnurl",
4998
- url
4999
- };
5000
- } catch {}
5001
- try {
5002
- bitcoinAddressScript(stripped, options.network);
5003
- return {
5004
- kind: "request",
5005
- request: { options: [{
5006
- kind: "bitcoin",
5007
- address: stripped
5008
- }] }
5009
- };
5010
- } catch {
5011
- if (decodesOnOtherNetwork(stripped, options)) return invalid("network");
5012
- }
5013
- return { kind: "unrecognized" };
5014
- } catch {
5015
- return invalid("malformed");
4690
+ })).json();
4691
+ const result = typeof body === "object" && body !== null && "result" in body ? body.result : void 0;
4692
+ if (typeof result !== "string") throw new TypeError(`eth_chainId returned a malformed response from ${url}`);
4693
+ const chainId = Number.parseInt(result, 16);
4694
+ if (chainId !== info.chainId) throw new Error(`${url} reports chain id ${chainId}, expected ${info.chainId}`);
4695
+ const current = this.getState().customRpc[network] ?? [];
4696
+ const customRpc = {
4697
+ ...this.getState().customRpc,
4698
+ [network]: [url, ...current]
4699
+ };
4700
+ this.update((s) => ({
4701
+ ...s,
4702
+ customRpc
4703
+ }));
4704
+ this.clients.delete(network);
4705
+ const store = this.engineStore;
4706
+ if (store !== void 0) await store.collection("networks").put("customRpc", new TextEncoder().encode(JSON.stringify(customRpc)));
5016
4707
  }
5017
- }
4708
+ };
5018
4709
  // src/payments/resolve.ts
5019
4710
  /**
5020
4711
  * `parsePayment` plus LNURL dereferencing: an `lnurl` result is fetched and turned into a concrete
@@ -5052,7 +4743,7 @@ async function resolvePayment(input, options) {
5052
4743
  }
5053
4744
  // src/spark/notes.ts
5054
4745
  const HEX64 = /^[0-9a-f]{64}$/;
5055
- const isObject$4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4746
+ const isObject$3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
5056
4747
  const NOTE_FIELDS = /* @__PURE__ */ new Set([
5057
4748
  "kind",
5058
4749
  "recipientPubkey",
@@ -5062,7 +4753,7 @@ const NOTE_FIELDS = /* @__PURE__ */ new Set([
5062
4753
  ]);
5063
4754
  /** Strict read-side validation: anything off-shape is `undefined`, never a throw. */
5064
4755
  function parsePaymentNote(value) {
5065
- if (!isObject$4(value)) return;
4756
+ if (!isObject$3(value)) return;
5066
4757
  for (const field of Object.keys(value)) if (!NOTE_FIELDS.has(field)) return;
5067
4758
  const { kind, recipientPubkey, eventId, comment, lightning } = value;
5068
4759
  if (kind !== "zap") return;
@@ -5350,7 +5041,7 @@ var SparkController = class extends Controller {
5350
5041
  note = void 0;
5351
5042
  }
5352
5043
  if (note === void 0) {
5353
- this.options.logger.warn(`spark note record for ${payment.id} ignored: malformed`, /* @__PURE__ */ new Error("malformed payment note"));
5044
+ this.options.logger.warn("spark note record ignored: malformed");
5354
5045
  return payment;
5355
5046
  }
5356
5047
  return {
@@ -5483,7 +5174,8 @@ var SparkController = class extends Controller {
5483
5174
  signer
5484
5175
  });
5485
5176
  } catch (error) {
5486
- throw error instanceof SparkControllerError ? error : new SparkControllerError("internal", "registration failed");
5177
+ if (error instanceof SparkControllerError) throw error;
5178
+ throw new SparkControllerError(error instanceof SparkRequestError ? "network" : "internal", "registration failed", error);
5487
5179
  }
5488
5180
  }
5489
5181
  async unregisterLightningAddress(ref, params) {
@@ -5495,7 +5187,8 @@ var SparkController = class extends Controller {
5495
5187
  signer
5496
5188
  });
5497
5189
  } catch (error) {
5498
- throw error instanceof SparkControllerError ? error : new SparkControllerError("internal", "unregistration failed");
5190
+ if (error instanceof SparkControllerError) throw error;
5191
+ throw new SparkControllerError(error instanceof SparkRequestError ? "network" : "internal", "unregistration failed", error);
5499
5192
  }
5500
5193
  }
5501
5194
  async payInvoice(ref, params) {
@@ -5577,6 +5270,14 @@ var SparkController = class extends Controller {
5577
5270
  async claimDeposit(ref, transaction) {
5578
5271
  await this.guarded(async () => this.clientFor(ref).deposits.claim({ transaction }));
5579
5272
  }
5273
+ /** The account's last-synced balance — a cached snapshot, not a fresh query. */
5274
+ accountBalance(ref) {
5275
+ return this.getState().accounts[key(ref)]?.balanceSats;
5276
+ }
5277
+ /** A payment's settle status — `payInvoice` resolves the send; `sendStatus` reports its preimage. */
5278
+ async paymentStatus(ref, request) {
5279
+ return this.guarded(async () => this.clientFor(ref).lightning.sendStatus(request));
5280
+ }
5580
5281
  async receiveAddress(ref) {
5581
5282
  const state = this.getState().accounts[key(ref)];
5582
5283
  await Promise.resolve();
@@ -5687,7 +5388,7 @@ var DepositClaimer = class {
5687
5388
  };
5688
5389
  // src/transactions/bitcoin.ts
5689
5390
  /** Bitcoin route: scan → coin-select → PSBT → sign → broadcast, plus esplora status poll. */
5690
- const isObject$3 = (v) => typeof v === "object" && v !== null;
5391
+ const isObject$2 = (v) => typeof v === "object" && v !== null;
5691
5392
  const broadcastPsbt = async (es, result) => {
5692
5393
  if (result.kind !== "bitcoin.psbt" || !(result.signedPsbt instanceof Uint8Array)) throw new Error("unexpected bitcoin sign result");
5693
5394
  const signed = Transaction.fromPSBT(result.signedPsbt);
@@ -5715,7 +5416,7 @@ const accountPath = (accountPath) => accountPath.replace(/^m\//, "").split("/").
5715
5416
  const poll = async (ctx, tx) => {
5716
5417
  if (tx.hash === void 0) return "failed";
5717
5418
  const status = await ctx.options.networks.esplora(tx.network).get(`/tx/${tx.hash}/status`);
5718
- if (!(isObject$3(status) && status["confirmed"] === true)) return;
5419
+ if (!(isObject$2(status) && status["confirmed"] === true)) return;
5719
5420
  return "confirmed";
5720
5421
  };
5721
5422
  const nextReceiveAddress = async (ctx, walletId, groupIndex, network) => {
@@ -6490,190 +6191,6 @@ const createEvmRoute = () => {
6490
6191
  prepareReplace
6491
6192
  };
6492
6193
  };
6493
- PROGRAM_IDS.token2022;
6494
- const MAX_MESSAGE_BYTES = 1232;
6495
- const CU_SIMULATE_LIMIT = 14e5;
6496
- const b64 = (bytes) => base64.encode(bytes);
6497
- const isObject$2 = (v) => typeof v === "object" && v !== null;
6498
- const obj$1 = (v) => isObject$2(v) ? v : void 0;
6499
- const str = (v, fallback = "0") => {
6500
- if (typeof v === "string") return v;
6501
- return typeof v === "number" || typeof v === "bigint" ? String(v) : fallback;
6502
- };
6503
- var SolanaChainAdapter = class {
6504
- async rpc(rpc, method, params) {
6505
- return rpc.call(method, params);
6506
- }
6507
- async instructions(rpc, from, intent) {
6508
- if (intent.kind === "sol") return [getTransferSolInstruction({
6509
- source: createNoopSigner(address(from)),
6510
- destination: address(intent.to),
6511
- amount: intent.lamports
6512
- })];
6513
- const tokenProgram = intent.tokenProgram === void 0 ? TOKEN_PROGRAM_ADDRESS : address(intent.tokenProgram);
6514
- const [sourceAta] = await findAssociatedTokenPda({
6515
- mint: address(intent.mint),
6516
- owner: address(from),
6517
- tokenProgram
6518
- });
6519
- const [destAta] = await findAssociatedTokenPda({
6520
- mint: address(intent.mint),
6521
- owner: address(intent.to),
6522
- tokenProgram
6523
- });
6524
- const ixs = [];
6525
- const destInfo = await this.rpc(rpc, "getAccountInfo", [destAta, {
6526
- encoding: "base64",
6527
- commitment: "confirmed"
6528
- }]);
6529
- if (obj$1(obj$1(destInfo)?.["value"]) === void 0) ixs.push(getCreateAssociatedTokenIdempotentInstruction({
6530
- ata: destAta,
6531
- mint: address(intent.mint),
6532
- owner: address(intent.to),
6533
- payer: createNoopSigner(address(from)),
6534
- tokenProgram
6535
- }));
6536
- ixs.push(getTransferCheckedInstruction({
6537
- source: sourceAta,
6538
- mint: address(intent.mint),
6539
- destination: destAta,
6540
- authority: address(from),
6541
- amount: intent.amount,
6542
- decimals: intent.decimals
6543
- }, { programAddress: tokenProgram }));
6544
- return ixs;
6545
- }
6546
- /** Instruction set, simulated compute units, and a fresh blockhash — fee fields come later. */
6547
- async build(rpc, network, from, intent) {
6548
- const instructions = await this.instructions(rpc, from, intent);
6549
- const hashResult = obj$1(await this.rpc(rpc, "getLatestBlockhash", [{ commitment: "confirmed" }]));
6550
- const value = obj$1(hashResult?.["value"]);
6551
- const blockhashValue = typeof value?.["blockhash"] === "string" ? value["blockhash"] : "";
6552
- const lastValidBlockHeight = BigInt(str(value?.["lastValidBlockHeight"], "0"));
6553
- const compiled = this.compile(from, instructions, blockhashValue, lastValidBlockHeight);
6554
- const units = await this.simulate(rpc, compiled.messageBytes);
6555
- return {
6556
- family: "solana",
6557
- network,
6558
- from,
6559
- instructions,
6560
- writable: this.writableAccounts(instructions),
6561
- unitsConsumed: units,
6562
- blockhash: blockhashValue,
6563
- lastValidBlockHeight
6564
- };
6565
- }
6566
- writableAccounts(instructions) {
6567
- const out = /* @__PURE__ */ new Set();
6568
- for (const ix of instructions) {
6569
- const accounts = obj$1(ix)?.["accounts"];
6570
- if (!Array.isArray(accounts)) continue;
6571
- for (const a of accounts) {
6572
- const record = obj$1(a);
6573
- const role = Number(record?.["role"] ?? 0);
6574
- if (typeof record?.["address"] === "string" && role >= 2) out.add(record["address"]);
6575
- }
6576
- }
6577
- return [...out];
6578
- }
6579
- /** Unsigned wire bytes: shortvec(1) sig count + 64-byte zero sig + message (for simulate). */
6580
- wireBytes(messageBytes) {
6581
- const out = new Uint8Array(65 + messageBytes.length);
6582
- out[0] = 1;
6583
- out.set(messageBytes, 65);
6584
- return out;
6585
- }
6586
- async simulate(rpc, messageBytes) {
6587
- const result = obj$1(await this.rpc(rpc, "simulateTransaction", [b64(this.wireBytes(messageBytes)), {
6588
- encoding: "base64",
6589
- sigVerify: false,
6590
- replaceRecentBlockhash: false
6591
- }]));
6592
- const value = obj$1(result?.["value"]);
6593
- const units = Number(value?.["unitsConsumed"] ?? 0);
6594
- return units > 0 ? units : CU_SIMULATE_LIMIT;
6595
- }
6596
- compile(from, instructions, blockhashValue, lastValidBlockHeight) {
6597
- const message = createTransactionMessage({ version: 0 });
6598
- const withPayer = setTransactionMessageFeePayer(address(from), message);
6599
- const withLifetime = setTransactionMessageLifetimeUsingBlockhash({
6600
- blockhash: blockhash(blockhashValue),
6601
- lastValidBlockHeight
6602
- }, withPayer);
6603
- const withIxs = appendTransactionMessageInstructions([...instructions], withLifetime);
6604
- const compiled = compileTransactionMessage(withIxs);
6605
- const messageBytes = new Uint8Array(getCompiledTransactionMessageEncoder().encode(compiled));
6606
- if (messageBytes.length > MAX_MESSAGE_BYTES) throw new Error(`compiled message is ${messageBytes.length} bytes (max ${MAX_MESSAGE_BYTES})`);
6607
- return {
6608
- messageBytes,
6609
- instructions
6610
- };
6611
- }
6612
- /** Percentile-tiered prioritization fees over the writable accounts of this transaction. */
6613
- async estimateFee(rpc, writable) {
6614
- const result = await this.rpc(rpc, "getRecentPrioritizationFees", [[...writable]]);
6615
- const fees = (Array.isArray(result) ? result : []).flatMap((r) => {
6616
- const fee = obj$1(r)?.["prioritizationFee"];
6617
- return fee === void 0 ? [] : [Number(fee)];
6618
- }).sort((a, b) => a - b);
6619
- const pick = (p) => BigInt(fees[Math.min(fees.length - 1, Math.floor(fees.length * p / 100))] ?? 0);
6620
- return [
6621
- {
6622
- tier: "slow",
6623
- microLamportsPerCu: pick(50)
6624
- },
6625
- {
6626
- tier: "normal",
6627
- microLamportsPerCu: pick(75)
6628
- },
6629
- {
6630
- tier: "fast",
6631
- microLamportsPerCu: pick(90)
6632
- }
6633
- ];
6634
- }
6635
- /** Prepend CU-limit + CU-price budget instructions; returns message bytes for the sign request. */
6636
- applyFee(tx, fee) {
6637
- const units = Math.ceil((tx.unitsConsumed === 0 ? CU_SIMULATE_LIMIT : tx.unitsConsumed) * 1.1);
6638
- return this.compile(tx.from, [
6639
- getSetComputeUnitLimitInstruction({ units }),
6640
- getSetComputeUnitPriceInstruction({ microLamports: fee.microLamportsPerCu }),
6641
- ...tx.instructions
6642
- ], tx.blockhash, tx.lastValidBlockHeight).messageBytes;
6643
- }
6644
- /** Wire transaction bytes — sigCount shortvec + each 64-byte sig + message. */
6645
- finalize(messageBytes, signatures) {
6646
- for (const sig of signatures) if (sig.length !== 64) throw new Error(`solana signature must be 64 bytes, got ${sig.length}`);
6647
- const out = new Uint8Array(1 + 64 * signatures.length + messageBytes.length);
6648
- out[0] = signatures.length;
6649
- for (const [i, sig] of signatures.entries()) out.set(sig, 1 + 64 * i);
6650
- out.set(messageBytes, 1 + 64 * signatures.length);
6651
- return out;
6652
- }
6653
- async broadcast(rpc, wireBytes) {
6654
- const result = await this.rpc(rpc, "sendTransaction", [b64(wireBytes), {
6655
- encoding: "base64",
6656
- skipPreflight: false,
6657
- maxRetries: 0,
6658
- preflightCommitment: "confirmed"
6659
- }]);
6660
- if (typeof result !== "string") throw new TypeError("sendTransaction returned a malformed signature");
6661
- return result;
6662
- }
6663
- /** Processed → confirmed → finalized; an error on the status means the tx failed on-chain. */
6664
- async status(rpc, signature) {
6665
- const result = obj$1(await this.rpc(rpc, "getSignatureStatuses", [[signature], { searchTransactionHistory: true }]));
6666
- const entry = Array.isArray(result?.["value"]) ? obj$1(result["value"][0]) : void 0;
6667
- if (entry === void 0) return "pending";
6668
- if (entry["err"] !== null && entry["err"] !== void 0) return "failed";
6669
- const c = entry["confirmationStatus"];
6670
- return c === "finalized" ? "finalized" : c === "confirmed" ? "confirmed" : "pending";
6671
- }
6672
- async blockHeight(rpc) {
6673
- const result = await this.rpc(rpc, "getBlockHeight", [{ commitment: "confirmed" }]);
6674
- return BigInt(str(result, "0"));
6675
- }
6676
- };
6677
6194
  // src/transactions/solana.ts
6678
6195
  /** Solana route: SOL/SPL send → sign → broadcast, plus status poll with rebroadcast/drop. */
6679
6196
  /** The network's base signature fee, lamports per signature. */
@@ -7177,6 +6694,73 @@ function createWalletEngine(options) {
7177
6694
  addressBook,
7178
6695
  openStore: options.openStore,
7179
6696
  spark: controller,
6697
+ nostrSign: async (ref, event) => nostr(options.wallet).signer(ref).signEvent(event),
6698
+ solanaSign: async (account, network, request, verify) => {
6699
+ const rpc = networks.solanaRpc(network);
6700
+ const adapter = new SolanaChainAdapter();
6701
+ const hdAccount = {
6702
+ kind: "hd",
6703
+ walletId: account.walletId,
6704
+ groupIndex: account.groupIndex,
6705
+ template: "solana.bip44-change"
6706
+ };
6707
+ if (request.kind === "transactions") {
6708
+ const signatures = [];
6709
+ const signedTransactions = [];
6710
+ for (const messageBytes of request.transactions) {
6711
+ normalizeSolana({
6712
+ kind: "solana.transaction",
6713
+ network,
6714
+ account: hdAccount,
6715
+ message: messageBytes
6716
+ }, account.address);
6717
+ const result = await chains(options.wallet).sign({
6718
+ request: {
6719
+ kind: "solana.transaction",
6720
+ network,
6721
+ account: hdAccount,
6722
+ message: messageBytes
6723
+ },
6724
+ verify
6725
+ });
6726
+ if (result.kind !== "solana.transaction" || !(result.signature instanceof Uint8Array)) throw new Error("unexpected solana sign result");
6727
+ const wire = adapter.finalize(messageBytes, [result.signature]);
6728
+ if (request.send) signatures.push(await adapter.broadcast(rpc, wire));
6729
+ else signedTransactions.push(wire);
6730
+ }
6731
+ return request.send ? {
6732
+ kind: "solana.transactions",
6733
+ send: true,
6734
+ signatures
6735
+ } : {
6736
+ kind: "solana.transactions",
6737
+ send: false,
6738
+ signedTransactions
6739
+ };
6740
+ }
6741
+ normalizeSolana({
6742
+ kind: "solana.message",
6743
+ format: "raw",
6744
+ network,
6745
+ account: hdAccount,
6746
+ message: request.message
6747
+ }, account.address);
6748
+ const result = await chains(options.wallet).sign({
6749
+ request: {
6750
+ kind: "solana.message",
6751
+ format: "raw",
6752
+ network,
6753
+ account: hdAccount,
6754
+ message: request.message
6755
+ },
6756
+ verify
6757
+ });
6758
+ if (result.kind !== "solana.message" || !(result.signature instanceof Uint8Array)) throw new Error("unexpected solana sign result");
6759
+ return {
6760
+ kind: "solana.message",
6761
+ signature: result.signature
6762
+ };
6763
+ },
7180
6764
  fetch: options.fetch,
7181
6765
  random: options.random,
7182
6766
  now: options.now,
@@ -7203,7 +6787,8 @@ function createWalletEngine(options) {
7203
6787
  nostr: { syncSigner: (walletId) => nostr(options.wallet).syncSigner(walletId) },
7204
6788
  metaSync: options.metaSync,
7205
6789
  logger: options.logger,
7206
- now: options.now
6790
+ now: options.now,
6791
+ verifyEvent: options.verifyEvent
7207
6792
  });
7208
6793
  const depositClaimer = new DepositClaimer({
7209
6794
  transactions,
@@ -7227,7 +6812,17 @@ function createWalletEngine(options) {
7227
6812
  if (!("address" in account)) throw new Error("no EVM address for the group");
7228
6813
  return account.address;
7229
6814
  },
6815
+ solanaAddress: async (group, network) => {
6816
+ const account = await chains(options.wallet).account({
6817
+ ...group,
6818
+ template: "solana.bip44-change",
6819
+ network
6820
+ });
6821
+ if (!("address" in account)) throw new Error("no Solana address for the group");
6822
+ return account.address;
6823
+ },
7230
6824
  enabledNetworks: () => networks.enabled("evm"),
6825
+ nostrPubkey: async (ref) => nostr(options.wallet).signer(ref).getPublicKey(),
7231
6826
  invalidate: (origin) => {
7232
6827
  requests.invalidateOrigin(origin);
7233
6828
  }
@@ -7238,6 +6833,55 @@ function createWalletEngine(options) {
7238
6833
  networks,
7239
6834
  defaultNetwork: () => networks.enabled("evm")[0] ?? "eip155:1"
7240
6835
  });
6836
+ const nip07 = new Nip07Handler({
6837
+ connections,
6838
+ requests,
6839
+ signerFor: (ref) => nostr(options.wallet).signer(ref)
6840
+ });
6841
+ const webln = new WeblnHandler({
6842
+ connections,
6843
+ requests,
6844
+ spark: controller,
6845
+ sparkAccount: () => {
6846
+ const group = connections.activeGroup();
6847
+ return group === void 0 ? void 0 : {
6848
+ walletId: group.walletId,
6849
+ groupIndex: group.groupIndex,
6850
+ network: options.sparkNetwork
6851
+ };
6852
+ },
6853
+ alias: options.weblnAlias,
6854
+ lightningMaxFee: options.lightningMaxFee,
6855
+ sleep: async (ms) => {
6856
+ const setTimer = options.setTimer ?? ((ms_, fn) => {
6857
+ const timer = setTimeout(fn, ms_);
6858
+ return () => {
6859
+ clearTimeout(timer);
6860
+ };
6861
+ });
6862
+ await new Promise((resolve) => {
6863
+ setTimer(ms, resolve);
6864
+ });
6865
+ }
6866
+ });
6867
+ const solanaWallet = new SolanaWalletHandler({
6868
+ connections,
6869
+ requests,
6870
+ solanaAccount: async (group, network) => {
6871
+ const account = await chains(options.wallet).account({
6872
+ ...group,
6873
+ template: "solana.bip44-change",
6874
+ network
6875
+ });
6876
+ if (!("address" in account) || !("publicKey" in account) || !(account.publicKey instanceof Uint8Array)) throw new Error("no Solana account for the group");
6877
+ return {
6878
+ address: account.address,
6879
+ publicKey: account.publicKey
6880
+ };
6881
+ },
6882
+ activeGroup: () => connections.activeGroup(),
6883
+ solanaNetwork: () => networks.enabled("solana")[0] ?? SOLANA_CHAIN_IDS["solana:mainnet"] ?? ""
6884
+ });
7241
6885
  let chain = Promise.resolve();
7242
6886
  let store;
7243
6887
  let started = false;
@@ -7316,13 +6960,17 @@ function createWalletEngine(options) {
7316
6960
  addressBook,
7317
6961
  connections,
7318
6962
  eip1193,
6963
+ nip07,
6964
+ webln,
6965
+ solanaWallet,
7319
6966
  spark: controller,
7320
6967
  accounts,
7321
6968
  metaSync,
7322
6969
  backup,
7323
6970
  zaps: { prepare: async (params) => prepareZap(params, {
7324
6971
  fetch: options.fetch,
7325
- now: options.now
6972
+ now: options.now,
6973
+ verifyEvent: options.verifyEvent
7326
6974
  }) },
7327
6975
  payments: {
7328
6976
  parse: (input, network) => parsePayment(input, {