@qntx/wallet-engine 0.7.0 → 0.8.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.
@@ -0,0 +1,1296 @@
1
+ import { r as NetworkInfo } from "./registry-LcFSPrE1.mjs";
2
+ import { StoreApi } from "zustand/vanilla";
3
+ import { SignRequest } from "@qntx/wallet-chains";
4
+ import { NostrKeyRef, UnlockFactor, Wallet } from "@qntx/wallet";
5
+ import "@scure/btc-signer";
6
+ import { CooperativeExitResult, LightningInvoice, LightningPayment, LightningSendStatus, SparkClient, SparkNetwork, SparkPayment, SparkStore, SparkTransfer } from "@qntx/spark";
7
+ import { decodeEvm } from "@qntx/wallet-chains/evm";
8
+ import { LnurlPayRequest, LnurlWithdrawRequest } from "@qntx/spark/lnurl";
9
+ import { Event, NostrSigner, UnsignedEvent } from "@qntx/nostr";
10
+ import { chains } from "@qntx/wallet/chains";
11
+ import { WalletSigner } from "@qntx/wallet/nostr";
12
+ import { SparkSigner } from "@qntx/wallet/spark";
13
+ import { PublicClient } from "viem";
14
+ import "@solana/kit";
15
+ import "@scure/btc-signer/psbt.js";
16
+ import { SparkAccountRef, SparkApproveIntent } from "@qntx/wallet/protocol";
17
+ type ControllerOptions<S> = {
18
+ readonly name: string;
19
+ readonly defaultState: () => S;
20
+ };
21
+ /**
22
+ * Controller base: a zustand vanilla store plus lifecycle. `update` applies a recipe that must
23
+ * return a NEW state object; returning the same reference is a no-op (no set, no notification).
24
+ * Persistence and migrations layer on later — this package carries only what its first user needs.
25
+ */
26
+ declare abstract class Controller<S extends Record<string, unknown>> {
27
+ readonly name: string;
28
+ readonly store: StoreApi<S>;
29
+ protected constructor(options: ControllerOptions<S>);
30
+ getState(): S;
31
+ protected update(recipe: (state: S) => S): void;
32
+ abstract init(): Promise<void>;
33
+ abstract destroy(): Promise<void>;
34
+ }
35
+ /** Log port: listener failures are reported here and never reach the emitter or peers. */
36
+ type EngineLogger = {
37
+ readonly warn: (message: string, error?: unknown) => void;
38
+ };
39
+ type EventBus<E> = {
40
+ /** Synchronous dispatch to every current listener in registration order. */
41
+ emit: <K extends keyof E>(type: K, payload: E[K]) => void;
42
+ on: <K extends keyof E>(type: K, listener: (payload: E[K]) => void) => () => void;
43
+ };
44
+ declare function createEventBus<E>(logger: EngineLogger): EventBus<E>;
45
+ /**
46
+ * Engine storage port: named collections of byte values. `collection` is synchronous and cheap —
47
+ * the same collection object backs every call, so guards (closed) live on the store.
48
+ */
49
+ type EngineCollection = {
50
+ readonly get: (key: string) => Promise<Uint8Array | undefined>;
51
+ readonly put: (key: string, bytes: Uint8Array) => Promise<void>;
52
+ readonly delete: (key: string) => Promise<void>;
53
+ /** Every key in the collection, in an unspecified order. */
54
+ readonly list: () => Promise<ReadonlyArray<string>>;
55
+ };
56
+ type EngineStore = {
57
+ readonly collection: (name: string) => EngineCollection;
58
+ readonly close: () => Promise<void>;
59
+ };
60
+ type ConnectionOrigin = {
61
+ readonly kind: "browser";
62
+ readonly origin: string;
63
+ };
64
+ type ConnectionScope = {
65
+ /** CAIP-10 */
66
+ readonly accounts: ReadonlyArray<string>;
67
+ readonly methods: ReadonlyArray<string>;
68
+ readonly notifications: ReadonlyArray<string>;
69
+ };
70
+ type ConnectionSession = {
71
+ readonly id: string;
72
+ readonly origin: ConnectionOrigin;
73
+ /** Keyed by CAIP-2. */
74
+ readonly scopes: Readonly<Record<string, ConnectionScope>>;
75
+ /** The session's current EVM network; only dApp sessions have one. */
76
+ readonly currentNetwork: string;
77
+ /** The origin's Nostr policy — set when the host approves a `nostr` connection. */
78
+ readonly nostrPolicy?: NostrPolicy;
79
+ /** The origin's Lightning policy — set when the host approves a `lightning` connection. */
80
+ readonly lightningPolicy?: LightningPolicy;
81
+ readonly createdAt: number;
82
+ readonly lastUsedAt: number;
83
+ };
84
+ /**
85
+ * How much a `nostr` session may do without per-call approval: `signing` is `"ask"` (every
86
+ * `signEvent` goes through the pipeline), `"always"` (any kind signs directly), or a kind list (`{
87
+ * kinds }` — only those kinds sign directly, the rest ask); `decrypt` gates `nip04/nip44 .decrypt`.
88
+ * The four forced-confirm kinds `{0,3,5,10002}` always ask regardless.
89
+ */
90
+ type NostrPolicy = {
91
+ readonly signing: "ask" | "always" | {
92
+ readonly kinds: ReadonlyArray<number>;
93
+ };
94
+ readonly decrypt: boolean;
95
+ };
96
+ /**
97
+ * How much a `lightning` session may do without per-call approval: `balance` gates `getBalance`
98
+ * (WebLN). Sending and invoicing always go through their own approvals.
99
+ */
100
+ type LightningPolicy = {
101
+ readonly balance: boolean;
102
+ };
103
+ /** `connect` asks for accounts; `network` asks to add a network the session does not cover. */
104
+ type PendingConnection = {
105
+ readonly id: string;
106
+ readonly origin: ConnectionOrigin;
107
+ readonly kind: "connect" | "network";
108
+ /**
109
+ * Which namespace the connection is for — `eip155` (EVM), `nostr` (NIP-07) or `lightning`
110
+ * (WebLN).
111
+ */
112
+ readonly namespace: "eip155" | "nostr" | "lightning" | "solana";
113
+ readonly network?: string;
114
+ readonly createdAt: number;
115
+ };
116
+ type AccountGroup = {
117
+ readonly walletId: string;
118
+ readonly groupIndex: number;
119
+ };
120
+ type ConnectionState = {
121
+ readonly sessions: Readonly<Record<string, ConnectionSession>>;
122
+ readonly pending: Readonly<Record<string, PendingConnection>>;
123
+ };
124
+ type ConnectionControllerOptions = {
125
+ readonly openStore: () => Promise<EngineStore>;
126
+ readonly random: (n: number) => Uint8Array;
127
+ readonly now: () => number;
128
+ readonly logger: EngineLogger;
129
+ /** Development builds also accept `http://localhost`. */
130
+ readonly allowLocalhost: boolean;
131
+ /** The group the app currently shows; sessions are bound to it. */
132
+ readonly selectedGroup: () => AccountGroup | undefined;
133
+ /** The group's EVM address on `network`. */
134
+ readonly evmAddress: (group: AccountGroup, network: string) => Promise<string>;
135
+ /** The group's Solana address on `network` (a CAIP-2 `solana:<genesis>` chain). */
136
+ readonly solanaAddress: (group: AccountGroup, network: string) => Promise<string>;
137
+ readonly enabledNetworks: () => ReadonlyArray<string>;
138
+ /** A Nostr identity's public key — `nostr(wallet).signer(ref).getPublicKey()`. */
139
+ readonly nostrPubkey: (ref: NostrKeyRef) => Promise<string>;
140
+ /** Voids a page's unfinished requests (revoked, or its network changed). */
141
+ readonly invalidate: (origin: string) => void;
142
+ };
143
+ declare class ConnectionController extends Controller<ConnectionState> {
144
+ private readonly options;
145
+ private engineStore;
146
+ private readonly waiters;
147
+ private group;
148
+ private identity;
149
+ constructor(options: ConnectionControllerOptions);
150
+ init(): Promise<void>;
151
+ destroy(): Promise<void>;
152
+ /** Locking is not consent: every pending connection is rejected. */
153
+ lock(): void;
154
+ /**
155
+ * A page navigated away (or the bridge is being disposed): the origin's pending connection
156
+ * requests are rejected and its unfinished pipeline requests voided — the live session survives
157
+ * (a refresh is not a revocation).
158
+ */
159
+ invalidateOrigin(origin: string): void;
160
+ /** Throws `4100` unless `origin` is `https://host[:port]` (or localhost in development). */
161
+ checkOrigin(origin: string): ConnectionOrigin;
162
+ session(origin: string): ConnectionSession | undefined;
163
+ pending(): ReadonlyArray<PendingConnection>;
164
+ /** The group sessions are bound to: the host's last `setActiveGroup`, else the app's selection. */
165
+ activeGroup(): AccountGroup | undefined;
166
+ /** Whether `network` is an EVM network the wallet has enabled. */
167
+ isEnabled(network: string): boolean;
168
+ /** The origin's authorized addresses on its current network; empty when not connected. */
169
+ accounts(origin: string): ReadonlyArray<string>;
170
+ /** Throws `4100` unless the origin's session covers `method` on `network`. */
171
+ authorize(origin: string, network: string, method: string): ConnectionSession;
172
+ /** Resolves with the session once the host approves; rejects with `4001` when it refuses. */
173
+ request(origin: string, kind: PendingConnection["kind"], network?: string, namespace?: PendingConnection["namespace"]): Promise<ConnectionSession>;
174
+ /**
175
+ * The host's approval, by id: the accounts granted (EVM addresses of the active group) and the
176
+ * network.
177
+ */
178
+ approveConnection(id: string, grant: {
179
+ readonly accounts: ReadonlyArray<string>;
180
+ readonly network: string;
181
+ /** The `nostr` namespace's grant: the identity's pubkey and the origin's policy. */
182
+ readonly nostr?: {
183
+ readonly pubkey: string;
184
+ readonly policy: NostrPolicy;
185
+ };
186
+ /** The `lightning` namespace's grant: the origin's policy. */
187
+ readonly lightning?: {
188
+ readonly policy: LightningPolicy;
189
+ };
190
+ }): Promise<ConnectionSession>;
191
+ rejectConnection(id: string): void;
192
+ /** Ends the origin's session; its pending connection and unfinished requests are void. */
193
+ revoke(origin: string): Promise<void>;
194
+ /** Switches within the session's scope; the origin's unfinished requests are void. */
195
+ setCurrentNetwork(origin: string, network: string): Promise<void>;
196
+ touch(origin: string): Promise<void>;
197
+ /**
198
+ * The host switched account group: every session's accounts become the new group's addresses. A
199
+ * session that cannot get one (no address derivable) is left with an empty list and has to be
200
+ * authorized again.
201
+ */
202
+ setActiveGroup(walletId: string, groupIndex: number): Promise<void>;
203
+ /** The active Nostr identity — `undefined` until the host picks one. */
204
+ activeIdentity(): NostrKeyRef | undefined;
205
+ /** The origin's persisted Nostr policy — `undefined` until it is nostr-authorized. */
206
+ nostrPolicy(origin: string): NostrPolicy | undefined;
207
+ /** The origin's `nostr` namespace scope's pubkey, or `undefined` when not nostr-authorized. */
208
+ nostrAccount(origin: string): string | undefined;
209
+ /** The origin's persisted Lightning policy — `undefined` until it is lightning-authorized. */
210
+ lightningPolicy(origin: string): LightningPolicy | undefined;
211
+ /** The origin's `solana` scope's address on `network`, or `undefined` when not authorized. */
212
+ solanaAccount(origin: string, network: string): string | undefined;
213
+ /**
214
+ * The host's Nostr identity selection: every authorized `nostr` session's account becomes the new
215
+ * identity's pubkey (or empties when the identity is cleared). No event — NIP-07 has none.
216
+ */
217
+ setActiveIdentity(ref: NostrKeyRef | undefined): Promise<void>;
218
+ private dropPending;
219
+ private persist;
220
+ private requireStore;
221
+ }
222
+ type Esplora = {
223
+ readonly get: (path: string) => Promise<unknown>;
224
+ readonly post: (path: string, body: string) => Promise<unknown>;
225
+ };
226
+ type SolanaRpc = {
227
+ readonly call: (method: string, params: unknown[]) => Promise<unknown>;
228
+ };
229
+ /**
230
+ * A host-endpoint-only client for cross-checking pre-signing reads. `not-needed`: the gateway is
231
+ * not this network's first endpoint, so the primary reads already come from the host.
232
+ * `unavailable`: a cross-check is needed but the network has no host endpoint.
233
+ */
234
+ type Independent<T> = {
235
+ readonly kind: "not-needed";
236
+ } | {
237
+ readonly kind: "unavailable";
238
+ } | {
239
+ readonly kind: "available";
240
+ readonly client: T;
241
+ };
242
+ type NetworkControllerState = {
243
+ readonly customRpc: Record<string, ReadonlyArray<string>>;
244
+ };
245
+ type Options$2 = {
246
+ readonly fetch: typeof globalThis.fetch;
247
+ readonly rpc: Readonly<Record<string, ReadonlyArray<string>>>;
248
+ readonly openStore: () => Promise<EngineStore>;
249
+ readonly logger: EngineLogger;
250
+ readonly gateway?: {
251
+ readonly url: string;
252
+ readonly installId: string;
253
+ } | undefined;
254
+ };
255
+ declare class NetworkController extends Controller<NetworkControllerState> {
256
+ private readonly options;
257
+ private engineStore?;
258
+ private readonly clients;
259
+ private readonly gatewayBase;
260
+ private readonly gatewayOrigin;
261
+ /** Networks the gateway reported at unlock; empty while locked or when the read failed. */
262
+ private gatewayServed;
263
+ constructor(options: Options$2);
264
+ init(): Promise<void>;
265
+ private loadCustomRpc;
266
+ /** Reads the gateway's served networks; any failure leaves the gateway unused until next unlock. */
267
+ private loadGatewayNetworks;
268
+ /** `fetch` that adds the install id to requests bound for the gateway's origin only. */
269
+ private readonly gatewayFetch;
270
+ destroy(): Promise<void>;
271
+ lock(): void;
272
+ /**
273
+ * Ordered endpoints: a network with custom endpoints uses custom → host and never the gateway;
274
+ * otherwise a gateway-served network uses gateway → host; else host only.
275
+ */
276
+ endpoints(network: string): ReadonlyArray<string>;
277
+ info(network: string): NetworkInfo;
278
+ client(network: string): PublicClient;
279
+ /** True when the gateway heads this network's endpoint list (no custom endpoints, gateway-served). */
280
+ private gatewayFirst;
281
+ private independent;
282
+ /** Host-endpoint EVM client for cross-checking reads; never sends the install id. */
283
+ independentClient(network: string): Independent<PublicClient>;
284
+ independentSolanaRpc(network: string): Independent<SolanaRpc>;
285
+ independentEsplora(network: string): Independent<Esplora>;
286
+ /** Networks with at least one configured endpoint or served by the gateway, by family. */
287
+ enabled(family: "evm" | "solana" | "bitcoin"): ReadonlyArray<string>;
288
+ /** Solana JSON-RPC over the ordered endpoint list — kit's transport is single-endpoint. */
289
+ solanaRpc(network: string): SolanaRpc;
290
+ /** Bounded-concurrency + 429-aware ordered-failover Esplora client. */
291
+ esplora(network: string): Esplora;
292
+ /** Validate a custom endpoint's reported chain id, then persist it first in the list. */
293
+ addRpc(network: string, url: string): Promise<void>;
294
+ }
295
+ type AddressFamily = "evm" | "solana" | "bitcoin" | "spark";
296
+ type AddressBookEntry = {
297
+ readonly id: string;
298
+ readonly name: string;
299
+ readonly family: AddressFamily;
300
+ readonly address: string;
301
+ readonly note?: string;
302
+ readonly createdAt: number;
303
+ readonly updatedAt: number;
304
+ };
305
+ type AddressBookTombstone = {
306
+ readonly id: string;
307
+ readonly deleted: true;
308
+ readonly updatedAt: number;
309
+ };
310
+ type AddressBookRecord = AddressBookEntry | AddressBookTombstone;
311
+ type AddressBookState = {
312
+ /** Live entries only; tombstones stay internal. */
313
+ readonly entries: Record<string, AddressBookEntry>;
314
+ };
315
+ type AddressBookOptions = {
316
+ readonly openStore: () => Promise<EngineStore>;
317
+ readonly random: (n: number) => Uint8Array;
318
+ readonly now: () => number;
319
+ readonly logger: EngineLogger;
320
+ };
321
+ declare class AddressBookController extends Controller<AddressBookState> {
322
+ private readonly options;
323
+ private engineStore;
324
+ /** Every record, tombstones included, by id. */
325
+ private records;
326
+ constructor(options: AddressBookOptions);
327
+ init(): Promise<void>;
328
+ destroy(): Promise<void>;
329
+ lock(): void;
330
+ /** Entries and tombstones, for the metadata document. */
331
+ syncEntries(): ReadonlyArray<AddressBookRecord>;
332
+ /**
333
+ * Merges records from another device (last writer wins, tombstones win over older entries).
334
+ * Returns whether anything local changed and whether the merged set holds something `remote`
335
+ * lacks, i.e. whether the remote copy needs a newer publish.
336
+ */
337
+ merge(remote: ReadonlyArray<AddressBookRecord>): Promise<{
338
+ readonly changed: boolean;
339
+ readonly localNewer: boolean;
340
+ }>;
341
+ add(params: {
342
+ readonly name: string;
343
+ readonly family: AddressFamily;
344
+ readonly address: string;
345
+ readonly note?: string;
346
+ }): Promise<AddressBookEntry>;
347
+ rename(id: string, name: string): Promise<AddressBookEntry>;
348
+ /** Sets or clears (empty or `undefined`) the note. */
349
+ setNote(id: string, note: string | undefined): Promise<AddressBookEntry>;
350
+ /** Removes the entry, leaving a tombstone so other devices drop it too. */
351
+ remove(id: string): Promise<void>;
352
+ private checkedNote;
353
+ private requireEntry;
354
+ private persist;
355
+ private requireStore;
356
+ }
357
+ type EvmFeeTier = "slow" | "normal" | "fast";
358
+ type SolanaFeeTier = "slow" | "normal" | "fast";
359
+ type RequestCheckCode = "decode-partial" | "nonce-mismatch" | "fee-mismatch" | "reads-unverified" | "fee-above-network" | "fee-exceeds-amount";
360
+ /**
361
+ * Local, engine-side metadata pinned to a history entry by transfer id. Written after the payment
362
+ * it annotates has already succeeded — a missing or malformed note must never affect the payment
363
+ * itself.
364
+ */
365
+ type PaymentNote = {
366
+ readonly kind: "zap";
367
+ /** 64 lowercase hex. */
368
+ readonly recipientPubkey: string;
369
+ /** 64 lowercase hex — event zaps carry the zapped event's id. */
370
+ readonly eventId?: string;
371
+ /** At most 2000 characters. */
372
+ readonly comment?: string;
373
+ /** The lud16 or LNURL the zap resolved. */
374
+ readonly lightning: string;
375
+ };
376
+ type SparkActivity = SparkPayment & {
377
+ readonly note?: PaymentNote;
378
+ };
379
+ /**
380
+ * SparkStore over one EngineCollection: chains keyed by leafId, plus an index record listing them
381
+ * (`exitChains` is a full listing — the port has no secondary index).
382
+ */
383
+ declare function sparkStore(col: EngineCollection): SparkStore;
384
+ type SparkAccountState = {
385
+ readonly status: "locked" | "connecting" | "ready" | "error";
386
+ readonly balanceSats?: number;
387
+ readonly identityPublicKey?: string;
388
+ readonly sparkAddress?: string;
389
+ readonly errorCategory?: string;
390
+ /** First history page (20 entries, newest first), refreshed alongside the balance. */
391
+ readonly recent?: ReadonlyArray<SparkActivity>;
392
+ };
393
+ type SparkControllerState = {
394
+ readonly accounts: Readonly<Record<string, SparkAccountState>>;
395
+ };
396
+ type SparkApis = {
397
+ readonly signer: (ref: SparkAccountRef) => SparkSigner;
398
+ readonly approve: (params: {
399
+ account: SparkAccountRef;
400
+ intent: SparkApproveIntent;
401
+ verify: UnlockFactor;
402
+ }) => Promise<unknown>;
403
+ };
404
+ type SparkClientFactory = (options: {
405
+ readonly ref: SparkAccountRef;
406
+ readonly store: ReturnType<typeof sparkStore>;
407
+ readonly signer: SparkSigner;
408
+ readonly fetch: typeof globalThis.fetch;
409
+ }) => SparkClient;
410
+ type SparkControllerOptions = {
411
+ readonly spark: SparkApis;
412
+ readonly fetch: typeof globalThis.fetch;
413
+ readonly random: (length: number) => Uint8Array;
414
+ readonly now: () => number;
415
+ readonly logger: EngineLogger;
416
+ readonly createClient: SparkClientFactory;
417
+ };
418
+ declare class SparkController extends Controller<SparkControllerState> {
419
+ private readonly options;
420
+ private engineStore;
421
+ private readonly accounts;
422
+ private readonly clients;
423
+ private readonly recentSeq;
424
+ private readonly aborts;
425
+ constructor(options: SparkControllerOptions);
426
+ /** Engine calls this with the open store on unlock; `undefined` on lock. */
427
+ setStore(store: EngineStore | undefined): void;
428
+ /**
429
+ * Declarative account set: refs not yet tracked are patched `locked` and started when the store
430
+ * is open; tracked refs no longer listed are stopped and dropped; running refs stay untouched.
431
+ */
432
+ setAccounts(refs: ReadonlyArray<SparkAccountRef>): void;
433
+ init(): Promise<void>;
434
+ destroy(): Promise<void>;
435
+ private stopAccount;
436
+ /** Lock: abort every event loop, close every client, reset state. */
437
+ lockAll(): Promise<void>;
438
+ private startAccount;
439
+ private runEvents;
440
+ private handleTransfer;
441
+ private notesCollection;
442
+ /** Attach locally written notes to a history page; malformed records warn and drop. */
443
+ private withNotes;
444
+ /**
445
+ * Refill `recent` from the first history page. A failure keeps the previous page — it never
446
+ * touches `status`/`errorCategory`. A per-account sequence keeps a slower older refresh from
447
+ * overwriting a newer one.
448
+ */
449
+ private refreshRecent;
450
+ private patch;
451
+ private clientFor;
452
+ private guarded;
453
+ /**
454
+ * One-off balance + activity probe for an account that may not be running: builds a temporary
455
+ * client through the same factory on the account's own exit-chain collection (nothing diverges —
456
+ * `balance()`/`transfers.history` never write it), reads, and closes it in `finally`.
457
+ */
458
+ inspect(ref: SparkAccountRef): Promise<{
459
+ balanceSats: number;
460
+ used: boolean;
461
+ }>;
462
+ /** History for one account: a client page merged with locally written notes by id. */
463
+ history(ref: SparkAccountRef, options?: {
464
+ readonly limit?: number;
465
+ readonly offset?: number;
466
+ }): Promise<{
467
+ readonly items: ReadonlyArray<SparkActivity>;
468
+ readonly nextOffset: number | undefined;
469
+ }>;
470
+ send(ref: SparkAccountRef, params: {
471
+ receiver: string;
472
+ amountSats: number;
473
+ verify: UnlockFactor;
474
+ }): Promise<SparkTransfer>;
475
+ registerLightningAddress(ref: SparkAccountRef, params: {
476
+ serverUrl: string;
477
+ domain: string;
478
+ username: string;
479
+ description: string;
480
+ }): Promise<{
481
+ lnurl: string;
482
+ lightningAddress: string;
483
+ }>;
484
+ unregisterLightningAddress(ref: SparkAccountRef, params: {
485
+ serverUrl: string;
486
+ domain: string;
487
+ username: string;
488
+ }): Promise<void>;
489
+ payInvoice(ref: SparkAccountRef, params: {
490
+ invoice: string;
491
+ amountSats?: number;
492
+ maxFeeSats: number;
493
+ verify: UnlockFactor;
494
+ /** Local annotation written under the payment's transfer id after it succeeds. */
495
+ note?: PaymentNote;
496
+ }): Promise<LightningPayment>;
497
+ /**
498
+ * Pays a Spark invoice address. The approval intent mirrors `send`: receiver identity and amount
499
+ * come from the parsed invoice (the supplied `amountSats` fills an open invoice). Then
500
+ * `client.invoices.pay` executes it.
501
+ */
502
+ paySparkInvoice(ref: SparkAccountRef, params: {
503
+ invoice: string;
504
+ amountSats?: number;
505
+ verify: UnlockFactor;
506
+ }): Promise<SparkTransfer>;
507
+ createInvoice(ref: SparkAccountRef, params: {
508
+ amountSats: number;
509
+ memo?: string;
510
+ }): Promise<LightningInvoice>;
511
+ /** A fresh single-use L1 deposit address (with the SO's proof of possession). */
512
+ newDepositAddress(ref: SparkAccountRef): Promise<string>;
513
+ /** Claims a confirmed L1 deposit paying one of the account's unused deposit addresses. */
514
+ claimDeposit(ref: SparkAccountRef, transaction: Uint8Array): Promise<void>;
515
+ /** The account's last-synced balance — a cached snapshot, not a fresh query. */
516
+ accountBalance(ref: SparkAccountRef): number | undefined;
517
+ /** A payment's settle status — `payInvoice` resolves the send; `sendStatus` reports its preimage. */
518
+ paymentStatus(ref: SparkAccountRef, request: {
519
+ readonly requestId: string;
520
+ readonly paymentHash: Uint8Array;
521
+ }): Promise<LightningSendStatus>;
522
+ receiveAddress(ref: SparkAccountRef): Promise<string | undefined>;
523
+ /**
524
+ * Cooperative exit to an L1 address. The client exits `amountSats` of leaves and the payout is
525
+ * `amountSats - fee`, so the approval intent carries the PAYOUT: `amountSats: exit - fee` and
526
+ * `maxFeeSats: fee` — the kernel matches the exit output against the intent, not the leaf total.
527
+ */
528
+ withdraw(ref: SparkAccountRef, params: {
529
+ address: string;
530
+ amountSats?: number;
531
+ speed: "FAST" | "MEDIUM" | "SLOW";
532
+ maxFeeSats?: number;
533
+ verify: UnlockFactor;
534
+ }): Promise<CooperativeExitResult>;
535
+ }
536
+ /**
537
+ * What the host shows for a Spark, Lightning or exit request; `family` tells it apart from a chain
538
+ * intent.
539
+ */
540
+ type SparkDisplay = {
541
+ readonly family: "spark";
542
+ readonly network: SparkNetwork;
543
+ readonly kind: "transfer" | "lightning" | "exit";
544
+ readonly amountSats: number;
545
+ readonly maxFeeSats?: number;
546
+ /** Spark address, Lightning payee public key (hex) or bitcoin address. */
547
+ readonly receiver: string;
548
+ /** Invoice description or the LNURL metadata text. */
549
+ readonly description?: string;
550
+ };
551
+ type SparkResult = {
552
+ readonly kind: "spark";
553
+ readonly transfer: SparkTransfer;
554
+ } | {
555
+ readonly kind: "lightning";
556
+ readonly payment: LightningPayment;
557
+ } | {
558
+ readonly kind: "withdraw";
559
+ readonly exit: CooperativeExitResult;
560
+ };
561
+ /**
562
+ * A validated, fixed Spark payment: everything that does not need the user's verification has
563
+ * happened (including any LNURL invoice fetch), so approval only re-checks expiry and executes.
564
+ */
565
+ type PreparedSparkAction = {
566
+ readonly display: SparkDisplay;
567
+ readonly checks: ReadonlyArray<RequestCheckCode>;
568
+ /** Why the action can no longer be paid at `now` (an expiring invoice), if so. */
569
+ readonly staleReason: (now: number) => string | undefined;
570
+ /** Runs the controller's approve-first payment call. */
571
+ readonly execute: (spark: SparkController, verify: UnlockFactor) => Promise<SparkResult>;
572
+ };
573
+ type PaymentOption = {
574
+ readonly kind: "spark";
575
+ readonly address: string;
576
+ } | {
577
+ readonly kind: "spark-invoice";
578
+ readonly invoice: string;
579
+ readonly amountSats?: number;
580
+ readonly memo?: string;
581
+ readonly expiresAt?: number;
582
+ } | {
583
+ readonly kind: "lightning";
584
+ readonly invoice: string;
585
+ readonly amountSats?: number;
586
+ readonly paymentHash: string;
587
+ readonly description?: string;
588
+ readonly expiresAt: number;
589
+ } | {
590
+ readonly kind: "lnurl-pay";
591
+ readonly request: LnurlPayRequest;
592
+ readonly address?: string;
593
+ } | {
594
+ readonly kind: "lnurl-withdraw";
595
+ readonly request: LnurlWithdrawRequest;
596
+ } | {
597
+ readonly kind: "bitcoin";
598
+ readonly address: string;
599
+ };
600
+ type PaymentRequest = {
601
+ readonly options: ReadonlyArray<PaymentOption>;
602
+ readonly amountSats?: number;
603
+ readonly label?: string;
604
+ readonly message?: string;
605
+ };
606
+ type PaymentParse = {
607
+ readonly kind: "request";
608
+ readonly request: PaymentRequest;
609
+ } | {
610
+ readonly kind: "lnurl";
611
+ readonly url: string;
612
+ readonly address?: string;
613
+ } | {
614
+ readonly kind: "unsupported";
615
+ readonly format: "bolt12" | "silent-payment" | "lnurl-auth" | "spark-token-invoice" | "nostr-wallet-connect";
616
+ } | {
617
+ readonly kind: "invalid";
618
+ readonly reason: "network" | "expired" | "amount-mismatch" | "malformed";
619
+ } | {
620
+ readonly kind: "unrecognized";
621
+ };
622
+ type ParseOptions = {
623
+ readonly network: SparkNetwork;
624
+ readonly now: number;
625
+ };
626
+ /** `input` → PaymentParse. Never throws: every failure is a structured result. */
627
+ declare function parsePayment(input: string, options: ParseOptions): PaymentParse;
628
+ type PayParams = {
629
+ readonly account: SparkAccountRef;
630
+ readonly option: PaymentOption;
631
+ /** Caller-supplied amount — required by open invoices, the `spark` option, and LNURL flows. */
632
+ readonly amountSats?: number;
633
+ readonly comment?: string;
634
+ readonly maxFeeSats?: number;
635
+ readonly speed?: "FAST" | "MEDIUM" | "SLOW";
636
+ /** `amountSats` came from the service's minimum (WebLN `lnurl`), not an explicit amount. */
637
+ readonly amountFromServiceMinimum?: boolean;
638
+ };
639
+ type WithdrawLnurlParams = {
640
+ readonly account: SparkAccountRef;
641
+ readonly option: Extract<PaymentOption, {
642
+ kind: "lnurl-withdraw";
643
+ }>;
644
+ readonly amountSats: number;
645
+ };
646
+ /** A profile zap names the recipient pubkey; an event zap carries the event it zaps. */
647
+ type ZapRecipient = {
648
+ readonly pubkey: string;
649
+ readonly lightning: string;
650
+ } | {
651
+ readonly event: Event;
652
+ readonly lightning: string;
653
+ };
654
+ type PrepareZapParams = {
655
+ /** Any `NostrSigner` — wallet key, external key, NIP-07/46 — signs the 9734. */
656
+ readonly signer: NostrSigner;
657
+ readonly recipient: ZapRecipient;
658
+ readonly amountSats: number;
659
+ readonly comment?: string | undefined;
660
+ readonly relays: ReadonlyArray<string>;
661
+ readonly network: SparkNetwork;
662
+ };
663
+ type PrepareZapContext = {
664
+ readonly verifyEvent: (event: Event) => boolean;
665
+ readonly fetch: typeof globalThis.fetch;
666
+ readonly now: () => number;
667
+ };
668
+ /** Everything a payer needs: the signed 9734, the invoice, and the note fields. */
669
+ type PreparedZap = {
670
+ readonly zapRequest: Event;
671
+ readonly invoice: string;
672
+ /** Hex payment hash decoded from the invoice. */
673
+ readonly paymentHash: string;
674
+ /** Millisecond expiry decoded from the invoice. */
675
+ readonly expiresAt: number;
676
+ readonly amountSats: number;
677
+ /** The LNURL service's 9735 signing pubkey. */
678
+ readonly receiptPubkey: string;
679
+ readonly recipientPubkey: string;
680
+ readonly eventId?: string;
681
+ readonly comment?: string;
682
+ /** The lud16 or LNURL as given. */
683
+ readonly lightning: string;
684
+ };
685
+ /** Everything up to payment: resolve LNURL, sign the 9734, request the invoice. */
686
+ declare function prepareZap(params: PrepareZapParams, context: PrepareZapContext): Promise<PreparedZap>;
687
+ type ChainApis = ReturnType<typeof chains>;
688
+ type SignParams = Parameters<ChainApis["sign"]>[0];
689
+ type AccountRef = SignParams["request"]["account"];
690
+ type DisplayIntent = ReturnType<typeof decodeEvm>;
691
+ type TxState = "draft" | "signed" | "submitted" | "pending" | "confirmed" | "failed" | "rejected" | "dropped" | "replaced";
692
+ /** A bitcoin transaction that funds the wallet's own Spark account; it is claimed once confirmed. */
693
+ type SparkDepositTag = {
694
+ readonly walletId: string;
695
+ readonly groupIndex: number;
696
+ readonly network: SparkNetwork;
697
+ readonly claimed?: boolean;
698
+ };
699
+ type TrackedTransaction = {
700
+ readonly id: string;
701
+ readonly family: "evm" | "solana" | "bitcoin";
702
+ readonly network: string;
703
+ readonly account: string;
704
+ readonly hash: string | undefined;
705
+ readonly state: TxState;
706
+ readonly intent: DisplayIntent | undefined;
707
+ readonly nonce: number;
708
+ /** Solana only — the blockhash expiry that turns an unconfirmed tx `dropped`. */
709
+ readonly lastValidBlockHeight?: number;
710
+ /** EVM replacement — the earlier transaction this one bumps or cancels. */
711
+ readonly replaces?: string;
712
+ /** CPFP — the unconfirmed parent this child pushes. */
713
+ readonly parentId?: string;
714
+ /** Set on a Spark deposit; `claimed` flips once the deposit is credited on Spark. */
715
+ readonly sparkDeposit?: SparkDepositTag;
716
+ /** Bitcoin build record persisted at send for RBF/CPFP rebuilds. */
717
+ readonly btc?: {
718
+ readonly inputs: ReadonlyArray<{
719
+ readonly txid: string;
720
+ readonly vout: number;
721
+ readonly value: number;
722
+ readonly address: string;
723
+ }>;
724
+ readonly outputs: ReadonlyArray<{
725
+ readonly address: string;
726
+ readonly value: number;
727
+ readonly own: boolean;
728
+ }>;
729
+ readonly vsize: number;
730
+ readonly fee: number;
731
+ readonly feeRate: number;
732
+ };
733
+ readonly submittedAt: number;
734
+ readonly error: string | undefined;
735
+ };
736
+ type SendParams = {
737
+ readonly account: AccountRef;
738
+ readonly network: string;
739
+ readonly to: string;
740
+ readonly amount: bigint;
741
+ /** ERC-20 contract — when set, `to`/`amount` are the transfer recipient/units and value is 0. */
742
+ readonly token?: string;
743
+ readonly fee: EvmFeeTier | SolanaFeeTier;
744
+ /** SPL mint decimals — required when `token` is a Solana mint. */
745
+ readonly decimals?: number;
746
+ readonly verify: SignParams["verify"];
747
+ };
748
+ type PrepareParams = Omit<SendParams, "verify">;
749
+ type ChainRequestMethod = "send" | "speed-up" | "cancel" | "cpfp";
750
+ /** What a request asks for; replacements and CPFP name the original transaction. */
751
+ type ChainRequestInput = ({
752
+ readonly method: "send";
753
+ } & PrepareParams) | {
754
+ readonly method: "speed-up" | "cancel";
755
+ readonly txId: string;
756
+ } | {
757
+ readonly method: "cpfp";
758
+ readonly txId: string;
759
+ readonly feeRate: number;
760
+ };
761
+ /**
762
+ * A fully built, estimated and cross-checked send that has not been signed. The unsigned content
763
+ * lives in the closures and cannot change after `prepare` returns.
764
+ */
765
+ type PreparedRequest = {
766
+ /** Id of the tracked transaction `submit` creates. */
767
+ readonly txId: string;
768
+ readonly account: AccountRef;
769
+ readonly network: string;
770
+ /** The transaction being replaced or accelerated; absent for a plain send. */
771
+ readonly target?: string;
772
+ readonly intent: DisplayIntent;
773
+ readonly checks: ReadonlyArray<RequestCheckCode>;
774
+ /** Why the build can no longer be signed (nonce taken, blockhash expired), if so. */
775
+ readonly staleReason: () => string | undefined | Promise<string | undefined>;
776
+ /** Signs, finalizes, broadcasts and hands the transaction to tracking. */
777
+ readonly submit: (verify: SendParams["verify"]) => Promise<TrackedTransaction>;
778
+ /** Frees what `prepare` reserved; safe to call more than once. */
779
+ readonly release: () => void;
780
+ };
781
+ type SignatureResult = {
782
+ readonly kind: "evm.personal-message" | "evm.typed-data";
783
+ readonly signature: Uint8Array;
784
+ };
785
+ /** A prepared message signature: nothing is broadcast or tracked, `submit` returns the signature. */
786
+ type PreparedMessage = Omit<PreparedRequest, "submit" | "txId"> & {
787
+ readonly submit: (verify: SendParams["verify"]) => Promise<SignatureResult>;
788
+ };
789
+ type Options$1 = {
790
+ readonly wallet: Wallet;
791
+ readonly networks: NetworkController;
792
+ readonly openStore: () => Promise<EngineStore>;
793
+ readonly random: (n: number) => Uint8Array;
794
+ readonly setTimer: (ms: number, fn: () => unknown) => () => void;
795
+ readonly now: () => number;
796
+ readonly logger: EngineLogger;
797
+ readonly pollMs?: number;
798
+ /** Test seam — defaults to the wallet's real chains proxy. */
799
+ readonly chains?: ReturnType<typeof chains>;
800
+ };
801
+ type TransactionControllerState = {
802
+ readonly txs: Record<string, TrackedTransaction>;
803
+ };
804
+ declare class TransactionController extends Controller<TransactionControllerState> {
805
+ private readonly options;
806
+ private engineStore?;
807
+ private readonly timers;
808
+ private evmRoute;
809
+ private bitcoinRoute;
810
+ private locked;
811
+ constructor(options: Options$1);
812
+ init(): Promise<void>;
813
+ destroy(): Promise<void>;
814
+ lock(): void;
815
+ private persist;
816
+ private transition;
817
+ private routeCtx;
818
+ /**
819
+ * Internal entry for the request pipeline: builds, estimates and cross-checks a send without
820
+ * signing it. Bitcoin outputs it selects stay locked under `requestId` until the returned
821
+ * `release` runs or the broadcast moves them to the transaction.
822
+ */
823
+ prepareSend(params: PrepareParams, requestId: string, sparkDeposit?: SparkDepositTag): Promise<PreparedRequest>;
824
+ /** The group's next unused `btc.bip84` receive address on a bitcoin `network`. */
825
+ nextReceiveAddress(walletId: string, groupIndex: number, network: string): Promise<string>;
826
+ /** Records that a Spark deposit was credited; persisted with the transaction. */
827
+ markDepositClaimed(id: string): Promise<void>;
828
+ /**
829
+ * Internal entry for a dApp's EVM signature request: the request is normalized first, a
830
+ * transaction is rebuilt with fresh nonce and fees (the dApp's own are discarded), and a message
831
+ * is decoded and signed as is.
832
+ */
833
+ prepareDapp(account: AccountRef, request: SignRequest): Promise<PreparedRequest | PreparedMessage>;
834
+ /**
835
+ * Internal entry for replacements and CPFP: builds, cross-checks and reserves what the
836
+ * replacement needs without signing it. The original must be `submitted` or `pending`.
837
+ */
838
+ prepareReplacement(input: Exclude<ChainRequestInput, {
839
+ method: "send";
840
+ }>, requestId: string): Promise<PreparedRequest>;
841
+ private track;
842
+ }
843
+ /**
844
+ * Recipient risk, pure: a recipient the wallet has never paid or saved is a `warning`; one that
845
+ * looks like a known address (same first and last four characters, different address) is a `danger`
846
+ * — the shape of an address-poisoning lookalike. Both can apply to one recipient.
847
+ */
848
+ type RiskFinding = {
849
+ readonly code: "first-recipient" | "address-poisoning";
850
+ readonly level: "warning" | "danger";
851
+ };
852
+ /** A web page; `origin` is `scheme://host[:port]`, computed by the host from the top-level URL. */
853
+ type BrowserOrigin = {
854
+ readonly kind: "browser";
855
+ readonly origin: string;
856
+ };
857
+ type RequestOrigin = {
858
+ readonly kind: "internal";
859
+ } | BrowserOrigin;
860
+ type RequestMethod = ChainRequestMethod | "pay" | "zap" | "evm-sign" | "nostr-sign" | "webln-invoice" | "solana-sign" | "spark-deposit" | "spark-exit";
861
+ /** A Solana chain account the `solana-sign` request signs for. */
862
+ type SolanaAccount = {
863
+ readonly walletId: string;
864
+ readonly groupIndex: number;
865
+ readonly address: string;
866
+ };
867
+ type SignLogOutcome = "submitted" | "rejected" | "failed" | "expired" | "invalidated";
868
+ type SignLogEntry = {
869
+ readonly id: string;
870
+ readonly at: number;
871
+ readonly origin: RequestOrigin;
872
+ readonly method: RequestMethod;
873
+ readonly account: AccountRef | SparkAccountRef | NostrKeyRef | SolanaAccount;
874
+ readonly network: string;
875
+ readonly summary: string;
876
+ readonly verification: "verified" | "unverifiable";
877
+ readonly checks: ReadonlyArray<RequestCheckCode>;
878
+ readonly risk: ReadonlyArray<RiskFinding>;
879
+ readonly outcome: SignLogOutcome;
880
+ readonly error?: string;
881
+ };
882
+ /** A Spark, Lightning (including LNURL-pay and lightning addresses) or cooperative-exit payment. */
883
+ type PayInput = {
884
+ readonly method: "pay";
885
+ readonly origin?: BrowserOrigin;
886
+ } & PayParams;
887
+ /** A prepared zap; its invoice was fetched by `engine.zaps.prepare` and is paid as-is. */
888
+ type ZapInput = {
889
+ readonly method: "zap";
890
+ readonly account: SparkAccountRef;
891
+ readonly zap: PreparedZap;
892
+ readonly maxFeeSats: number;
893
+ };
894
+ /**
895
+ * A dApp's EVM request: a transaction (rebuilt here with fresh nonce and fees), a personal message
896
+ * or EIP-712 typed data.
897
+ */
898
+ type EvmSignInput = {
899
+ readonly method: "evm-sign";
900
+ readonly origin: BrowserOrigin;
901
+ readonly account: AccountRef;
902
+ readonly network: string;
903
+ readonly request: SignRequest;
904
+ };
905
+ /**
906
+ * Funds the wallet's own Spark account from a bitcoin account of the same wallet; the transaction
907
+ * is an ordinary bitcoin send to a fresh Spark deposit address and is claimed once confirmed.
908
+ */
909
+ type SparkDepositInput = {
910
+ readonly method: "spark-deposit";
911
+ readonly account: SparkAccountRef;
912
+ readonly from: AccountRef;
913
+ readonly amountSats: number;
914
+ readonly fee: PrepareParams["fee"];
915
+ };
916
+ /** A cooperative exit to the group's own next unused `btc.bip84` receive address. */
917
+ type SparkExitInput = {
918
+ readonly method: "spark-exit";
919
+ readonly account: SparkAccountRef;
920
+ readonly amountSats: number;
921
+ readonly maxFeeSats: number;
922
+ readonly speed?: "FAST" | "MEDIUM" | "SLOW";
923
+ };
924
+ /**
925
+ * A NIP-07 `signEvent` that the policy sends through the pipeline: no factor on approval (Nostr
926
+ * events are not per-event verifiable, WD-065); the display is the kind, a short content preview
927
+ * and the tag count — the sign log records kind and event id only.
928
+ */
929
+ type NostrSignInput = {
930
+ readonly method: "nostr-sign";
931
+ readonly origin: BrowserOrigin;
932
+ /** The active identity — the signer the page's pubkey must match. */
933
+ readonly ref: NostrKeyRef;
934
+ readonly event: UnsignedEvent;
935
+ };
936
+ /**
937
+ * A WebLN `makeInvoice` confirmation: no factor (it only asks the user to confirm generating an
938
+ * invoice — WD-065 does not apply; the factor-free rule mirrors `nostr-sign`), `display` carries
939
+ * the requested amount and memo.
940
+ */
941
+ type WeblnInvoiceInput = {
942
+ readonly method: "webln-invoice";
943
+ readonly origin: BrowserOrigin;
944
+ readonly ref: SparkAccountRef;
945
+ readonly amountSats: number;
946
+ readonly memo?: string;
947
+ };
948
+ /**
949
+ * A dApp's Solana request: one `solana-sign` covers a batch of transactions (signed sequentially —
950
+ * each prompts) or a `solana.message` raw-message signature.
951
+ */
952
+ type SolanaSignInput = {
953
+ readonly method: "solana-sign";
954
+ readonly origin: BrowserOrigin;
955
+ readonly account: SolanaAccount;
956
+ readonly network: string;
957
+ readonly request: {
958
+ readonly kind: "transactions";
959
+ readonly transactions: ReadonlyArray<Uint8Array>;
960
+ readonly send: boolean;
961
+ } | {
962
+ readonly kind: "message";
963
+ readonly message: Uint8Array;
964
+ };
965
+ };
966
+ type RequestInput = ChainRequestInput | PayInput | ZapInput | EvmSignInput | NostrSignInput | WeblnInvoiceInput | SolanaSignInput | SparkDepositInput | SparkExitInput;
967
+ /** `approve` of a `nostr-sign` request: the signed event. */
968
+ type NostrSignResult = {
969
+ readonly kind: "nostr.event";
970
+ readonly event: Event;
971
+ };
972
+ /** `nostr-sign` display: the kind, a content preview and the tag count — nothing else is shown. */
973
+ type NostrDisplay = {
974
+ readonly kind: "nostr.event";
975
+ readonly eventKind: number;
976
+ readonly preview: string;
977
+ readonly tagCount: number;
978
+ };
979
+ /** `approve` of a `webln-invoice` request: the created invoice's BOLT11 payment request. */
980
+ type WeblnInvoiceResult = {
981
+ readonly kind: "lightning.invoice";
982
+ readonly paymentRequest: string;
983
+ };
984
+ /** `solana-sign` display: each transaction's decode (fee payer + transfers) or the raw message. */
985
+ type SolanaDisplay = {
986
+ readonly kind: "solana.sign";
987
+ readonly send: boolean;
988
+ readonly count: number;
989
+ readonly transactions: ReadonlyArray<unknown>;
990
+ };
991
+ /** `approve` of a `solana-sign` request: the signatures (or signed transactions) per input. */
992
+ type SolanaSignResult = {
993
+ readonly kind: "solana.transactions";
994
+ readonly send: boolean;
995
+ readonly signatures?: ReadonlyArray<string>;
996
+ readonly signedTransactions?: ReadonlyArray<Uint8Array>;
997
+ } | {
998
+ readonly kind: "solana.message";
999
+ readonly signature: Uint8Array;
1000
+ };
1001
+ /** `webln-invoice` display: the requested amount and memo. */
1002
+ type LightningInvoiceDisplay = {
1003
+ readonly kind: "lightning.invoice";
1004
+ readonly amountSats: number;
1005
+ readonly memo?: string;
1006
+ };
1007
+ type RequestStage = "awaiting-approval" | "signing" | "submitted" | "rejected" | "failed" | "expired" | "invalidated";
1008
+ type PendingRequest = {
1009
+ readonly id: string;
1010
+ readonly origin: RequestOrigin;
1011
+ readonly method: RequestMethod;
1012
+ readonly account: AccountRef | SparkAccountRef | NostrKeyRef | SolanaAccount;
1013
+ readonly network: string;
1014
+ readonly stage: RequestStage;
1015
+ /** Decoded locally from the exact content that will be signed; `family` tells the shapes apart. */
1016
+ readonly display: DisplayIntent | SparkDisplay | NostrDisplay | LightningInvoiceDisplay | SolanaDisplay;
1017
+ /** `unverifiable` as soon as any check is recorded; the host must ask for explicit confirmation. */
1018
+ readonly verification: "verified" | "unverifiable";
1019
+ readonly checks: ReadonlyArray<RequestCheckCode>;
1020
+ /**
1021
+ * Recipient risk; independent of `verification`. A `danger` needs the user's explicit
1022
+ * acknowledgement.
1023
+ */
1024
+ readonly risk: ReadonlyArray<RiskFinding>;
1025
+ readonly createdAt: number;
1026
+ readonly expiresAt: number;
1027
+ /** The transaction being replaced or accelerated; absent for a plain send. */
1028
+ readonly target?: string;
1029
+ /** The tracked transaction once submitted. */
1030
+ readonly txId?: string;
1031
+ readonly error?: string;
1032
+ };
1033
+ type RequestControllerState = {
1034
+ readonly requests: Record<string, PendingRequest>;
1035
+ };
1036
+ type RequestControllerOptions = {
1037
+ readonly transactions: TransactionController;
1038
+ /** The full controller: its payment methods are reachable only through this pipeline. */
1039
+ readonly spark: SparkController;
1040
+ readonly addressBook: AddressBookController;
1041
+ readonly openStore: () => Promise<EngineStore>;
1042
+ readonly fetch: typeof globalThis.fetch;
1043
+ readonly random: (n: number) => Uint8Array;
1044
+ readonly now: () => number;
1045
+ readonly setTimer: (ms: number, fn: () => unknown) => () => void;
1046
+ readonly logger: EngineLogger;
1047
+ /** Signs a Nostr event for `nostr-sign` — `nostr(wallet).signer(ref).signEvent`. */
1048
+ readonly nostrSign: (ref: NostrKeyRef, event: UnsignedEvent) => Promise<Event>;
1049
+ /** Signs/broadcasts a `solana-sign` request — `chains.sign` per tx, then the Solana adapter. */
1050
+ readonly solanaSign: (account: {
1051
+ readonly walletId: string;
1052
+ readonly groupIndex: number;
1053
+ readonly address: string;
1054
+ }, network: string, request: SolanaSignInput["request"], verify: SendParams["verify"]) => Promise<SolanaSignResult>;
1055
+ };
1056
+ /** Requests expire this long after creation. */
1057
+ declare const REQUEST_TTL_MS: number;
1058
+ declare class RequestController extends Controller<RequestControllerState> {
1059
+ private readonly options;
1060
+ private readonly entries;
1061
+ private readonly log;
1062
+ private readonly settlers;
1063
+ /** Original transaction id → the unfinished request replacing or accelerating it. */
1064
+ private readonly targets;
1065
+ private locked;
1066
+ /** Bumped on every unlock and lock so work that outlives a session never touches the next one. */
1067
+ private session;
1068
+ constructor(options: RequestControllerOptions);
1069
+ init(): Promise<void>;
1070
+ destroy(): Promise<void>;
1071
+ /** Locking is not consent: every unfinished request becomes `invalidated` and frees its resources. */
1072
+ lock(): void;
1073
+ /** A page navigated away, was revoked or changed network: its unfinished requests are void. */
1074
+ invalidateOrigin(origin: string): void;
1075
+ /** The signature record, newest first. */
1076
+ signLog(): Promise<ReadonlyArray<SignLogEntry>>;
1077
+ clearSignLog(): Promise<void>;
1078
+ prepare(input: RequestInput): Promise<PendingRequest>;
1079
+ /**
1080
+ * Resolves with what `approve` returned, or rejects with `RequestEndedError` when the request
1081
+ * ends any other way — how a dApp's pending call learns the outcome.
1082
+ */
1083
+ outcome(id: string): Promise<TrackedTransaction | SparkResult | SignatureResult | NostrSignResult | WeblnInvoiceResult | SolanaSignResult>;
1084
+ private openSettler;
1085
+ private settle;
1086
+ /** The bitcoin network `account`'s Spark network settles on; any other pairing is refused. */
1087
+ private l1Network;
1088
+ private sparkBuilt;
1089
+ private build;
1090
+ /**
1091
+ * Signs and submits a request. Anything but a live, unexpired `send` request with this id throws
1092
+ * before any signing; a stale build (nonce taken, blockhash expired) fails without signing.
1093
+ */
1094
+ approve(id: string, method: ChainRequestMethod | "spark-deposit", verify?: SendParams["verify"]): Promise<TrackedTransaction>;
1095
+ approve(id: string, method: "pay" | "zap" | "spark-exit", verify?: SendParams["verify"]): Promise<SparkResult>;
1096
+ approve(id: string, method: "evm-sign", verify?: SendParams["verify"]): Promise<TrackedTransaction | SignatureResult>;
1097
+ approve(id: string, method: "nostr-sign"): Promise<NostrSignResult>;
1098
+ approve(id: string, method: "webln-invoice"): Promise<WeblnInvoiceResult>;
1099
+ approve(id: string, method: "solana-sign", verify?: SendParams["verify"]): Promise<SolanaSignResult>;
1100
+ /**
1101
+ * A cancelled or refused verification is `rejected`; anything after it is `failed`. Chain
1102
+ * requests record which step failed on the tracked transaction; for Spark, the approval round is
1103
+ * the only source of `WalletError`.
1104
+ */
1105
+ private failureStage;
1106
+ reject(id: string): void;
1107
+ /** `approve` for a factor-required run: a missing factor is invalid input. */
1108
+ private requireVerify;
1109
+ private requireRequest;
1110
+ private put;
1111
+ private unclaim;
1112
+ /** Ends a request in a terminal stage and frees what it reserved. */
1113
+ private finish;
1114
+ /** Appends the final stage to the signature record; a failed write is a warning, not an error. */
1115
+ private record;
1116
+ private appendLog;
1117
+ /**
1118
+ * Addresses the wallet already knows for a family: contacts, plus recipients of tracked chain
1119
+ * sends (Spark payments are not tracked).
1120
+ */
1121
+ private knownAddresses;
1122
+ private chainRisk;
1123
+ /** Only a Spark transfer has a recipient to check; Lightning and exits are not assessed. */
1124
+ private sparkRisk;
1125
+ }
1126
+ type Eip1193Request = {
1127
+ readonly method: string;
1128
+ readonly params?: unknown;
1129
+ };
1130
+ type Eip1193Event = {
1131
+ readonly name: "connect";
1132
+ readonly origin: string;
1133
+ readonly chainId: string;
1134
+ } | {
1135
+ readonly name: "accountsChanged";
1136
+ readonly origin: string;
1137
+ readonly accounts: ReadonlyArray<string>;
1138
+ } | {
1139
+ readonly name: "chainChanged";
1140
+ readonly origin: string;
1141
+ readonly chainId: string;
1142
+ } | {
1143
+ readonly name: "disconnect";
1144
+ readonly origin: string;
1145
+ };
1146
+ type Eip1193HandlerOptions = {
1147
+ readonly connections: ConnectionController;
1148
+ readonly requests: RequestController;
1149
+ readonly networks: NetworkController;
1150
+ /** The network an unconnected page sees. */
1151
+ readonly defaultNetwork: () => string;
1152
+ };
1153
+ declare class Eip1193Handler {
1154
+ private readonly options;
1155
+ private readonly listeners;
1156
+ private unsubscribe;
1157
+ constructor(options: Eip1193HandlerOptions);
1158
+ /** Events for the host to forward to pages; derived from changes to the sessions. */
1159
+ subscribe(listener: (event: Eip1193Event) => void): () => void;
1160
+ handle(origin: string, request: Eip1193Request): Promise<unknown>;
1161
+ private requestAccounts;
1162
+ private permissions;
1163
+ private switchChain;
1164
+ private authorizedAccount;
1165
+ private personalSign;
1166
+ private typedData;
1167
+ private sendTransaction;
1168
+ private signingSession;
1169
+ private sign;
1170
+ private read;
1171
+ }
1172
+ /** A NIP-07 method call from the page. */
1173
+ type Nip07Request = {
1174
+ readonly method: string;
1175
+ readonly params?: unknown;
1176
+ };
1177
+ type Nip07HandlerOptions = {
1178
+ readonly connections: Pick<ConnectionController, "checkOrigin" | "authorize" | "session" | "nostrAccount" | "nostrPolicy" | "activeIdentity" | "request" | "touch">;
1179
+ readonly requests: Pick<RequestController, "prepare" | "outcome">;
1180
+ /** `nostr(wallet).signer(ref)` — the active identity's signer. */
1181
+ readonly signerFor: (ref: NostrKeyRef) => WalletSigner;
1182
+ };
1183
+ declare class Nip07Handler {
1184
+ private readonly options;
1185
+ constructor(options: Nip07HandlerOptions);
1186
+ handle(origin: string, request: Nip07Request): Promise<unknown>;
1187
+ private publicKey;
1188
+ private signEvent;
1189
+ private crypt;
1190
+ }
1191
+ /**
1192
+ * The Wallet Standard (`window.solana` / `registerWallet`) handler — the bridge routes `provider:
1193
+ * "solana"` messages here.
1194
+ */
1195
+ type SolanaRequest = {
1196
+ readonly method: string;
1197
+ readonly params?: unknown;
1198
+ };
1199
+ type SolanaHandler = {
1200
+ readonly handle: (origin: string, request: SolanaRequest) => Promise<unknown>;
1201
+ readonly subscribe: (listener: (event: SolanaEvent) => void) => () => void;
1202
+ };
1203
+ /**
1204
+ * The Wallet Standard short chain ids to the registry's CAIP-2 genesis-hash ids, derived from the
1205
+ * solana network registry by name.
1206
+ */
1207
+ declare const SOLANA_CHAIN_IDS: Readonly<Record<string, string>>;
1208
+ /** The Wallet Standard `WalletAccount` shape `standard:connect` returns per account. */
1209
+ type SolanaWalletAccount = {
1210
+ readonly address: string;
1211
+ readonly publicKey: Uint8Array;
1212
+ readonly chains: ReadonlyArray<string>;
1213
+ readonly features: ReadonlyArray<string>;
1214
+ readonly icon?: string;
1215
+ readonly label?: string;
1216
+ };
1217
+ type SolanaEvent = {
1218
+ readonly name: "solanaAccountsChanged";
1219
+ readonly origin: string;
1220
+ readonly accounts: ReadonlyArray<SolanaWalletAccount>;
1221
+ };
1222
+ type SolanaConnections = Pick<ConnectionController, "checkOrigin" | "session" | "authorize" | "solanaAccount" | "request" | "touch" | "revoke" | "getState" | "store">;
1223
+ type Options = {
1224
+ readonly connections: SolanaConnections;
1225
+ readonly requests: Pick<RequestController, "prepare" | "outcome">;
1226
+ /** The group's Solana address + public key on `network` (the `solana.bip44-change` account). */
1227
+ readonly solanaAccount: (group: {
1228
+ readonly walletId: string;
1229
+ readonly groupIndex: number;
1230
+ }, network: string) => Promise<{
1231
+ readonly address: string;
1232
+ readonly publicKey: Uint8Array;
1233
+ }>;
1234
+ readonly activeGroup: () => {
1235
+ readonly walletId: string;
1236
+ readonly groupIndex: number;
1237
+ } | undefined;
1238
+ readonly solanaNetwork: () => string;
1239
+ };
1240
+ /**
1241
+ * The Wallet Standard handler: `standard:connect` authorizes the `solana` scope, `solana:*` sign
1242
+ * requests go through `solana-sign`, `solanaAccountsChanged` returns the re-pointed accounts the
1243
+ * bridge forwards as `standard:events` `change` on a group switch.
1244
+ */
1245
+ declare class SolanaWalletHandler implements SolanaHandler {
1246
+ readonly options: Options;
1247
+ private readonly listeners;
1248
+ private unsubscribe;
1249
+ constructor(options: Options);
1250
+ /** `standard:events` `change` per origin — derived from changes to the sessions. */
1251
+ subscribe(listener: (event: SolanaEvent) => void): () => void;
1252
+ handle(origin: string, request: SolanaRequest): Promise<unknown>;
1253
+ private connect;
1254
+ private walletAccount;
1255
+ private signTransactions;
1256
+ private signMessage;
1257
+ /** The `setActiveGroup` re-point: the solana session's new `WalletAccount[]` for `change`. */
1258
+ solanaAccountsChanged(_origin: string): Promise<SolanaWalletAccount[]>;
1259
+ }
1260
+ /** A WebLN method call from the page. */
1261
+ type WeblnRequest = {
1262
+ readonly method: string;
1263
+ readonly params?: unknown;
1264
+ };
1265
+ type WeblnHandlerOptions = {
1266
+ readonly connections: Pick<ConnectionController, "checkOrigin" | "authorize" | "session" | "lightningPolicy" | "request" | "touch">;
1267
+ readonly requests: Pick<RequestController, "prepare" | "outcome">;
1268
+ readonly spark: Pick<SparkController, "accountBalance" | "paymentStatus">;
1269
+ /** The active group's Spark account — `undefined` when no group is selected. */
1270
+ readonly sparkAccount: () => SparkAccountRef | undefined;
1271
+ /** The node's display alias — host-configured, never a pubkey. */
1272
+ readonly alias: string;
1273
+ /** The host's lightning fee cap — `pay`'s `maxFeeSats` comes from here. */
1274
+ readonly lightningMaxFee: (amountSats: number) => number;
1275
+ /** The injected wait for the preimage poll. */
1276
+ readonly sleep: (ms: number) => Promise<void>;
1277
+ };
1278
+ declare class WeblnHandler {
1279
+ private readonly options;
1280
+ constructor(options: WeblnHandlerOptions);
1281
+ private ref;
1282
+ handle(origin: string, request: WeblnRequest): Promise<unknown>;
1283
+ private sendPayment;
1284
+ private makeInvoice;
1285
+ private lnurl;
1286
+ private preimage;
1287
+ private lightningOption;
1288
+ private getBalance;
1289
+ }
1290
+ /** EIP-1193 / EIP-1474 / EIP-3326 error: `code` is what the page's promise rejects with. */
1291
+ declare class ProviderError extends Error {
1292
+ readonly code: number;
1293
+ constructor(code: number, message: string);
1294
+ }
1295
+ export { sparkStore as $, RiskFinding as A, ParseOptions as B, SparkDepositInput as C, Controller as Ct, BrowserOrigin as D, SignLogOutcome as E, PreparedZap as F, PreparedSparkAction as G, PaymentParse as H, ZapRecipient as I, SparkAccountState as J, SparkDisplay as K, prepareZap as L, SignatureResult as M, PrepareZapContext as N, RequestMethod as O, PrepareZapParams as P, SparkControllerState as Q, PayParams as R, RequestStage as S, createEventBus as St, SignLogEntry as T, PaymentRequest as U, PaymentOption as V, parsePayment as W, SparkController as X, SparkClientFactory as Y, SparkControllerOptions as Z, PendingRequest as _, PendingConnection as _t, SolanaEvent as a, AddressBookEntry as at, RequestControllerState as b, EngineLogger as bt, SolanaWalletAccount as c, NetworkController as ct, Nip07Request as d, ConnectionController as dt, PaymentNote as et, Eip1193Event as f, ConnectionOrigin as ft, PayInput as g, NostrPolicy as gt, EvmSignInput as h, ConnectionState as ht, SOLANA_CHAIN_IDS as i, AddressBookState as it, TransactionController as j, RequestOrigin as k, SolanaWalletHandler as l, Esplora as lt, Eip1193Request as m, ConnectionSession as mt, WeblnHandler as n, RequestCheckCode as nt, SolanaHandler as o, AddressBookRecord as ot, Eip1193Handler as p, ConnectionScope as pt, SparkResult as q, WeblnRequest as r, AddressBookController as rt, SolanaRequest as s, AddressFamily as st, ProviderError as t, SparkActivity as tt, Nip07Handler as u, AccountGroup as ut, REQUEST_TTL_MS as v, EngineCollection as vt, SparkExitInput as w, ControllerOptions as wt, RequestInput as x, EventBus as xt, RequestController as y, EngineStore as yt, WithdrawLnurlParams as z };
1296
+ //# sourceMappingURL=errors-CW_XXGL9.d.mts.map