@arkade-os/sdk 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +24 -6
  2. package/dist/adapters/expo.cjs +7 -7
  3. package/dist/adapters/expo.d.cts +2 -2
  4. package/dist/adapters/expo.d.ts +2 -2
  5. package/dist/adapters/expo.js +4 -4
  6. package/dist/{asyncStorageTaskQueue-B9byr6ij.d.cts → asyncStorageTaskQueue-B6rFkXzW.d.cts} +1 -1
  7. package/dist/{asyncStorageTaskQueue-XP4CCdRY.d.ts → asyncStorageTaskQueue-C0irgPwJ.d.ts} +1 -1
  8. package/dist/{chunk-MWEDDWFU.js → chunk-2657D67V.js} +9 -7
  9. package/dist/chunk-2657D67V.js.map +1 -0
  10. package/dist/{chunk-MWMO2ZQP.js → chunk-3KNSMZWD.js} +24 -13
  11. package/dist/chunk-3KNSMZWD.js.map +1 -0
  12. package/dist/{chunk-DNFTHG73.js → chunk-4DUTRRXF.js} +8 -6
  13. package/dist/chunk-4DUTRRXF.js.map +1 -0
  14. package/dist/{chunk-MQUATTIM.cjs → chunk-4PSM6ZUC.cjs} +55 -57
  15. package/dist/chunk-4PSM6ZUC.cjs.map +1 -0
  16. package/dist/{chunk-FDJ734CH.js → chunk-DPFD5KBK.js} +5 -2
  17. package/dist/chunk-DPFD5KBK.js.map +1 -0
  18. package/dist/{chunk-OMPDPBT5.cjs → chunk-DY24A73N.cjs} +296 -240
  19. package/dist/chunk-DY24A73N.cjs.map +1 -0
  20. package/dist/{chunk-VMVFRTF4.js → chunk-FUCKDTH7.js} +285 -234
  21. package/dist/chunk-FUCKDTH7.js.map +1 -0
  22. package/dist/{chunk-4AJRIM44.js → chunk-GUK33TNC.js} +9 -13
  23. package/dist/chunk-GUK33TNC.js.map +1 -0
  24. package/dist/{chunk-RLD7DRSZ.js → chunk-HT35HPXR.js} +19365 -18395
  25. package/dist/chunk-HT35HPXR.js.map +1 -0
  26. package/dist/{chunk-3NALVGMJ.cjs → chunk-ODLSVJRU.cjs} +38 -27
  27. package/dist/chunk-ODLSVJRU.cjs.map +1 -0
  28. package/dist/{chunk-X6ZI53DZ.cjs → chunk-OMZZQTDM.cjs} +28 -35
  29. package/dist/chunk-OMZZQTDM.cjs.map +1 -0
  30. package/dist/{chunk-V3ZLL5VY.js → chunk-PXEFYEKL.js} +22 -29
  31. package/dist/chunk-PXEFYEKL.js.map +1 -0
  32. package/dist/{chunk-JFJNB7ZH.cjs → chunk-UPIQZRNJ.cjs} +16 -14
  33. package/dist/chunk-UPIQZRNJ.cjs.map +1 -0
  34. package/dist/{chunk-V5WRO3P6.cjs → chunk-UPV4W423.cjs} +14 -18
  35. package/dist/chunk-UPV4W423.cjs.map +1 -0
  36. package/dist/{chunk-URGVQ5TQ.cjs → chunk-V2EU5QWF.cjs} +4583 -3610
  37. package/dist/chunk-V2EU5QWF.cjs.map +1 -0
  38. package/dist/{chunk-FLPWNMX3.cjs → chunk-WIZCF5IX.cjs} +5 -2
  39. package/dist/chunk-WIZCF5IX.cjs.map +1 -0
  40. package/dist/{chunk-MXCB6EVM.cjs → chunk-WZJJZGBT.cjs} +22 -20
  41. package/dist/chunk-WZJJZGBT.cjs.map +1 -0
  42. package/dist/{chunk-V2DDN4MV.js → chunk-Z6WDOZZI.js} +10 -12
  43. package/dist/chunk-Z6WDOZZI.js.map +1 -0
  44. package/dist/compiler.cjs +4 -4
  45. package/dist/compiler.d.cts +1 -1
  46. package/dist/compiler.d.ts +1 -1
  47. package/dist/compiler.js +3 -3
  48. package/dist/contracts/handlers/index.cjs +11 -11
  49. package/dist/contracts/handlers/index.d.cts +3 -4
  50. package/dist/contracts/handlers/index.d.ts +3 -4
  51. package/dist/contracts/handlers/index.js +4 -4
  52. package/dist/{index-18cDMayF.d.ts → index-Bq349_ly.d.cts} +2334 -101
  53. package/dist/{index-Ccfhdfvj.d.cts → index-D4ahI0W6.d.cts} +2 -3
  54. package/dist/{index-DDJFHfba.d.cts → index-Mn2POBPj.d.ts} +2334 -101
  55. package/dist/{index-B_kcptF8.d.ts → index-Yh5y9G4E.d.ts} +2 -3
  56. package/dist/index.cjs +362 -346
  57. package/dist/index.d.cts +1505 -1374
  58. package/dist/index.d.ts +1505 -1374
  59. package/dist/index.js +7 -7
  60. package/dist/{program-BARSNg3X.d.ts → program-38A2Twvj.d.ts} +4 -2
  61. package/dist/{program-znrWkxE4.d.cts → program-DPzf5qsk.d.cts} +4 -2
  62. package/dist/repositories/realm/index.cjs +40 -40
  63. package/dist/repositories/realm/index.d.cts +2 -2
  64. package/dist/repositories/realm/index.d.ts +2 -2
  65. package/dist/repositories/realm/index.js +8 -8
  66. package/dist/repositories/sqlite/index.cjs +38 -38
  67. package/dist/repositories/sqlite/index.d.cts +2 -2
  68. package/dist/repositories/sqlite/index.d.ts +2 -2
  69. package/dist/repositories/sqlite/index.js +8 -8
  70. package/dist/{taskRunner-DUafWu0o.d.ts → taskRunner-BYxEgwM5.d.ts} +1 -1
  71. package/dist/{taskRunner-JYHaLPne.d.cts → taskRunner-Z3LnHfgs.d.cts} +1 -1
  72. package/dist/wallet/expo/background.cjs +17 -17
  73. package/dist/wallet/expo/background.d.cts +3 -3
  74. package/dist/wallet/expo/background.d.ts +3 -3
  75. package/dist/wallet/expo/background.js +9 -9
  76. package/dist/wallet/expo/index.cjs +18 -18
  77. package/dist/wallet/expo/index.d.cts +3 -5
  78. package/dist/wallet/expo/index.d.ts +3 -5
  79. package/dist/wallet/expo/index.js +8 -8
  80. package/dist/worker/expo/index.cjs +12 -12
  81. package/dist/worker/expo/index.d.cts +4 -4
  82. package/dist/worker/expo/index.d.ts +4 -4
  83. package/dist/worker/expo/index.js +8 -8
  84. package/package.json +1 -1
  85. package/dist/chunk-3NALVGMJ.cjs.map +0 -1
  86. package/dist/chunk-4AJRIM44.js.map +0 -1
  87. package/dist/chunk-DNFTHG73.js.map +0 -1
  88. package/dist/chunk-FDJ734CH.js.map +0 -1
  89. package/dist/chunk-FLPWNMX3.cjs.map +0 -1
  90. package/dist/chunk-JFJNB7ZH.cjs.map +0 -1
  91. package/dist/chunk-MQUATTIM.cjs.map +0 -1
  92. package/dist/chunk-MWEDDWFU.js.map +0 -1
  93. package/dist/chunk-MWMO2ZQP.js.map +0 -1
  94. package/dist/chunk-MXCB6EVM.cjs.map +0 -1
  95. package/dist/chunk-OMPDPBT5.cjs.map +0 -1
  96. package/dist/chunk-RLD7DRSZ.js.map +0 -1
  97. package/dist/chunk-URGVQ5TQ.cjs.map +0 -1
  98. package/dist/chunk-V2DDN4MV.js.map +0 -1
  99. package/dist/chunk-V3ZLL5VY.js.map +0 -1
  100. package/dist/chunk-V5WRO3P6.cjs.map +0 -1
  101. package/dist/chunk-VMVFRTF4.js.map +0 -1
  102. package/dist/chunk-X6ZI53DZ.cjs.map +0 -1
  103. package/dist/delegate-gGkUnYpi.d.cts +0 -92
  104. package/dist/delegate-iyDum4fw.d.ts +0 -92
  105. package/dist/keyringDescriptorProvider-DL-jAiRO.d.ts +0 -2082
  106. package/dist/keyringDescriptorProvider-Dtv0JWrT.d.cts +0 -2082
@@ -1,2082 +0,0 @@
1
- import { a as Identity, a3 as Transaction, a4 as SignerSession, a5 as ReadonlyIdentity, a6 as Network, a7 as ActivityResolver, a8 as BatchStartedEvent, a9 as TreeSigningStartedEvent, aa as TxTree, ab as TreeNoncesEvent, ac as BatchFinalizationEvent, ad as BatchFinalizedEvent, ae as BatchFailedEvent, af as TreeTxEvent, ag as TreeSignatureEvent, n as SettlementEvent, b as WalletConfig, W as WalletRepository, C as ContractRepository, ah as DescriptorProvider, j as IContractManager, k as GetNewAddressesOptions, l as NewAddress, ai as IReadonlyWallet, aj as OnchainProvider, x as OperatorProvider, w as IndexerProvider, ak as DelegateProvider, al as ReadonlyWalletConfig, Y as BatchRegistrationRepository, $ as VirtualTxRepository, am as ExitCaptureMode, an as ExitDataSource, h as ActivityRegistry, ao as IReadonlyAssetManager, ap as ContractSyncState, aq as RecipientArkadeAddressContext, G as GetOperatorInfoOptions, O as OperatorInfo, A as ArkadeReader, ar as EsploraProvider, as as NetworkName, d as WalletBalance, e as GetVtxosFilter, N as NormalizedExtendedVirtualCoin, f as GetSpendableVtxosFilter, at as ContractWithVtxos, au as selectPendingRecoveryOutpoints, g as ArkTransaction, i as Activity, E as ExtendedCoin, av as Coin, z as ExtendedVirtualCoin, aw as ContractManager, ax as ContractManagerConfig, I as IWallet, B as Outpoint, ay as SettlementConfig, c as ArkadeBroadcaster, q as IAssetManager, az as VtxoManager, m as IDelegateManager, S as SettleParams, R as Recipient, p as SendOnchainParams, aA as SignedIntent, aB as Intent, aC as SignedProof, aD as Proof, o as SendParams, aE as TimeHeight, P as PageRequest, D as PageResult, F as ScriptVtxoCursor, H as ScriptVtxoPageOptions, J as StoredVtxo, K as VtxoRepositoryKey, L as TransactionHistoryPageFilter, M as TransactionHistoryPageCursor, Q as AtomicWalletState, U as WalletState, aF as DescriptorSigningRequest } from './index-DDJFHfba.cjs';
2
- import { TransactionOutput } from '@scure/btc-signer/psbt.js';
3
- import { Bytes } from '@scure/btc-signer/utils.js';
4
- import { R as RelativeTimelock, A as ArkAddress, C as CSVMultisigTapscript } from './base-C-Y5t_0F.cjs';
5
- import { D as DefaultVtxo, a as DelegateVtxo } from './delegate-gGkUnYpi.cjs';
6
-
7
- /**
8
- * In-memory single key implementation for Bitcoin transaction signing.
9
- *
10
- * @example
11
- * ```typescript
12
- * // Create from hex string
13
- * const key = SingleKey.fromHex('your_private_key_hex');
14
- *
15
- * // Create from raw bytes
16
- * const key = SingleKey.fromPrivateKey(privateKeyBytes);
17
- *
18
- * // Create random key
19
- * const randomKey = SingleKey.fromRandomBytes();
20
- *
21
- * // Sign a transaction
22
- * const signedTx = await key.sign(transaction);
23
- * ```
24
- */
25
- declare class SingleKey implements Identity {
26
- private key;
27
- private constructor();
28
- /** Create a signing identity from raw private key bytes. */
29
- static fromPrivateKey(privateKey: Uint8Array): SingleKey;
30
- /** Create a signing identity from a hex-encoded private key. */
31
- static fromHex(privateKeyHex: string): SingleKey;
32
- /** Create a signing identity with a freshly generated random private key. */
33
- static fromRandomBytes(): SingleKey;
34
- /**
35
- * Export the private key as a hex string.
36
- *
37
- * @returns The private key as a hex string
38
- */
39
- toHex(): string;
40
- sign(tx: Transaction, inputIndexes?: number[]): Promise<Transaction>;
41
- compressedPublicKey(): Promise<Uint8Array>;
42
- xOnlyPublicKey(): Promise<Uint8Array>;
43
- signerSession(): SignerSession;
44
- signMessage(message: Uint8Array, signatureType?: "schnorr" | "ecdsa"): Promise<Uint8Array>;
45
- /**
46
- * BIP-340 sign `messageHash` with aux_rand = 0, so the signature — and
47
- * anything derived from it — is reproducible from the key alone.
48
- *
49
- * What lets a static wallet derive a swap preimage instead of storing one
50
- * (see `wallet/contractSecrets.ts`). Deliberately NOT `signMessage`, whose
51
- * schnorr branch draws a random aux_rand: a preimage derived from that is
52
- * unrecoverable, and the loss would only surface at claim time.
53
- */
54
- signSchnorrDeterministic(messageHash: Uint8Array): Promise<Uint8Array>;
55
- toReadonly(): Promise<ReadonlySingleKey>;
56
- }
57
- declare class ReadonlySingleKey implements ReadonlyIdentity {
58
- private readonly publicKey;
59
- /** Create a readonly identity from a compressed public key. */
60
- constructor(publicKey: Uint8Array);
61
- /**
62
- * Create a ReadonlySingleKey from a compressed public key.
63
- *
64
- * @param publicKey - 33-byte compressed public key (02/03 prefix + 32-byte x coordinate)
65
- * @returns A new ReadonlySingleKey instance
66
- * @example
67
- * ```typescript
68
- * const pubkey = new Uint8Array(33); // your compressed public key
69
- * const readonlyKey = ReadonlySingleKey.fromPublicKey(pubkey);
70
- * ```
71
- */
72
- static fromPublicKey(publicKey: Uint8Array): ReadonlySingleKey;
73
- xOnlyPublicKey(): Promise<Uint8Array>;
74
- compressedPublicKey(): Promise<Uint8Array>;
75
- }
76
-
77
- /** Wall-clock floor for `batchExpiry` outside regtest. */
78
- declare const DEFAULT_MIN_BATCH_EXPIRY_SECONDS = 86400n;
79
- /** Wall-clock floor for `batchExpiry` on regtest (~10 blocks). */
80
- declare const REGTEST_MIN_BATCH_EXPIRY_SECONDS = 6000n;
81
- /** Bounds applied to a server-supplied `BatchStartedEvent.batchExpiry`. */
82
- type BatchExpiryPolicy = {
83
- /** Minimum wall-clock delay in seconds, after normalization. */
84
- minSeconds: bigint;
85
- /**
86
- * Reject block-typed timelocks. Mirrors arkd, which allows a block-typed
87
- * vtxo tree expiry only on regtest.
88
- */
89
- requireSeconds: boolean;
90
- /** When advertised by the operator, `batchExpiry` must equal it exactly. */
91
- advertisedVtxoTreeExpiry?: bigint;
92
- };
93
- /**
94
- * Default policy for a network.
95
- *
96
- * Derive it from the locally held {@link Network} — pinned at wallet setup —
97
- * rather than from a per-round server field, so the permissive regtest branch
98
- * can't be selected by the operator at event time.
99
- */
100
- declare function defaultBatchExpiryPolicy(network: Network): BatchExpiryPolicy;
101
- /** Resolve a policy for `network`, applying any caller overrides on top. */
102
- declare function resolveBatchExpiryPolicy(network: Network, overrides?: Partial<BatchExpiryPolicy>): BatchExpiryPolicy;
103
- /**
104
- * Check a server-supplied batch expiry against `policy` and return the timelock
105
- * to commit to.
106
- *
107
- * The sweep leaf of the shared batch output is derived from this value, so it
108
- * is never reconstructible from anything else the server sends: validating the
109
- * tree only proves it is consistent with whatever value was chosen. Callers
110
- * must encode the returned timelock rather than re-deriving their own.
111
- *
112
- * @throws {ServerResponseMismatchError} if the value is out of policy.
113
- */
114
- declare function assertValidBatchExpiry(batchExpiry: bigint, policy: BatchExpiryPolicy): RelativeTimelock;
115
-
116
- /**
117
- * ArkadeCash is a bearer instrument for the Arkade.
118
- * It encodes a private key and contract parameters as a bech32m string,
119
- * enabling wallet-to-wallet transfers without address exchange.
120
- *
121
- * Format: arkadecash1... / tarkadecash1... (bech32m encoded)
122
- * Payload: version (1 byte) + private key (32 bytes) + server pubkey (32 bytes) + csv timelock sequence (4 bytes)
123
- */
124
- declare class ArkadeCash {
125
- readonly csvTimelock: RelativeTimelock;
126
- readonly hrp: string;
127
- static readonly DefaultHRP = "arkadecash";
128
- /** The only prefixes minted or accepted: mainnet and test networks. */
129
- static readonly HRPs: readonly string[];
130
- static readonly Version = 0;
131
- static readonly PayloadLength: number;
132
- private readonly _privateKey;
133
- private readonly _serverPubKey;
134
- private readonly _publicKey;
135
- constructor(privateKey: Uint8Array, serverPubKey: Uint8Array, csvTimelock: RelativeTimelock, hrp?: string);
136
- /** The note's private key. Returns a fresh copy; mutating it is a no-op. */
137
- get privateKey(): Uint8Array;
138
- /** The server's public key. Returns a fresh copy; mutating it is a no-op. */
139
- get serverPubKey(): Uint8Array;
140
- /** The note's public key. Returns a fresh copy; mutating it is a no-op. */
141
- get publicKey(): Uint8Array;
142
- static generate(serverPubKey: Uint8Array, csvTimelock: RelativeTimelock, hrp?: string): ArkadeCash;
143
- static fromString(encoded: string): ArkadeCash;
144
- toString(): string;
145
- get identity(): SingleKey;
146
- get vtxoScript(): DefaultVtxo.Script;
147
- address(addressHrp: string): ArkAddress;
148
- }
149
-
150
- type ArkadeCashAction = "issued" | "claimed";
151
- /** One transaction of a voucher and the voucher's share of it, in sats. */
152
- interface ArkadeCashTx {
153
- txid: string;
154
- amount: number;
155
- }
156
- interface ArkadeCashRecord {
157
- id: string;
158
- action: ArkadeCashAction;
159
- createdAt: number;
160
- outcome: string;
161
- issues: ArkadeCashTx[];
162
- claims: ArkadeCashTx[];
163
- }
164
- declare class ArkadeCashTracker {
165
- readonly records: Map<string, ArkadeCashRecord>;
166
- get(id: string): ArkadeCashRecord | undefined;
167
- list(): ArkadeCashRecord[];
168
- }
169
- declare function createArkadeCashTracker(): ArkadeCashTracker;
170
- /**
171
- * Combine two records of one voucher. Transactions are unioned by txid and the earliest
172
- * `createdAt` is kept. A claim outranks an issue for `action` and `outcome`; between records
173
- * with the same action, `next` wins.
174
- */
175
- declare function mergeArkadeCashRecord(prev: ArkadeCashRecord | undefined, next: ArkadeCashRecord): ArkadeCashRecord;
176
- /** Inject a public record, merging it into any record already held for the voucher. */
177
- declare function addArkadeCashRecord(records: ArkadeCashTracker, record: ArkadeCashRecord): void;
178
- declare function arkadeCashId(cash: ArkadeCash): string;
179
- declare function arkadeCashResolver(records: ArkadeCashTracker): ActivityResolver;
180
-
181
- declare class ArkError extends Error {
182
- readonly code: number;
183
- readonly message: string;
184
- readonly name: string;
185
- readonly metadata?: Record<string, string> | undefined;
186
- constructor(code: number, message: string, name: string, metadata?: Record<string, string> | undefined);
187
- }
188
- /**
189
- * Structured arkd error `name`s the SDK branches on, centralized so call sites don't
190
- * hardcode string literals. Not an exhaustive mirror of the server's codes — only the
191
- * ones the SDK acts on.
192
- */
193
- declare const ArkErrorName: {
194
- readonly DIGEST_MISMATCH: "DIGEST_MISMATCH";
195
- readonly VTXO_ALREADY_SPENT: "VTXO_ALREADY_SPENT";
196
- readonly INVALID_TX_FILTER: "INVALID_TX_FILTER";
197
- readonly TX_FILTERS_LIMIT_EXCEEDED: "TX_FILTERS_LIMIT_EXCEEDED";
198
- /**
199
- * A CLTV closure was spent before its absolute locktime matured. `submitTx` only, with
200
- * metadata `{ locktime, current_locktime, type: "height" | "time" }`. Self-healing, so defer
201
- * and retry: the server matures a seconds-locktime against the **chain tip block's
202
- * timestamp**, not wall clock, so a prompt spend is rejected until a later block lands.
203
- */
204
- readonly FORFEIT_CLOSURE_LOCKED: "FORFEIT_CLOSURE_LOCKED";
205
- readonly INVALID_INTENT_PROOF: "INVALID_INTENT_PROOF";
206
- readonly INTERNAL_ERROR: "INTERNAL_ERROR";
207
- };
208
- type ArkErrorName = (typeof ArkErrorName)[keyof typeof ArkErrorName];
209
- /**
210
- * Type guard for a structured {@link ArkError}, optionally narrowing to a cataloged
211
- * {@link ArkErrorName}; for an uncataloged name, add it there or compare `err.name` after the
212
- * one-argument form.
213
- *
214
- * @example
215
- * if (isArkError(maybeArkError(err), ArkErrorName.DIGEST_MISMATCH)) { ... }
216
- */
217
- declare function isArkError(error: unknown, name?: ArkErrorName): error is ArkError;
218
- /**
219
- * Which remote dependency an availability failure refers to; labels the
220
- * {@link ProviderUnavailableError} message and `ProviderConnectionState`. Deliberately *not* a
221
- * field on the error: structured clone across the service-worker `postMessage` boundary keeps
222
- * `message`, `stack` and `cause` but drops own-properties and normalizes a custom `name` to
223
- * `"Error"`.
224
- */
225
- type ProviderKind = "arkade" | "indexer";
226
- /**
227
- * A remote provider (Arkade operator or its indexer) is temporarily unreachable: transport
228
- * failure, timeout, or a 5xx/429. Retryable, unlike terminal config/auth/schema errors, which
229
- * stay a plain `Error`/{@link ArkError}. The low-level error is kept as {@link Error.cause}.
230
- */
231
- declare class ProviderUnavailableError extends Error {
232
- /** Always `true`: this error type only ever wraps retryable conditions. */
233
- readonly retryable = true;
234
- constructor(message: string, options?: {
235
- cause?: unknown;
236
- });
237
- }
238
- /**
239
- * A response doesn't reconcile with what the SDK submitted or validated (a checkpoint txid not
240
- * among those submitted, a commitment tx differing from the one validated at tree signing).
241
- * Terminal: the two are equal by construction in a well-formed exchange. `retryable` and `name`
242
- * don't cross the SW boundary (see {@link ProviderKind}), so every distinguishing detail belongs
243
- * in `message`.
244
- */
245
- declare class ServerResponseMismatchError extends Error {
246
- readonly retryable = false;
247
- constructor(message: string, options?: {
248
- cause?: unknown;
249
- });
250
- }
251
- /**
252
- * Try to convert an error to an ArkError class, returning undefined if the error is not an ArkError
253
- * @param error - The error to parse
254
- * @returns The parsed ArkError, or undefined if the error is not an ArkError
255
- */
256
- declare function maybeArkError(error: any): ArkError | undefined;
257
-
258
- /** Where the {@link OperatorInfo} used to construct a wallet came from. */
259
- type ServerInfoSource = "live" | "cache";
260
-
261
- /**
262
- * Batch namespace provides utilities for joining and processing batch session.
263
- * The batch settlement process involves multiple events, this namespace provides abstractions and types to handle them.
264
- * @see https://docs.arkadeos.com/learn/pillars/batch-swaps
265
- * @example
266
- * ```typescript
267
- * // use wallet handler or create a custom one
268
- * const handler = wallet.createBatchHandler(intentId, inputs, expectedRecipients, musig2session);
269
- *
270
- * const abortController = new AbortController();
271
- * // Get event stream from the operator provider
272
- * const eventStream = arkProvider.getEventStream(
273
- * abortController.signal,
274
- * ['your-topic-1', 'your-topic-2']
275
- * );
276
- *
277
- * // Join the batch and process events
278
- * try {
279
- * const commitmentTxid = await Batch.join(eventStream, handler);
280
- * console.log('Batch completed with commitment:', commitmentTxid);
281
- * } catch (error) {
282
- * console.error('Batch processing failed:', error);
283
- * } finally {
284
- * abortController.abort();
285
- * }
286
- * ```
287
- */
288
- declare namespace Batch {
289
- interface Handler {
290
- /**
291
- * Called on BatchStarted event.
292
- * @returns { skip: boolean } indicating whether the batch should be skipped or not.
293
- */
294
- onBatchStarted(event: BatchStartedEvent): Promise<{
295
- skip: boolean;
296
- }>;
297
- /**
298
- * Called when tree signing starts.
299
- * @param event The tree signing started event.
300
- * @param vtxoTree The unsigned virtual output tree, reconstructed from the TreeTxEvent events.
301
- * @returns Promise resolving to a boolean indicating whether to continue processing.
302
- */
303
- onTreeSigningStarted(event: TreeSigningStartedEvent, vtxoTree: TxTree): Promise<{
304
- skip: boolean;
305
- }>;
306
- /**
307
- * Called when tree nonces are received.
308
- * @param event The tree nonces event.
309
- * @returns Promise resolving to a boolean indicating whether signing is complete.
310
- */
311
- onTreeNonces(event: TreeNoncesEvent): Promise<{
312
- fullySigned: boolean;
313
- }>;
314
- /**
315
- * Called during batch finalization.
316
- * @param event The batch finalization event.
317
- * @param vtxoTree The signed virtual output tree, reconstructed from the TreeTxEvent events.
318
- * @param connectorTree The connector transaction tree, reconstructed from the TreeTxEvent events.
319
- */
320
- onBatchFinalization(event: BatchFinalizationEvent, vtxoTree?: TxTree, connectorTree?: TxTree): Promise<void>;
321
- /**
322
- * Called when batch finalization completes successfully.
323
- *
324
- * @param event - Batch finalized event
325
- */
326
- onBatchFinalized?(event: BatchFinalizedEvent): Promise<void>;
327
- /**
328
- * Called when batch processing fails.
329
- *
330
- * @param event - Batch failed event
331
- */
332
- onBatchFailed?(event: BatchFailedEvent): Promise<void>;
333
- /**
334
- * Called for each virtual output tree transaction chunk received during batch processing.
335
- *
336
- * @param event - Tree transaction event
337
- */
338
- onTreeTxEvent?(event: TreeTxEvent): Promise<void>;
339
- /**
340
- * Called for each tree signature event received during batch processing.
341
- *
342
- * @param event - Tree signature event
343
- */
344
- onTreeSignatureEvent?(event: TreeSignatureEvent): Promise<void>;
345
- }
346
- /**
347
- * Options for the join function.
348
- *
349
- * @property abortController - Abort controller used to cancel batch processing.
350
- * @property skipVtxoTreeSigning - Ignore events related to the virtual output tree musig2 signing session.
351
- * @property eventCallback - Callback invoked for each settlement event received while joining the batch.
352
- */
353
- type JoinOptions = Partial<{
354
- abortController: AbortController;
355
- skipVtxoTreeSigning: boolean;
356
- eventCallback: (event: SettlementEvent) => Promise<void>;
357
- }>;
358
- /**
359
- * Starts `stream` so the provider subscribes now, before the caller registers an intent whose
360
- * batch could otherwise start unseen. The returned iterator replays the first event; pass it
361
- * to {@link join}.
362
- */
363
- function prime(stream: AsyncIterableIterator<SettlementEvent>): AsyncIterableIterator<SettlementEvent>;
364
- /**
365
- * Start the state machine that will process the batch events and join a batch.
366
- * @param eventIterator - The events stream to process.
367
- * @param handler - How to react to events.
368
- * @param options - Options.
369
- */
370
- function join(eventIterator: AsyncIterableIterator<SettlementEvent>, handler: Handler, options?: JoinOptions): Promise<string>;
371
- }
372
-
373
- /**
374
- * Inputs a {@link ReceiveRotatorFactory} gets at boot to find the current display contract or
375
- * allocate a fresh descriptor. Allocation only: `resolveBoot` rebuilds the tapscript afterwards.
376
- */
377
- interface ReceiveRotatorBootOpts {
378
- walletRepository: WalletRepository;
379
- contractRepository: ContractRepository;
380
- serverPubKey: Uint8Array;
381
- /** When set, only this contract family is considered for the current display contract. */
382
- expectedContractType?: "default" | "delegate";
383
- /**
384
- * The wallet's baseline (index-0) x-only receive pubkey, used by {@link
385
- * WalletReceiveRotator.defaultBoot} when no tagged receive row exists. Such a wallet never
386
- * rotated L2, and the raw watermark can't be used: boarding shares the HD index stream, so a
387
- * boarding-only allocation may have advanced it.
388
- */
389
- baselineReceivePubKey?: Uint8Array;
390
- /** Receives rotation-failure and backoff diagnostics. Defaults to `console`. */
391
- logger?: Logger;
392
- }
393
- /**
394
- * Output of {@link ReceiveRotatorFactory.createReceiveRotator}: the rotator plus the receive
395
- * pubkey resolved at boot (existing tagged display contract's, or freshly allocated).
396
- */
397
- interface ReceiveRotatorBoot {
398
- rotator: WalletReceiveRotator;
399
- receivePubkey: Uint8Array;
400
- }
401
- /**
402
- * What {@link WalletReceiveRotator.resolveBoot} returns: the rotator, the offchain tapscript to
403
- * use (rebuilt to the boot pubkey if it differs), and the provider, which the wallet keeps so
404
- * spends route per-input signing through {@link DescriptorProvider.signWithDescriptor}.
405
- */
406
- interface ReceiveRotatorBootResult {
407
- rotator: WalletReceiveRotator;
408
- offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script;
409
- provider: DescriptorProvider;
410
- }
411
- /**
412
- * Opt-in {@link DescriptorProvider} extension for providers driving HD receive rotation
413
- * (implemented by {@link HDDescriptorProvider}). Kept out of the core interface so
414
- * allocate-and-sign providers needn't know the receive lifecycle; without it the wallet uses
415
- * {@link WalletReceiveRotator.defaultBoot}.
416
- */
417
- interface ReceiveRotatorFactory {
418
- createReceiveRotator(opts: ReceiveRotatorBootOpts): Promise<ReceiveRotatorBoot | undefined>;
419
- }
420
- /**
421
- * Parse the trailing HD child index from a materialized signing descriptor
422
- * (`tr(...xpub.../0/<index>)`). Returns 0 when absent or unparseable: restore registers the
423
- * index-0 baseline untagged, so a missing descriptor legitimately means 0.
424
- */
425
- declare function signingDescriptorIndex(descriptor: unknown): number;
426
- /**
427
- * Strict {@link signingDescriptorIndex}: `undefined` instead of the 0 fallback, for callers
428
- * (e.g. watermark moves) where mapping "unparseable" to 0 would silently do nothing.
429
- */
430
- declare function strictSigningDescriptorIndex(descriptor: string): number | undefined;
431
- /** Minimal logging surface the rotator needs; `console` or any structured logger satisfies it. */
432
- interface Logger {
433
- error(message: string, ...args: unknown[]): void;
434
- }
435
- /**
436
- * The wallet surface the rotator needs at runtime. An interface to avoid a circular dependency on
437
- * `wallet.ts`; `Wallet` satisfies it structurally.
438
- */
439
- interface RotatableWallet {
440
- readonly defaultContractScript: string;
441
- readonly network: {
442
- hrp: string;
443
- };
444
- readonly arkServerPublicKey: Uint8Array;
445
- readonly offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script;
446
- /**
447
- * @internal Sole sanctioned write path for `offchainTapscript` after construction; called
448
- * once per rotation after the new display contract is persisted.
449
- */
450
- setOffchainTapscriptForRotation(tapscript: DefaultVtxo.Script | DelegateVtxo.Script): void;
451
- getContractManager(): Promise<IContractManager>;
452
- getAddress(): Promise<string>;
453
- }
454
- /**
455
- * Owns the wallet's HD receive-rotation lifecycle; exists only when `walletMode` resolves to a
456
- * {@link DescriptorProvider}.
457
- *
458
- * 1. `resolveBoot()` (before Wallet construction): reuse the display contract's pubkey or
459
- * allocate the first descriptor.
460
- * 2. `install(wallet)`: subscribe to `vtxo_received` and rotate on matching events.
461
- * 3. `dispose()`: unsubscribe and drain any in-flight rotation.
462
- *
463
- * NArk parity: the provider is a pure allocator; the current address comes from the contract
464
- * repository, not the provider.
465
- */
466
- declare class WalletReceiveRotator {
467
- private readonly provider;
468
- private unsubscribe?;
469
- private chain;
470
- /**
471
- * Script of the latest tagged display contract, retired by the next `rotate()`. `undefined`
472
- * means the untagged index-0 baseline is displayed, which must NOT be deactivated.
473
- */
474
- private currentTaggedScript;
475
- /** Drives exponential backoff so a broken provider isn't hammered on every inbound VTXO. */
476
- private consecutiveFailures;
477
- /** Unix ms before which `vtxo_received` events skip rotation; 0 = no backoff. */
478
- private nextRotationAllowedAt;
479
- private readonly logger;
480
- private constructor();
481
- /**
482
- * Resolve `walletMode` to a provider and build the rotator (via its
483
- * {@link ReceiveRotatorFactory}, else {@link defaultBoot}). Returns `undefined` for the
484
- * static path.
485
- *
486
- * Resolution errors propagate for `'hd'` and explicit providers (degrading would hide
487
- * misconfig); a {@link NonRangeableDescriptorError} is swallowed only under `'auto'`, for
488
- * back-compat with identities whose descriptor isn't rangeable.
489
- */
490
- static resolveBoot(config: WalletConfig, setup: ReceiveRotatorBootOpts & {
491
- offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script;
492
- }): Promise<ReceiveRotatorBootResult | undefined>;
493
- /**
494
- * Default boot any {@link ReceiveRotatorFactory.createReceiveRotator} can delegate to: take
495
- * the current display contract from the repository, else allocate/derive the receive pubkey.
496
- * Tapscript construction is deliberately left to `resolveBoot`.
497
- */
498
- static defaultBoot(provider: DescriptorProvider, opts: ReceiveRotatorBootOpts): Promise<ReceiveRotatorBoot>;
499
- /**
500
- * Subscribe to `vtxo_received` and rotate whenever the current display contract receives
501
- * funds. Old display contracts stay watched, so earlier shared addresses keep crediting.
502
- */
503
- install(wallet: RotatableWallet): Promise<void>;
504
- /**
505
- * One rotation attempt with exponential backoff. Errors are logged, not rethrown, so `chain`
506
- * never rejects and the next `vtxo_received` still runs.
507
- */
508
- private runRotateWithBackoff;
509
- /** Wait for any in-flight rotation to complete (mainly for tests). */
510
- drain(): Promise<void>;
511
- /**
512
- * Run `fn` on the rotation chain. {@link Wallet.rotateServerSigner} uses it because both it
513
- * and `rotate()` swap `offchainTapscript`; interleaving could tear the visible receive state.
514
- * The chain advances even if `fn` rejects (the caller still sees the rejection).
515
- */
516
- runExclusive<T>(fn: () => Promise<T>): Promise<T>;
517
- /**
518
- * Unsubscribe first so no late event queues work, then drain so an in-flight
519
- * `createContract` finishes before the contract manager disposes.
520
- */
521
- dispose(): Promise<void>;
522
- /**
523
- * Allocate the next descriptor, register it as the new tagged display contract (same
524
- * default/delegate shape), swap it in, and mark the previous tagged one `inactive` (still
525
- * watched; it just stops being advertised). The untagged index-0 baseline is never retired.
526
- */
527
- private rotate;
528
- }
529
-
530
- /**
531
- * Capability a wallet exposes so descriptor-blind consumers (Boltz swaps, other plugins) can bind
532
- * artifacts to the wallet's current HD index and later enumerate every used index. Probed
533
- * structurally ({@link isHDWalletCapable}) rather than widening `IWallet`, so plugins keep working
534
- * against older wallets; a static wallet answers "no HD state" through the same methods.
535
- */
536
- interface HDWalletCapable {
537
- /**
538
- * The descriptor at the wallet's current receive index, or `undefined` for
539
- * static / `auto` wallets and HD wallets that have never rotated. Callers
540
- * fall back to the identity key.
541
- */
542
- getCurrentSigningDescriptor(): Promise<string | undefined>;
543
- /**
544
- * Every descriptor the wallet may hold keys under, ascending by index: the allocation
545
- * watermark's band plus any descriptor persisted on a contract. Empty for static wallets.
546
- * `lookAhead` appends that many past the watermark without advancing it, for restore probing.
547
- */
548
- getUsedSigningDescriptors(opts?: {
549
- lookAhead?: number;
550
- }): Promise<string[]>;
551
- /**
552
- * An {@link Identity} whose keys and signatures are those of `descriptor`; the wallet
553
- * identity itself when `descriptor` is the identity's own key.
554
- *
555
- * Throws {@link ForeignDescriptorError} for a descriptor this wallet cannot sign for — never
556
- * substitutes another key, which would sign happily and surface only as a rejected tx or a
557
- * dead script. The returned identity must actually sign (`sign`, `signMessage`,
558
- * `signerSession`): `contractSigner` refuses a watch-only one as `WalletCannotSignError`,
559
- * which would otherwise pass every check and throw after the contract is funded.
560
- */
561
- signerForDescriptor(descriptor: string): Promise<Identity>;
562
- }
563
- /**
564
- * Thrown by {@link HDWalletCapable.signerForDescriptor} when the wallet holds no key for the
565
- * descriptor, so callers can tell "not my key" from transient signing failures.
566
- */
567
- declare class ForeignDescriptorError extends Error {
568
- readonly descriptor: string;
569
- readonly name = "ForeignDescriptorError";
570
- constructor(descriptor: string, options?: {
571
- cause?: unknown;
572
- });
573
- }
574
- /**
575
- * Thrown by `Wallet.getNewAddresses({ forceNew: true })` when there is no HD stream to advance
576
- * (`walletMode: 'static'` / `'auto'`, or a {@link DescriptorProvider} that declined). Typed
577
- * rather than a silent repeat, which would surface only as two payers sharing a script.
578
- */
579
- declare class WalletCannotAllocateAddressError extends Error {
580
- readonly name = "WalletCannotAllocateAddressError";
581
- constructor(reason: string, options?: {
582
- cause?: unknown;
583
- });
584
- }
585
- /** Anything that can derive and sign for a descriptor it claims. */
586
- type DescriptorOwner = Pick<DescriptorProvider, "isOurs" | "signWithDescriptor" | "signMessageWithDescriptor">;
587
- /**
588
- * The identity that signs `descriptor`, or {@link ForeignDescriptorError}. Shared by every
589
- * {@link HDWalletCapable.signerForDescriptor} so page- and worker-side wallets cannot drift into
590
- * a signer that passes a pubkey check and then throws on every signature, after funding.
591
- */
592
- declare function resolveDescriptorSigner(descriptor: string, identity: Identity, provider?: DescriptorOwner): Promise<Identity>;
593
- /** Structural type guard for {@link HDWalletCapable}. */
594
- declare function isHDWalletCapable(value: unknown): value is HDWalletCapable;
595
- /**
596
- * Allocating a *fresh* index — strictly more than {@link HDWalletCapable}'s descriptor awareness.
597
- * A separate probe because widening that guard would silently demote every wallet implementing
598
- * only its original surface (including older SDKs') from HD-capable to static.
599
- */
600
- interface HDAllocationCapable {
601
- /**
602
- * The signing descriptor a new artifact (swap, invoice, contract) should bind to. **The
603
- * wallet decides**: an HD wallet allocates a fresh index, advancing the watermark; a static
604
- * wallet answers with its one `tr(pubkey)` every time. Consumers must not probe the wallet's
605
- * shape or mint key material; they use the answer with
606
- * {@link HDWalletCapable.signerForDescriptor}.
607
- *
608
- * `undefined` only for implementations that genuinely cannot answer (`Wallet` always
609
- * answers); callers then fall back to the identity key — never a random one.
610
- *
611
- * Unlike {@link HDWalletCapable.getCurrentSigningDescriptor}, which peeks (two artifacts bound
612
- * to a peek share a key). Per-call uniqueness is a wallet property, so anything deriving
613
- * per-artifact secrets must check the descriptor's shape, not the wallet's.
614
- */
615
- getNextSigningDescriptor(): Promise<string | undefined>;
616
- /**
617
- * Move the allocation watermark to `descriptor`'s index so later allocations cannot reissue
618
- * it. Monotonic; a static wallet accepts its own descriptor as a no-op.
619
- *
620
- * Throws on a descriptor this wallet cannot derive, or an HD descriptor with no parseable
621
- * trailing index: mapping those to index 0 would let a restored artifact's index be reissued.
622
- */
623
- advanceSigningDescriptorWatermark(descriptor: string): Promise<void>;
624
- }
625
- /** Structural type guard for {@link HDAllocationCapable}. */
626
- declare function isHDAllocationCapable(value: unknown): value is HDAllocationCapable;
627
- /**
628
- * Minting addresses to hand out: beyond {@link HDAllocationCapable}'s bare index, the wallet
629
- * builds the scripts, persists them as watched contracts, and reports the rows. A third probe
630
- * for the same no-silent-demotion reason.
631
- */
632
- interface AddressAllocationCapable {
633
- /**
634
- * Fresh addresses of each requested type from one newly allocated HD index, persisted and
635
- * watched. An HD wallet burns an index; a wallet with no stream answers with its existing
636
- * display addresses or, under `forceNew`, throws {@link WalletCannotAllocateAddressError}.
637
- *
638
- * Unlike {@link HDAllocationCapable.getNextSigningDescriptor}, allocation and script
639
- * registration happen together: split across a process boundary, a failed registration
640
- * leaves a burnt index and an unwatched address.
641
- */
642
- getNewAddresses(opts?: GetNewAddressesOptions): Promise<NewAddress[]>;
643
- }
644
- /** Structural type guard for {@link AddressAllocationCapable}. */
645
- declare function isAddressAllocationCapable(value: unknown): value is AddressAllocationCapable;
646
-
647
- /**
648
- * Cap on HD descriptors getUsedSigningDescriptors() materializes past the watermark (bounds
649
- * plugin/restore probes; the watermark itself is not moved).
650
- */
651
- declare const MAX_USED_SIGNING_DESCRIPTORS_LOOK_AHEAD = 1000;
652
- type IncomingFunds = {
653
- type: "utxo";
654
- coins: Coin[];
655
- } | {
656
- type: "vtxo";
657
- newVtxos: ExtendedVirtualCoin[];
658
- spentVtxos: ExtendedVirtualCoin[];
659
- };
660
- /**
661
- * Capability contract for a wallet that can report newly received funds.
662
- *
663
- * Kept as its own interface rather than on the wallet interfaces because not every wallet
664
- * implements it (the service-worker and Expo wallets do not), matching the repo's
665
- * capability-interface pattern. Lets helpers depend on just this one method instead of the
666
- * whole Wallet class.
667
- */
668
- interface NotifiesIncomingFunds {
669
- notifyIncomingFunds(eventCallback: (coins: IncomingFunds) => void): Promise<() => void>;
670
- }
671
-
672
- /**
673
- * Structural rather than {@link ContractWithVtxos} so the worker's repository-built snapshot
674
- * (VTXOs without `contractScript`) classifies without a parallel array.
675
- */
676
- type PendingRecoverySnapshot = Parameters<typeof selectPendingRecoveryOutpoints>[0];
677
- /**
678
- * Boarding UTXOs grouped by boarding address, with that address's signer. A flat
679
- * {@link ExtendedCoin} can't carry it: it keeps only the encoded leaves, not the owning script's
680
- * `serverPubKey` or CSV delay, which deprecated-signer classification needs.
681
- */
682
- interface BoardingUtxoGroup {
683
- /** Tapscript of the boarding address the coins sit on. */
684
- tapscript: DefaultVtxo.Script;
685
- /** Operator key of that address, normalized x-only hex. */
686
- serverPubKey: string;
687
- /** CSV exit timelock decoded from THIS tapscript's exit leaf. */
688
- csvTimelock: RelativeTimelock;
689
- coins: ExtendedCoin[];
690
- }
691
- /**
692
- * Why a VTXO at an arkadeCash address could neither be swept nor imported for
693
- * recovery by {@link Wallet.claimCash}.
694
- *
695
- * - `subdust` — below dust, so it sits at an OP_RETURN script with no spendable
696
- * leaf. Unspendable as cash; `createCash` prevents minting these.
697
- * - `already-spent` — someone else claimed it first.
698
- * - `exited` — unilaterally exited onchain, so the offchain sweep cannot reach it;
699
- * `Unroll.completeUnroll` is the remedy.
700
- * - `has-assets` — asset-bearing; the BTC-only sweep would burn the assets.
701
- * - `sweep-failed` — spendable, but its own sweep was rejected.
702
- * - `recovery-failed` — operator-swept and recoverable in principle, but the
703
- * import that hands it to the wallet's recovery machinery failed.
704
- *
705
- * An output the operator swept whose import *succeeds* is not reported here — it lands
706
- * in {@link ArkadeCashClaimResult.recovering} instead.
707
- */
708
- type ArkadeCashUnclaimedReason = "subdust" | "already-spent" | "exited" | "has-assets" | "sweep-failed" | "recovery-failed";
709
- /** Minimal outpoint + value identifying a VTXO in a claim report. */
710
- interface ArkadeCashVtxoRef {
711
- txid: string;
712
- vout: number;
713
- /** Value in satoshis. */
714
- value: number;
715
- }
716
- /** A VTXO {@link Wallet.claimCash} left behind, with the reason why. */
717
- interface ArkadeCashUnclaimedVtxo extends ArkadeCashVtxoRef {
718
- reason: ArkadeCashUnclaimedReason;
719
- }
720
- /**
721
- * Outcome of {@link Wallet.claimCash}: what was swept instantly, what was
722
- * imported for background recovery, and what was left behind.
723
- *
724
- * The shape is open — further buckets may be added as more of the
725
- * non-sweepable states become claimable.
726
- */
727
- interface ArkadeCashClaimResult {
728
- /**
729
- * The Arkade transactions registered by successful sweeps, each with the sats it paid this
730
- * wallet.
731
- */
732
- claims?: ArkadeCashTx[];
733
- /** Satoshis swept to this wallet instantly (the thin single-key sweep). */
734
- swept: number;
735
- /**
736
- * Operator-swept outputs imported for recovery. These funds are not in the
737
- * wallet yet: a swept VTXO can only move through a settlement, so
738
- * `claimCash` imports it as a signable contract and hands it to the
739
- * wallet's own recovery machinery, which settles it back (rotation-aware)
740
- * on the normal retry cadence. The amount arrives as a fresh VTXO once
741
- * that settlement finalizes.
742
- */
743
- recovering: {
744
- /** Satoshis imported for recovery. */
745
- amount: number;
746
- vtxos: ArkadeCashVtxoRef[];
747
- };
748
- unclaimed: {
749
- /** Satoshis left behind. */
750
- amount: number;
751
- vtxos: ArkadeCashUnclaimedVtxo[];
752
- };
753
- }
754
- /**
755
- * Thrown when {@link Wallet.createCash}'s `send` fails after the transaction may already have been
756
- * submitted. `cash` carries the private key of the funded output: discard it and the sats may be
757
- * stranded. Persist it; {@link Wallet.claimCash} recovers the funds whether or not the send landed.
758
- */
759
- declare class ArkadeCashCreateError extends Error {
760
- /** The encoded arkadeCash token controlling the funded output. */
761
- readonly cash: string;
762
- /** The original failure from `send`. */
763
- readonly cause: unknown;
764
- constructor(
765
- /** The encoded arkadeCash token controlling the funded output. */
766
- cash: string,
767
- /** The original failure from `send`. */
768
- cause: unknown);
769
- }
770
- /**
771
- * Thrown by {@link Wallet.claimCash} when the arkadeCash comes from another operator. Its signer
772
- * is not the connected operator's active signer, and it is not in the operator's list of
773
- * deprecated signers either. Nothing is queried or signed. To claim it, connect to the operator
774
- * that issued it.
775
- */
776
- declare class ArkadeCashOperatorMismatchError extends Error {
777
- /** The signer in the arkadeCash script, x-only hex. */
778
- readonly cashSignerPubKey: string;
779
- /** The active signer of the connected operator, x-only hex. */
780
- readonly activeSignerPubKey: string;
781
- constructor(
782
- /** The signer in the arkadeCash script, x-only hex. */
783
- cashSignerPubKey: string,
784
- /** The active signer of the connected operator, x-only hex. */
785
- activeSignerPubKey: string);
786
- }
787
- /**
788
- * Freshness of provider-backed sync (operator info source + indexer-sync health). Balances/VTXOs
789
- * are always served from the repository regardless. `syncing` says a provider sync is in flight
790
- * right now; optional so adding it breaks no implementer, {@link ReadonlyWallet} always sets it.
791
- */
792
- type ProviderConnectionState = {
793
- mode: "online";
794
- syncing?: boolean;
795
- source: "live";
796
- lastOnlineAt: number;
797
- } | {
798
- mode: "degraded";
799
- syncing?: boolean;
800
- source: "cache" | "repository";
801
- provider: ProviderKind;
802
- reason: string;
803
- lastOnlineAt?: number;
804
- };
805
- declare class ReadonlyWallet implements IReadonlyWallet {
806
- readonly identity: ReadonlyIdentity;
807
- readonly network: Network;
808
- readonly onchainProvider: OnchainProvider;
809
- /** Narrowed so a readonly wallet can't grow a `submitTx` use; `Wallet` re-widens it. */
810
- protected readonly arkProvider: Pick<OperatorProvider, "getInfo">;
811
- readonly indexerProvider: IndexerProvider;
812
- readonly dustAmount: bigint;
813
- readonly walletRepository: WalletRepository;
814
- readonly contractRepository: ContractRepository;
815
- readonly delegateProvider?: DelegateProvider | undefined;
816
- protected lazyInitialization: boolean;
817
- private boardingLoaded;
818
- private _contractManager?;
819
- private _contractManagerInitializing?;
820
- protected readonly watcherConfig?: ReadonlyWalletConfig["watcherConfig"];
821
- protected vtxoSyncOverlapMs?: number;
822
- protected copySyncOverlapTo(wallet: ReadonlyWallet): void;
823
- /** Opt-in intent-lifecycle repository; `undefined` ⇒ intent persistence is a no-op. */
824
- intentRepository?: BatchRegistrationRepository;
825
- /**
826
- * **Experimental / inert.** Opt-in virtual-tx repository, exposed so callers can pass it to
827
- * {@link Unroll.Session.create} as a best-effort raw-tx cache. Normal sync never writes it.
828
- */
829
- virtualTxRepository?: VirtualTxRepository;
830
- /** Opt-in exit-data capture settings; see {@link StorageConfig.exitDataCapture}. */
831
- exitDataCapture?: {
832
- mode?: ExitCaptureMode;
833
- minExitWorthSats?: number;
834
- sources?: ExitDataSource[];
835
- };
836
- private readonly _assetManager;
837
- readonly walletContractTimelocks: RelativeTimelock[];
838
- protected _pendingSpendOutpoints: Set<string>;
839
- protected _heldOutpoints: Set<string>;
840
- /** Activity resolvers consumed by {@link getActivityHistory}. */
841
- readonly activity: ActivityRegistry;
842
- get assetManager(): IReadonlyAssetManager;
843
- /**
844
- * Active receive tapscript; written only by {@link Wallet.setOffchainTapscriptForRotation}
845
- * (sole intended caller: {@link WalletReceiveRotator.rotate}).
846
- */
847
- protected _offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script;
848
- /**
849
- * Current boarding tapscript (QR / onboarding target); written only by
850
- * {@link Wallet.setBoardingTapscriptForRotation}. Static / `auto` wallets never rotate it.
851
- */
852
- protected _boardingTapscript: DefaultVtxo.Script;
853
- /**
854
- * Active operator signer (x-only); written only by
855
- * {@link Wallet.setArkServerPublicKeyForRotation} when arkd rotates its signer mid-session.
856
- */
857
- protected _arkServerPublicKey: Bytes;
858
- /**
859
- * Whether the LATEST operator info resolution was live or fell back to the cached snapshot.
860
- * Updated on every {@link getOperatorInfo} read so recovery (or a fresh fallback) is reflected.
861
- */
862
- protected _serverInfoSource: ServerInfoSource;
863
- /**
864
- * Epoch-ms of the last live operator contact, or the cached snapshot's `savedAt` when the
865
- * latest resolution fell back.
866
- */
867
- protected _serverInfoLastOnlineAt?: number;
868
- /** @see {@link _serverInfoSource} */
869
- get serverInfoSource(): ServerInfoSource;
870
- /**
871
- * Composed provider-connection freshness: degraded on `arkade` (`cache`) when the latest
872
- * operator info resolution fell back, else degraded on `indexer` (`repository`) when an
873
- * initialized contract manager has, else online. Never forces a `ContractManager` to
874
- * construct, so it is safe for readonly callers.
875
- */
876
- getProviderConnectionState(): ProviderConnectionState;
877
- /**
878
- * The contract manager's sync health **without initializing it** (`online` if none exists),
879
- * so unlike {@link getContractManager} it never triggers a remote sync.
880
- */
881
- getContractSyncState(): ContractSyncState;
882
- protected constructor(identity: ReadonlyIdentity, network: Network, onchainProvider: OnchainProvider,
883
- /** Narrowed so a readonly wallet can't grow a `submitTx` use; `Wallet` re-widens it. */
884
- arkProvider: Pick<OperatorProvider, "getInfo">, indexerProvider: IndexerProvider, arkServerPublicKey: Bytes, offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script, boardingTapscript: DefaultVtxo.Script, dustAmount: bigint, walletRepository: WalletRepository, contractRepository: ContractRepository, delegateProvider?: DelegateProvider | undefined, watcherConfig?: ReadonlyWalletConfig["watcherConfig"], walletContractTimelocks?: RelativeTimelock[]);
885
- /**
886
- * x-only hex → cutoff of the operator's deprecated signers, cached for OFFLINE read/watch.
887
- * Boarding watch/history fan out over {current} ∪ this set so deposits at addresses minted
888
- * under a rotated signer stay watched. Deliberately NOT used by the spend path:
889
- * {@link getBoardingUtxos} stays current-signer-only (a deprecated-signer input in a plain
890
- * settle() is rejected; recovery goes through the migration API).
891
- */
892
- protected _deprecatedSigners: Map<string, bigint>;
893
- /**
894
- * Refresh the cached deprecated-signer set from operator info; feeds
895
- * {@link pendingRecoveryOutpoints}. Lenient: a malformed entry is skipped, never fatal.
896
- */
897
- refreshDeprecatedSigners(info: {
898
- deprecatedSigners?: readonly {
899
- pubkey?: string;
900
- cutoffDate?: bigint;
901
- }[];
902
- }): void;
903
- /** Boarding WATCH/HISTORY signer set: current ∪ deprecated (spend stays current-only). */
904
- protected watchedBoardingSigners(): Set<string>;
905
- /**
906
- * `serverPubKey` defaults to the live key; spend paths that snapshot it
907
- * against mid-flight rotation pass their snapshot, so the check reads from
908
- * one rotation epoch.
909
- */
910
- protected recipientAddressContext(serverPubKey?: Bytes): RecipientArkadeAddressContext;
911
- /** Currently-active receive tapscript; changes only on receive rotation. */
912
- get offchainTapscript(): DefaultVtxo.Script | DelegateVtxo.Script;
913
- /** Current active server signer (x-only, 32 bytes); changes only on server-signer rotation. */
914
- get arkServerPublicKey(): Bytes;
915
- /**
916
- * Info for the connected operator: live wins, a retryable failure falls back to
917
- * the boot snapshot, a terminal one propagates. Live because `signerPubkey`,
918
- * `checkpointTapscript` and `fees` move on rotation, and a covenant built against a
919
- * superseded signer is unspendable.
920
- *
921
- * @remarks Reading does NOT re-pin the wallet ({@link arkServerPublicKey}, {@link dustAmount},
922
- * tapscripts), so inside a rotation window this can report epoch N+1 while the wallet spends
923
- * on N; the provider's `onServerInfoChanged` closes the window. Pass `{ requireLive: true }`
924
- * before binding the answer into a covenant to fail closed instead of getting the snapshot.
925
- *
926
- * @returns The operator's info
927
- * @see OperatorInfo
928
- */
929
- getOperatorInfo(opts?: GetOperatorInfoOptions): Promise<OperatorInfo>;
930
- /** @deprecated Use {@link getOperatorInfo}. */
931
- getArkadeInfo(opts?: GetOperatorInfoOptions): Promise<OperatorInfo>;
932
- /**
933
- * Chain reads against this wallet's operator for scripts it does not own, bound to the wallet's
934
- * own (possibly Expo/injected) `indexerProvider`. `getVtxos` normalizes via
935
- * {@link getNormalizedVtxos}. A bound object, not the provider, so an `IReadonlyWallet`
936
- * holder gets these two reads and nothing else.
937
- */
938
- getArkadeReader(): Promise<ArkadeReader>;
939
- /**
940
- * Current boarding tapscript (on-chain onboarding target); changes only when a fresh boarding
941
- * address is explicitly allocated.
942
- */
943
- get boardingTapscript(): DefaultVtxo.Script;
944
- /**
945
- * Fired after boarding rotation so a live {@link notifyIncomingFunds} watcher re-subscribes
946
- * to the fresh address in-session instead of missing deposits until its next re-init.
947
- */
948
- private readonly _boardingRotationListeners;
949
- /** Register a listener invoked synchronously after each boarding rotation. */
950
- protected onBoardingRotation(listener: () => void): () => void;
951
- /** A throwing listener is isolated: it can't break the rotation or starve siblings. */
952
- protected notifyBoardingRotation(): void;
953
- /** Shared setup for ReadonlyWallet.create() and Wallet.create(). */
954
- protected static setupWalletConfig(config: ReadonlyWalletConfig, pubKey: Uint8Array): Promise<{
955
- arkProvider: OperatorProvider;
956
- indexerProvider: IndexerProvider;
957
- onchainProvider: OnchainProvider | EsploraProvider;
958
- network: Network;
959
- networkName: NetworkName;
960
- serverPubKey: Uint8Array<ArrayBufferLike>;
961
- offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script;
962
- boardingTapscript: DefaultVtxo.Script;
963
- dustAmount: bigint;
964
- walletRepository: WalletRepository | IndexedDBWalletRepository;
965
- contractRepository: ContractRepository;
966
- info: OperatorInfo;
967
- serverInfoSource: ServerInfoSource;
968
- serverInfoLastOnlineAt: number | undefined;
969
- delegateProvider: DelegateProvider | undefined;
970
- walletContractTimelocks: RelativeTimelock[];
971
- }>;
972
- /**
973
- * Create a readonly wallet for querying balances, addresses, and history.
974
- *
975
- * @param config - Readonly wallet configuration
976
- * @returns A readonly wallet instance
977
- */
978
- static create<T extends ReadonlyWallet>(this: {
979
- prototype: T;
980
- }, config: ReadonlyWalletConfig): Promise<T>;
981
- static create(config: ReadonlyWalletConfig): Promise<ReadonlyWallet>;
982
- get arkAddress(): ArkAddress;
983
- /**
984
- * Get the pkScript hex for the wallet's primary offchain address.
985
- * For the full wallet-owned script set registered in ContractManager, use getWalletScripts().
986
- */
987
- get defaultContractScript(): string;
988
- /** Returns the wallet's Arkade address. */
989
- getAddress(): Promise<string>;
990
- /** Returns the onchain boarding address used to move funds into Arkade. */
991
- getBoardingAddress(): Promise<string>;
992
- /**
993
- * Return the wallet's combined onchain and offchain balances.
994
- */
995
- getBalance(): Promise<WalletBalance>;
996
- /** Cached balance; inspect connection state and boarding.loaded before displaying zeros. */
997
- getStoredBalance(): Promise<WalletBalance>;
998
- private balanceFromSnapshot;
999
- /**
1000
- * Return virtual outputs tracked by the wallet, including escrowed, locked and
1001
- * awaiting-recovery funds. Coin selection must use {@link getSpendableVtxos}: feeding this
1002
- * into `settle({ inputs })` or `send({ selectedVtxos })` bypasses the generic-spending gate.
1003
- *
1004
- * @param filter - Optional flags controlling whether recoverable or unrolled VTXOs are included
1005
- */
1006
- getVtxos(filter?: GetVtxosFilter): Promise<NormalizedExtendedVirtualCoin[]>;
1007
- /** Cached VTXOs; may be empty before the first sync. Never use for coin selection. */
1008
- getStoredVtxos(filter?: GetVtxosFilter): Promise<NormalizedExtendedVirtualCoin[]>;
1009
- /**
1010
- * @internal The stored VTXOs {@link reserveVtxos} holds, minus any being spent: for renewal,
1011
- * which skips them, to report the ones it would have renewed. No sync.
1012
- */
1013
- getHeldVtxos(): Promise<NormalizedExtendedVirtualCoin[]>;
1014
- /** @inheritdoc */
1015
- getSpendableVtxos(filter?: GetSpendableVtxosFilter): Promise<NormalizedExtendedVirtualCoin[]>;
1016
- /**
1017
- * Debug-log any explicit input generic selection would have excluded. Explicit-input APIs stay
1018
- * ungated on purpose (naming an outpoint *is* the intent, and is how an escrowed deposit is
1019
- * recovered), so this only makes the crossing visible — notably
1020
- * `settle({ inputs: await wallet.getVtxos() })`. Never throws. Public for worker and plugins.
1021
- */
1022
- logUngatedInputs(source: string, inputs: readonly {
1023
- txid: string;
1024
- vout: number;
1025
- script?: string;
1026
- }[]): Promise<void>;
1027
- /**
1028
- * Past-cutoff-signer contracts as a script-level exclusion: the `pendingRecovery` answer for a
1029
- * caller-supplied input without a synced snapshot (a swept outpoint is unspendable anyway).
1030
- */
1031
- private expiredSignerExclusion;
1032
- /** The intent store's lock set. Fails open, like every other read of it. */
1033
- protected lockedOutpoints(): Promise<Set<string>>;
1034
- /**
1035
- * One contract+VTXO read (which may sync against the indexer). Callers needing several views
1036
- * derive them all from one snapshot so they answer about the same instant.
1037
- */
1038
- protected contractSnapshot(filter?: GetSpendableVtxosFilter, options?: {
1039
- unspentOnly?: boolean;
1040
- }): Promise<ContractWithVtxos[]>;
1041
- protected contractSnapshotStored(): Promise<ContractWithVtxos[]>;
1042
- /**
1043
- * The two exclusion sets the gate is made of, derived from one snapshot so
1044
- * {@link getSpendableVtxos} and the balance answer about the same instant.
1045
- */
1046
- private spendabilityView;
1047
- /** The capability probes {@link computeOffchainBalance} needs, over one snapshot. */
1048
- private balanceCapabilities;
1049
- /**
1050
- * Outpoints of not-yet-swept VTXOs whose deprecated signer is past its cutoff (EXPIRED) —
1051
- * unspendable until they recover; excluded by {@link getBalance} and {@link getSpendableVtxos}.
1052
- * Takes a fresh (syncing) snapshot; callers that hold one or must not sync use
1053
- * {@link pendingRecoveryOutpointsIn}.
1054
- */
1055
- pendingRecoveryOutpoints(): Promise<Set<string>>;
1056
- /** {@link pendingRecoveryOutpoints} over a caller-held snapshot; no I/O of its own. */
1057
- pendingRecoveryOutpointsIn(snapshot: PendingRecoverySnapshot): Set<string>;
1058
- private selectPendingRecovery;
1059
- /**
1060
- * Return wallet transaction history derived from Arkade state and boarding transactions.
1061
- */
1062
- getTransactionHistory(): Promise<ArkTransaction[]>;
1063
- /**
1064
- * Wallet history grouped by registered activity resolvers. With no resolver match,
1065
- * rows bucket by transaction key so send/change pairs stay together.
1066
- */
1067
- getActivityHistory(): Promise<Activity[]>;
1068
- /**
1069
- * Clear the global VTXO sync cursor, forcing a full re-bootstrap on next sync.
1070
- * Useful for recovery after indexer reprocessing or debugging.
1071
- */
1072
- clearSyncCursor(): Promise<void>;
1073
- /**
1074
- * Wipe all locally persisted wallet data (VTXOs, UTXOs, history, sync
1075
- * cursor, contracts, intents). Create a fresh wallet instance afterward.
1076
- * Intents are kept while any may still be held by arkd, so a later
1077
- * reconciliation can release them with their stored proofs.
1078
- */
1079
- clear(): Promise<void>;
1080
- private clearIntents;
1081
- /**
1082
- * On-chain (P2TR) addresses of every boarding tapscript this wallet uses, current plus
1083
- * historical rotated, so deposits at old addresses still surface; {@link getBoardingAddress}
1084
- * stays single-valued.
1085
- */
1086
- getBoardingAddresses(): Promise<string[]>;
1087
- /** Transaction history across the wallet's boarding addresses (current + historical). */
1088
- getBoardingTxs(): Promise<{
1089
- boardingTxs: ArkTransaction[];
1090
- commitmentsToIgnore: Set<string>;
1091
- }>;
1092
- /**
1093
- * Every boarding tapscript whose UTXOs belong to this wallet (rotation spreads them over
1094
- * several addresses), deduplicated by scriptPubKey. Includes index-0 `default` rows when a
1095
- * baseline boarding script coalesced with one.
1096
- *
1097
- * @param allowedSigners - x-only operator keys whose persisted boarding rows are included;
1098
- * defaults to the current signer (the foreign-ASP guard). Migration widens it to old signers.
1099
- * The baseline and current display tapscript are included regardless.
1100
- */
1101
- protected getBoardingTapscripts(allowedSigners?: Set<string>): Promise<DefaultVtxo.Script[]>;
1102
- /**
1103
- * Fetch and cache onchain inputs (UTXOs) received at the boarding addresses
1104
- * of the given signer set, grouped per boarding address so the caller keeps
1105
- * the address↔signer association that {@link ExtendedCoin} cannot carry
1106
- * (it retains only the encoded leaves/tapTree the spend needs, not the
1107
- * `DefaultVtxo.Script` and its `serverPubKey`/CSV delay).
1108
- *
1109
- * Per group: `getCoins` (a failure throws), then `ContractManager.syncOnchain`,
1110
- * then the fetched coins minus stored-spent outpoints → {@link extendCoinWithTapscript}.
1111
- * It does not call `getInfo()`; the caller supplies the allowed signer set.
1112
- *
1113
- * @param allowedSigners - x-only-hex operator keys whose boarding addresses to
1114
- * fetch (passed through to {@link getBoardingTapscripts}).
1115
- * @param skipFailedSigners - x-only-hex server keys whose address lookups may fail: that
1116
- * address is left out of the result and its cache untouched, instead of failing the whole
1117
- * fetch. A lookup under any other signer still rejects.
1118
- */
1119
- getBoardingUtxosForSigners(allowedSigners: Set<string>, skipFailedSigners?: ReadonlySet<string>): Promise<BoardingUtxoGroup[]>;
1120
- /** `undefined` when a lookup under one of `skipFailedSigners` failed or timed out. */
1121
- private fetchBoardingCoins;
1122
- /**
1123
- * Fetch and cache boarding UTXOs at current and historical boarding addresses, each annotated
1124
- * with its own address's tapscript so spends use the right per-index leaves. Current-signer
1125
- * only: old-signer inputs would make a plain `settle()` the operator must reject, so their
1126
- * recovery goes through the deprecated-signer migration API.
1127
- */
1128
- getBoardingUtxos(): Promise<ExtendedCoin[]>;
1129
- /**
1130
- * @internal {@link getBoardingUtxos} minus those an in-flight settle is spending or an
1131
- * unresolved intent locks, for SDK picks. The getter itself lists them: callers that mirror it
1132
- * (the worker's cache and broadcasts, balances) must not see a settle's inputs vanish, and then
1133
- * stay gone if it fails.
1134
- */
1135
- getSelectableBoardingUtxos(): Promise<ExtendedCoin[]>;
1136
- /**
1137
- * @internal {@link getSelectableBoardingUtxos} for every boarding address history shows,
1138
- * current and deprecated signers, grouped by signer. Only the boarding sweep reads it: a
1139
- * unilateral exit needs no operator, so it recovers coins that `settle` must not take.
1140
- */
1141
- getSelectableBoardingUtxoGroups(): Promise<BoardingUtxoGroup[]>;
1142
- /** Boarding coins from the store, no network call; pending and confirmed spends excluded. */
1143
- getStoredBoardingUtxos(): Promise<ExtendedCoin[]>;
1144
- /**
1145
- * Subscribe to onchain and offchain notifications for newly received funds.
1146
- *
1147
- * The onchain watcher tracks every boarding address (current + historical) and re-subscribes
1148
- * automatically when boarding rotates after subscribing, so deposits to a fresh address fire
1149
- * within the same session.
1150
- *
1151
- * @param eventCallback - Callback invoked when matching funds are detected
1152
- * @returns A function that stops the subscriptions
1153
- */
1154
- notifyIncomingFunds(eventCallback: (coins: IncomingFunds) => void): Promise<() => void>;
1155
- /** Fetch Arkade transaction ids that are still pending final settlement. */
1156
- fetchPendingTxs(): Promise<string[]>;
1157
- /**
1158
- * Get all pkScript hex strings for the wallet's own addresses
1159
- * (both delegate and non-delegate, current and historical).
1160
- */
1161
- getWalletScripts(): Promise<string[]>;
1162
- /**
1163
- * Build a map of scriptHex → VtxoScript for all wallet contracts,
1164
- * so virtual outputs can be extended with the correct tapscript per contract.
1165
- */
1166
- getScriptMap(): Promise<Map<string, DefaultVtxo.Script | DelegateVtxo.Script>>;
1167
- /**
1168
- * Get the ContractManager, which manages the wallet's own receive contracts and external ones
1169
- * (Boltz swaps, HTLCs, …) with resilient multi-contract watching.
1170
- *
1171
- * @example
1172
- * ```typescript
1173
- * const manager = await wallet.getContractManager();
1174
- *
1175
- * // Create a contract for a Boltz swap
1176
- * const contract = await manager.createContract({
1177
- * label: "Boltz Swap",
1178
- * type: "vhtlc",
1179
- * params: { ... },
1180
- * script: swapScript,
1181
- * address: swapAddress,
1182
- * });
1183
- *
1184
- * // Start watching for events (includes wallet's default address)
1185
- * const stop = await manager.onContractEvent((event) => {
1186
- * console.log(`${event.type} on ${event.contractScript}`);
1187
- * });
1188
- * ```
1189
- */
1190
- getContractManager(): Promise<ContractManager>;
1191
- /**
1192
- * HD look-ahead configuration for the contract manager. Readonly wallets
1193
- * have no descriptor provider, hence no watermark to look ahead of.
1194
- * @see Wallet.lookAheadConfig
1195
- */
1196
- protected lookAheadConfig(): ContractManagerConfig["lookAhead"];
1197
- /** Readonly wallets never settle, so they neither release nor own batch registrations. */
1198
- protected intentReconciliationConfig(): ContractManagerConfig["intentReconciliation"];
1199
- private initializeContractManager;
1200
- /** Dispose wallet-owned managers and release background resources. */
1201
- dispose(): Promise<void>;
1202
- /** Async-dispose hook that forwards to `dispose()`. */
1203
- [Symbol.asyncDispose](): Promise<void>;
1204
- }
1205
- /**
1206
- * Main wallet implementation for Bitcoin transactions with Arkade protocol support.
1207
- *
1208
- * @example
1209
- * ```typescript
1210
- * // Create a wallet with providers
1211
- * const wallet = await Wallet.create({
1212
- * identity: MnemonicIdentity.fromMnemonic('abandon abandon...'),
1213
- * operatorProvider: new RestOperatorProvider(),
1214
- * onchainProvider: new EsploraProvider()
1215
- * });
1216
- *
1217
- * // Use custom providers and/or URLs (e.g., for Expo/React Native)
1218
- * const wallet = await Wallet.create({
1219
- * identity: MnemonicIdentity.fromMnemonic('abandon abandon...'),
1220
- * operatorProvider: new ExpoOperatorProvider('https://arkade.computer'),
1221
- * indexerProvider: new ExpoIndexerProvider('https://arkade.computer'),
1222
- * onchainProvider: new EsploraProvider('https://mempool.space/api')
1223
- * });
1224
- *
1225
- * // Get addresses
1226
- * const arkAddress = await wallet.getAddress();
1227
- * const boardingAddress = await wallet.getBoardingAddress();
1228
- *
1229
- * // Send bitcoin
1230
- * const txid = await wallet.send({
1231
- * address: 'ark1q...',
1232
- * amount: 50000,
1233
- * });
1234
- * ```
1235
- */
1236
- declare class Wallet extends ReadonlyWallet implements IWallet, HDWalletCapable, AddressAllocationCapable {
1237
- readonly forfeitOutputScript: Bytes;
1238
- readonly forfeitPubkey: Bytes;
1239
- /** Overrides for the `batchExpiry` bounds; defaults derive from `network`. */
1240
- protected readonly batchExpiryPolicy?: Partial<BatchExpiryPolicy> | undefined;
1241
- /** @see WalletConfig.oneShotSubmit */
1242
- readonly oneShotSubmit: boolean;
1243
- static MIN_FEE_RATE: number;
1244
- readonly identity: Identity;
1245
- private readonly _delegateManager?;
1246
- private _vtxoManager?;
1247
- private _vtxoManagerInitializing?;
1248
- private _walletAssetManager?;
1249
- /**
1250
- * HD receive rotator; absent for `static` and SingleKey-under-`auto` wallets. Its subscription
1251
- * installs lazily on first `getVtxoManager()` so the contract manager is up first.
1252
- */
1253
- private _receiveRotator?;
1254
- /** Unsubscribe for `onServerInfoChanged` (mid-session signer rotation). */
1255
- private _serverInfoUnsub?;
1256
- /**
1257
- * Tail of the serialized {@link handleServerInfoChanged} chain; {@link dispose} awaits it so an
1258
- * in-flight rotation settles before the contract manager is torn down.
1259
- */
1260
- private _serverInfoInFlight;
1261
- /**
1262
- * React to a mid-session operator info change (`DIGEST_MISMATCH`): refresh deprecated signers
1263
- * first so boarding watch widens immediately, then rotate via {@link rotateServerSigner} only
1264
- * if the active signer changed. Old-signer rows stay active. Never throws into the emit loop.
1265
- */
1266
- private handleServerInfoChanged;
1267
- /**
1268
- * Await an `onServerInfoChanged` handler still applying a rotation. {@link rotateServerSigner}
1269
- * persists the new signer's rows *before* committing the tapscripts, so a path that refreshes
1270
- * operator info then reads signer-derived state must drain first or it reads torn state and
1271
- * races the handler. Resolves once idle; handler rejections are swallowed (already logged).
1272
- *
1273
- * @internal Invoked by {@link dispose} and the {@link VtxoManager} migration
1274
- * pass; not part of the stable public API.
1275
- */
1276
- settleServerInfoChanges(): Promise<void>;
1277
- private _receiveRotatorInstalled;
1278
- /**
1279
- * Descriptor-aware signer for inputs locked by rotated pubkeys (the rotator's instance).
1280
- * Undefined for static / non-HD wallets, which only sign with the identity.
1281
- */
1282
- private readonly _descriptorProvider?;
1283
- /**
1284
- * Keyring holding foreign private keys imported outside the wallet's
1285
- * derivation tree (see {@link KeyringDescriptorProvider}). Wraps
1286
- * {@link _descriptorProvider} (or a {@link StaticDescriptorProvider}
1287
- * over the wallet identity when there is no HD provider) and is the
1288
- * descriptor provider {@link _signerRouter} actually signs through, so
1289
- * a contract carrying `metadata.signingDescriptor` for an imported key
1290
- * is signable by construction.
1291
- *
1292
- * Kept separate from {@link _descriptorProvider} on purpose: the latter
1293
- * still gates HD boarding/receive rotation (a `!provider` check means
1294
- * "static wallet, no rotation"), and wrapping it with a keyring for
1295
- * every wallet would break that gate. The keyring is orthogonal — it
1296
- * only ever adds foreign signable keys, never receive addresses.
1297
- *
1298
- * Populated for every {@link Wallet.create}d wallet; the constructor's
1299
- * param is optional so the router degrades to {@link _descriptorProvider}
1300
- * if a caller ever omits it.
1301
- */
1302
- private readonly _keyring?;
1303
- /**
1304
- * The built-in HD provider behind any keyring wrapping, or `undefined` when there is none.
1305
- * Every HD-specific branch goes through this: a wrapped HD provider (a public `walletMode`
1306
- * shape) fails `instanceof HDDescriptorProvider` and would silently take the non-HD path.
1307
- */
1308
- private get _hdProvider();
1309
- /** Per-side width of the HD look-ahead band. @see WalletConfig.lookAheadWindow */
1310
- private readonly _lookAheadWindow;
1311
- protected intentReconciliationConfig(): ContractManagerConfig["intentReconciliation"];
1312
- /**
1313
- * Watch a band of receive scripts around the HD watermark so payments to an externally-issued
1314
- * address land without a `restore()`. HD only. `candidateDeps` is read at refill time, so a
1315
- * band rebuilt after {@link rotateServerSigner} fans the new signer set.
1316
- */
1317
- protected lookAheadConfig(): ContractManagerConfig["lookAhead"];
1318
- /**
1319
- * Every axis an externally issued receive script could use: an issuer sharing the seed (NArk,
1320
- * a merchant backend) picks its own contract type. From cached state (no `getInfo`) to stay
1321
- * synchronous and offline-safe.
1322
- */
1323
- private receiveCandidateDeps;
1324
- private readonly _signerRouter;
1325
- private _emulator?;
1326
- private _cosignMarginBlocks;
1327
- /**
1328
- * @internal Sole write path for `offchainTapscript`; called by
1329
- * {@link WalletReceiveRotator.rotate} after the rotated contract is persisted.
1330
- */
1331
- setOffchainTapscriptForRotation(tapscript: DefaultVtxo.Script | DelegateVtxo.Script): void;
1332
- /**
1333
- * @internal Sole write path for `boardingTapscript`; called by
1334
- * {@link Wallet.getNewBoardingAddress} after the rotated contract is persisted.
1335
- */
1336
- setBoardingTapscriptForRotation(tapscript: DefaultVtxo.Script): void;
1337
- /**
1338
- * @internal Sole write path for `arkServerPublicKey`; called by
1339
- * {@link Wallet.rotateServerSigner} after the rotated rows are persisted.
1340
- */
1341
- setArkServerPublicKeyForRotation(serverPubKey: Bytes): void;
1342
- /**
1343
- * Checkpoint output script from the operator's `checkpointTapscript`; pinned at construction,
1344
- * re-sourced only via {@link setServerUnrollScriptForRotation}.
1345
- */
1346
- protected _serverUnrollScript: CSVMultisigTapscript.Type;
1347
- get serverUnrollScript(): CSVMultisigTapscript.Type;
1348
- /**
1349
- * @internal Sole write path for `serverUnrollScript`; called by
1350
- * {@link Wallet._doRotateServerSigner} with the rotating `OperatorInfo`'s checkpoint script.
1351
- */
1352
- setServerUnrollScriptForRotation(script: CSVMultisigTapscript.Type): void;
1353
- /**
1354
- * Serializes {@link rotateServerSigner} for static / non-HD wallets so two callers can't both
1355
- * swap the tapscripts; HD wallets use {@link WalletReceiveRotator.runExclusive} instead.
1356
- */
1357
- private _serverRotationChain;
1358
- /**
1359
- * Allocate a *fresh* on-chain boarding address at the next index of the shared HD stream and
1360
- * make it the displayed one (NArk: `GetNextContract(NextContractPurpose.Boarding)`).
1361
- * Persists an `active` `boarding` contract tagged {@link WALLET_RECEIVE_SOURCE} so it is
1362
- * watched, restored at boot and signable per index.
1363
- *
1364
- * A static / `auto` wallet returns {@link getBoardingAddress} unchanged (no index burned). A
1365
- * custom {@link DescriptorProvider} wallet burns an index per call, including via
1366
- * {@link maybeRotateBoardingAfterBoard} on every settle consuming a boarding UTXO; retired
1367
- * addresses stay reachable through {@link getBoardingUtxos}.
1368
- *
1369
- * @deprecated Use {@link getNewAddresses} — it mints any combination of
1370
- * address types at one shared index, and reports the contract row behind
1371
- * each. Note the difference in display behaviour: this method *swaps* the
1372
- * advertised boarding address, where `getNewAddresses` mints side
1373
- * addresses and leaves {@link getBoardingAddress} alone. To keep this
1374
- * method's behaviour, keep calling this method.
1375
- */
1376
- getNewBoardingAddress(): Promise<string>;
1377
- /**
1378
- * Allocate a *fresh* address of each requested type, all at **one** new HD index. The way to
1379
- * issue a second address before the first is paid ({@link getAddress} only advances on
1380
- * receipt). Each is persisted `active` with its `signingDescriptor`, so it is watched,
1381
- * counted, and signable via {@link signerForDescriptor}; the look-ahead band slides.
1382
- *
1383
- * Rows are deliberately **untagged**: boot adopts the newest {@link WALLET_RECEIVE_SOURCE} row
1384
- * as the display address, and a side address must not become what the wallet advertises.
1385
- * {@link getAddress} and {@link getBoardingAddress} are unchanged.
1386
- *
1387
- * A wallet with no HD stream (`static` / `auto`) returns its persisted display rows, or with
1388
- * `forceNew` throws {@link WalletCannotAllocateAddressError} rather than return a stale one.
1389
- *
1390
- * @example
1391
- * ```typescript
1392
- * const [invoice] = await wallet.getNewAddresses({ forceNew: true });
1393
- * // hand `invoice.address` to Alice, keep the descriptor with the invoice
1394
- * const signer = await wallet.signerForDescriptor(invoice.signingDescriptor);
1395
- * ```
1396
- */
1397
- getNewAddresses(opts?: GetNewAddressesOptions): Promise<NewAddress[]>;
1398
- /**
1399
- * Shared core of {@link getNewAddresses} and {@link getNewBoardingAddress}.
1400
- *
1401
- * @param tagSource - Tag rows {@link WALLET_RECEIVE_SOURCE} so boot adopts them as the display
1402
- * address; only the deprecated boarding allocator passes `true`.
1403
- */
1404
- private allocateAddresses;
1405
- /**
1406
- * The wallet's existing display addresses as persisted rows, each minted from the descriptor
1407
- * that owns its display script ({@link displayDescriptor}) so it signs for `address`.
1408
- */
1409
- private currentAddresses;
1410
- /**
1411
- * The descriptor owning the current display script for `type`, from its persisted row. Not
1412
- * derived from the identity: on a rotated wallet that would pair the address with a signer
1413
- * holding the wrong key. Falls back to the identity's `tr(pubkey)` when no row carries one
1414
- * (static / `auto`; index-0 baselines have no `signingDescriptor`).
1415
- */
1416
- private displayDescriptor;
1417
- /**
1418
- * Build, persist and shape one address of `type` owned by `descriptor`. The descriptor is the
1419
- * sole source of the owner key in both branches, so `address` and `signingDescriptor` can't
1420
- * drift apart.
1421
- */
1422
- private mintAddress;
1423
- /**
1424
- * Boarding contract owned by `pubKey`, keeping the current tapscript's other options
1425
- * (offchain analogue: {@link buildReceiveContract}).
1426
- */
1427
- private buildBoardingContract;
1428
- /**
1429
- * @see HDWalletCapable.getCurrentSigningDescriptor
1430
- */
1431
- getCurrentSigningDescriptor(): Promise<string | undefined>;
1432
- /**
1433
- * @see HDAllocationCapable.getNextSigningDescriptor
1434
- *
1435
- * Every `Wallet` answers, so consumers never branch on wallet shape: HD allocates through the
1436
- * contract manager; otherwise the identity key as `tr(pubkey)`, the same every call.
1437
- */
1438
- getNextSigningDescriptor(): Promise<string | undefined>;
1439
- /**
1440
- * @see HDAllocationCapable.advanceSigningDescriptorWatermark
1441
- */
1442
- advanceSigningDescriptorWatermark(descriptor: string): Promise<void>;
1443
- /**
1444
- * @see HDWalletCapable.getUsedSigningDescriptors
1445
- *
1446
- * Union of the watermark band (covers indices allocated for unpersisted things, e.g. swaps)
1447
- * and descriptors persisted on contracts (covers rows a restore scan wrote).
1448
- */
1449
- getUsedSigningDescriptors(opts?: {
1450
- lookAhead?: number;
1451
- }): Promise<string[]>;
1452
- /**
1453
- * @see HDWalletCapable.signerForDescriptor
1454
- *
1455
- * Fail-loud: a descriptor this wallet can't sign for throws {@link ForeignDescriptorError}
1456
- * rather than substituting the baseline identity, which would sign with the wrong key.
1457
- */
1458
- signerForDescriptor(descriptor: string): Promise<Identity>;
1459
- /**
1460
- * Mid-session operator signer rotation. A wallet built before the rotation keeps deriving
1461
- * old-signer receive addresses, and a migration output to one yields an output the operator must
1462
- * reject, so receive state is re-derived under the new signer first.
1463
- *
1464
- * Same write-path as {@link WalletReceiveRotator.rotate} with the operator key swapped: build the
1465
- * new tapscripts, register their rows (carrying signing metadata so a descriptor-backed
1466
- * pubkey still signs), and only then commit visible state. Old-signer rows stay `active` for
1467
- * the migration pass to drain. Idempotent; serialized against HD receive rotation.
1468
- *
1469
- * @internal Invoked by the {@link VtxoManager} migration pass; not part of
1470
- * the stable public API.
1471
- */
1472
- rotateServerSigner(newServerPubKey: Bytes, checkpointTapscript: string): Promise<void>;
1473
- private _doRotateServerSigner;
1474
- /**
1475
- * Serializes `settle`/`send` so VtxoManager's background renewal can't race user
1476
- * transactions for the same inputs; with `concurrentSpending`, only until inputs are reserved.
1477
- */
1478
- private _txLock;
1479
- private readonly _settlingOutpoints;
1480
- /** Coalesces concurrent {@link restore} calls into one scan; cleared on settle. */
1481
- private _restoreInFlight?;
1482
- private _addPendingSpends;
1483
- private _removePendingSpends;
1484
- /**
1485
- * Hold VTXOs so no SDK-chosen spend picks them; the holder still spends them by naming them.
1486
- * All-or-nothing: throws {@link VtxoReservedError} if any is held or already being spent.
1487
- * In-memory, for this `Wallet` instance only.
1488
- */
1489
- reserveVtxos(outpoints: readonly Outpoint[]): VtxoReservation;
1490
- /**
1491
- * @internal For `AssetManager`: reserves what `fn` submits, hiding it from other picks until
1492
- * the submit ends. With `concurrentSpending`, `fn` runs under the wallet lock, released once
1493
- * the inputs are reserved; otherwise `fn` runs unlocked and only the submit takes the lock.
1494
- */
1495
- withSpendLock<T>(fn: (submit: OffchainSubmit) => Promise<T>): Promise<T>;
1496
- private _withTxLock;
1497
- private _assertNotInFlight;
1498
- private _assertNotHeld;
1499
- /**
1500
- * Explicitly recover this wallet's contracts and balance on a fresh repo: a gap-limit scan
1501
- * for HD wallets, the single default pubkey otherwise. Throws on operational failure (a
1502
- * truncated restore is loud), never because of identity/mode. Idempotent.
1503
- *
1504
- * Ordering: scan → advance the HD watermark → inline VTXO pull → only THEN surface handler
1505
- * errors, so safely-discovered funds are recovered even when one handler failed.
1506
- *
1507
- * @param opts.gapLimit - Consecutive-unused-index window. Default 20. A non-positive /
1508
- * non-integer value throws synchronously.
1509
- *
1510
- * @note Concurrent calls coalesce onto the running scan; their `gapLimit` is ignored.
1511
- */
1512
- restore(opts?: {
1513
- gapLimit?: number;
1514
- }): Promise<void>;
1515
- private _runRestore;
1516
- readonly settlementConfig: SettlementConfig | false;
1517
- private _concurrentSpending;
1518
- private _submitsAwaitingFinalize;
1519
- /** @see WalletConfig.concurrentSpending */
1520
- get concurrentSpending(): boolean;
1521
- /** Public here; `ReadonlyWallet` keeps it protected so a readonly view can't submit. */
1522
- readonly arkProvider: OperatorProvider;
1523
- /**
1524
- * Broadcast access bound to this wallet's operator, so a plugin needs only the wallet. Not on
1525
- * {@link ReadonlyWallet}: a readonly wallet or `toReadonly()` view must not be able to submit.
1526
- */
1527
- getArkadeBroadcaster(): Promise<ArkadeBroadcaster>;
1528
- protected constructor(identity: Identity, network: Network, onchainProvider: OnchainProvider, arkProvider: OperatorProvider, indexerProvider: IndexerProvider, arkServerPublicKey: Bytes, offchainTapscript: DefaultVtxo.Script | DelegateVtxo.Script, boardingTapscript: DefaultVtxo.Script, serverUnrollScript: CSVMultisigTapscript.Type, forfeitOutputScript: Bytes, forfeitPubkey: Bytes, dustAmount: bigint, walletRepository: WalletRepository, contractRepository: ContractRepository, delegateProvider?: DelegateProvider, watcherConfig?: WalletConfig["watcherConfig"], settlementConfig?: WalletConfig["settlementConfig"], walletContractTimelocks?: RelativeTimelock[], receiveRotator?: WalletReceiveRotator, descriptorProvider?: DescriptorProvider, keyring?: KeyringDescriptorProvider, lookAheadWindow?: number,
1529
- /** Overrides for the `batchExpiry` bounds; defaults derive from `network`. */
1530
- batchExpiryPolicy?: Partial<BatchExpiryPolicy> | undefined,
1531
- /** @see WalletConfig.oneShotSubmit */
1532
- oneShotSubmit?: boolean);
1533
- get assetManager(): IAssetManager;
1534
- getVtxoManager(): Promise<VtxoManager>;
1535
- dispose(): Promise<void>;
1536
- /**
1537
- * Create a full wallet and initialize its background managers.
1538
- *
1539
- * @param config - Wallet configuration
1540
- * @returns A wallet ready to query balances and send transactions
1541
- * @example
1542
- * ```typescript
1543
- * const wallet = await Wallet.create({
1544
- * identity,
1545
- * operatorProvider: new RestOperatorProvider(),
1546
- * });
1547
- * ```
1548
- */
1549
- static create<T extends Wallet>(this: {
1550
- prototype: T;
1551
- }, config: WalletConfig): Promise<T>;
1552
- static create(config: WalletConfig): Promise<Wallet>;
1553
- /**
1554
- * Convert this wallet to a readonly wallet.
1555
- *
1556
- * @returns A readonly wallet with the same configuration but readonly identity
1557
- * @example
1558
- * ```typescript
1559
- * const wallet = await Wallet.create({ identity: MnemonicIdentity.fromMnemonic('abandon abandon...'), ... });
1560
- * const readonlyWallet = await wallet.toReadonly();
1561
- *
1562
- * // Can query balance and addresses
1563
- * const balance = await readonlyWallet.getBalance();
1564
- * const address = await readonlyWallet.getAddress();
1565
- *
1566
- * // But cannot send transactions (type error)
1567
- * // readonlyWallet.send(...); // TypeScript error
1568
- * ```
1569
- */
1570
- toReadonly(): Promise<ReadonlyWallet>;
1571
- /** Returns the delegate manager when delegation support is configured. */
1572
- getDelegateManager(): Promise<IDelegateManager | undefined>;
1573
- /**
1574
- * Settle boarding inputs and/or virtual outputs into a finalized mainnet transaction.
1575
- *
1576
- * `params.inputs` is **ungated** (how an escrowed deposit is recovered by hand), so
1577
- * `settle({ inputs: await wallet.getVtxos() })` bypasses the gate; pass
1578
- * {@link getSpendableVtxos} to settle "whatever is spendable".
1579
- *
1580
- * @param params - Optional settlement inputs and outputs. When omitted, the wallet settles all eligible funds.
1581
- * @param eventCallback - Optional callback invoked for settlement stream events.
1582
- * @param hooks - Optional phases for preparation and intent registration.
1583
- * @returns The finalized Arkade transaction id
1584
- */
1585
- settle(params?: SettleParams, eventCallback?: (event: SettlementEvent) => void, hooks?: {
1586
- onPhase?: (phase: "preparing" | "registration_attempt") => void;
1587
- }): Promise<string>;
1588
- private _settleImpl;
1589
- /**
1590
- * Rotate-on-board: the boarding analogue of {@link WalletReceiveRotator}'s L2 rotation.
1591
- * Boarding has no on-chain receive event (the watcher sees only the L2 indexer), so a settle
1592
- * consuming a boarding UTXO (a non-VTXO, non-arknote input) is the trigger. No-op without a
1593
- * descriptor provider. Best-effort: the settle has committed, so failures are only logged.
1594
- */
1595
- private maybeRotateBoardingAfterBoard;
1596
- private handleSettlementFinalizationEvent;
1597
- private unsignableBoardingInputError;
1598
- /**
1599
- * Create a batch event handler for settlement flows.
1600
- *
1601
- * @param intentId - The intent ID.
1602
- * @param inputs - Inputs used by the intent.
1603
- * @param expectedRecipients - Expected recipients to validate in the virtual output tree.
1604
- * @param session - Optional musig2 signing session. When omitted, signing steps are skipped.
1605
- */
1606
- createBatchHandler(intentId: string, inputs: ExtendedCoin[], expectedRecipients: Recipient[], session?: SignerSession): Batch.Handler;
1607
- /**
1608
- * Signing jobs keyed by each input's own `witnessUtxo.script`; inputs without one
1609
- * (cosigner/connector) are silently omitted.
1610
- */
1611
- private inputSigningJobsFromWitnessUtxos;
1612
- /**
1613
- * Best-effort upsert into {@link intentRepository}; never throws into the settle path.
1614
- * Preserves fields the event reducer already wrote.
1615
- */
1616
- private persistIntentSnapshot;
1617
- signInputsByWitnessScript(tx: Transaction): Promise<Transaction>;
1618
- signOnchainBoardingTx(tx: Transaction): Promise<Transaction>;
1619
- /** @see IWallet.cosignOnchainTx */
1620
- cosignOnchainTx(psbt: string | Transaction): Promise<string>;
1621
- /** @see IWallet.sendOnchain */
1622
- sendOnchain(params: SendOnchainParams): Promise<string>;
1623
- private _buildOnchainSpend;
1624
- private _cosignOnchainTxImpl;
1625
- /** Boarding outpoints the automatic cosign sweep should renew now (never unrolled exits); excludes coins an intent has locked. */
1626
- getOnchainSweepInputs(): Promise<Outpoint[]>;
1627
- /** Unspent onchain coins from the store; the onchain rows are kept fresh by syncOnchain, not the indexer. */
1628
- private onchainCoins;
1629
- safeRegisterIntent(intent: SignedIntent<Intent.RegisterMessage>, inputs: ExtendedCoin[]): Promise<string>;
1630
- makeRegisterIntentSignature(coins: ExtendedCoin[], outputs: TransactionOutput[], onchainOutputsIndexes: number[], cosignerPubKeys: string[], validAt?: number): Promise<SignedProof<Proof.RegisterMessage>>;
1631
- makeDeleteIntentSignature(coins: ExtendedCoin[]): Promise<SignedProof<Proof.DeleteMessage>>;
1632
- makeGetPendingTxIntentSignature(coins: ExtendedVirtualCoin[]): Promise<SignedProof<Proof.GetPendingTxMessage>>;
1633
- /**
1634
- * Finalizes pending transactions by retrieving them from the operator and finalizing each one.
1635
- * Skips the operator check entirely when no send was interrupted (no pending tx flag set).
1636
- * @param vtxos - Optional list of virtual outputs to use instead of retrieving them from the operator
1637
- * @returns Array of transaction IDs that were finalized
1638
- */
1639
- finalizePendingTxs(vtxos?: ExtendedVirtualCoin[]): Promise<{
1640
- finalized: string[];
1641
- pending: string[];
1642
- }>;
1643
- /**
1644
- * Operator unroll scripts a pending checkpoint may have been built under: configured, current,
1645
- * and one per deprecated signer — else a pre-rotation tx would stay pending forever.
1646
- */
1647
- private checkpointUnrollCandidates;
1648
- private hasPendingTxFlag;
1649
- private setPendingTxFlag;
1650
- /**
1651
- * Create an ArkadeCash bearer instrument: sends `amount` to a DefaultVtxo controlled by a fresh
1652
- * key and returns the encoded token, claimable via `claimCash()` without sharing an address.
1653
- *
1654
- * Short-lived: it carries a private key, so hand it over and claim it promptly. Unclaimed past
1655
- * its batch expiry it is swept, and `claimCash` can only report it.
1656
- *
1657
- * @param amount - Whole sats at or above dust (below dust mints an unspendable OP_RETURN).
1658
- * @returns The encoded arkadeCash string (e.g., "arkadecash1...")
1659
- */
1660
- createCash(amount: number): Promise<string>;
1661
- /**
1662
- * Claim an ArkadeCash bearer instrument: sweep what can be swept, recover what
1663
- * was swept by the operator, report the rest.
1664
- *
1665
- * Every spendable VTXO at the arkadeCash address is swept to this wallet in
1666
- * its own offchain transaction, signed with the key carried by the arkadeCash
1667
- * string. An output the operator already swept at batch expiry cannot move
1668
- * through the thin sweep — only a settlement can lift it — so it is
1669
- * **imported** as a signable `default` contract (the arkadeCash key is filed
1670
- * in the keyring) and handed to the wallet's own recovery machinery, which
1671
- * settles it back on the normal retry cadence. That import is the only
1672
- * thing `claimCash` persists, and the key is purged once recovery
1673
- * completes. Anything neither sweepable nor recoverable — subdust, already
1674
- * claimed, or asset-bearing — is returned in `unclaimed` with a per-VTXO
1675
- * reason and otherwise ignored.
1676
- *
1677
- * The arkadeCash string is the recovery token: a claim interrupted between
1678
- * submit and finalize is completed by simply re-running `claimCash`, which
1679
- * drains any pending arkadeCash transaction at the operator before sweeping.
1680
- * The import is idempotent, so re-running is always safe.
1681
- *
1682
- * @param cashStr - The encoded arkadeCash string (e.g., "arkadecash1...")
1683
- * @returns What was swept instantly, what was imported for recovery, and
1684
- * what was left behind. The shape is open: further buckets may be added.
1685
- */
1686
- claimCash(cashStr: string): Promise<ArkadeCashClaimResult>;
1687
- /**
1688
- * Import an arkadeCash instrument as a signable, recovery-only contract so the
1689
- * wallet's own recovery machinery can settle its operator-swept outputs back.
1690
- *
1691
- * Two writes, both idempotent so a re-run (or a resumed claim) is safe:
1692
- * - the arkadeCash private key is filed in the keyring, returning its
1693
- * `tr(<pubkey>)` descriptor;
1694
- * - a `default` contract for the arkadeCash script is registered carrying that
1695
- * descriptor as `metadata.signingDescriptor` (so the signer router can
1696
- * sign the swept inputs) and `metadata.recoveryOnly` (so the contract is
1697
- * settled in its own isolated intent, never bundled into the wallet's own
1698
- * renewal/recovery — a persistently rejected input then dents only its
1699
- * own recovery, never the wallet's funds).
1700
- *
1701
- * A row may already exist at the script WITHOUT the recovery flags — the
1702
- * public `createContract` surface lets a consumer register the cash
1703
- * address (e.g. to watch a note it issued) — and `createContract`'s
1704
- * same-type idempotency keeps such a row as-is. It is then promoted:
1705
- * presenting the bearer key IS the authorization to claim, and left
1706
- * unflagged the row would feed unsignable swept VTXOs into the wallet's
1707
- * own settles while being invisible to both the isolated recovery pass
1708
- * and `removeRecoveryContract`'s purge.
1709
- */
1710
- private importArkadeCashForRecovery;
1711
- /** Best-effort, non-blocking trigger of the isolated imported-recovery pass. */
1712
- private kickImportedRecovery;
1713
- /**
1714
- * Retire a contract imported for recovery once its funds have been settled
1715
- * back: purge the keyring key that backed it, then delete the contract row.
1716
- * Ends the key-at-rest window opened by {@link importArkadeCashForRecovery}.
1717
- *
1718
- * Scoped to recovery-only contracts as a safety guard — it will not touch a
1719
- * regular wallet contract — and idempotent: a second call (the contract
1720
- * already gone) is a no-op. Invoked by the isolated recovery pass in
1721
- * `VtxoManager` (see its `RecoveryContractCapableWallet` capability).
1722
- *
1723
- * The write order is load-bearing; do not swap it. The two repositories
1724
- * cannot be written atomically, so one of them leaks on a partial failure.
1725
- * Purging the key first leaves a contract row with a dangling descriptor:
1726
- * visible, harmless, and retried to completion by the next recovery pass
1727
- * (its VTXOs read back spent, so nothing is signed). The reverse leaves an
1728
- * unencrypted key that nothing references — the descriptor lived only in
1729
- * the row just deleted — so no retry can ever find it, breaking the
1730
- * purge-on-completion bound that justifies storing it in the clear.
1731
- */
1732
- removeRecoveryContract(script: string): Promise<void>;
1733
- /**
1734
- * Correlate an imported voucher's settlement with the voucher record. This
1735
- * is deliberately kept on wallet state rather than being inferred from the
1736
- * generic recovery row, which has no safe public correlation key. The
1737
- * imported contract carries no cash id, so its script is the join key:
1738
- * the script is the voucher id.
1739
- */
1740
- correlateArkadeCashRecovery(cashId: string, txid: string, amount: number, outcome?: string): Promise<void>;
1741
- /**
1742
- * Split the VTXOs at an arkadeCash address into three buckets: the ones the
1743
- * thin sweep can move (`spendable`), the operator-swept ones that must go
1744
- * through a recovery settlement (`recoverable`), and the ones that can
1745
- * only be reported (`unclaimed`).
1746
- */
1747
- private classifyCashVtxos;
1748
- /** Read every page of an unfiltered VTXO query for the given scripts. */
1749
- private fetchAllVtxos;
1750
- /**
1751
- * Complete sweeps a previous `claimCash` registered but never finalized: a thin
1752
- * {@link finalizePendingTxs} signed with the arkadeCash key. A drained tx pays whoever
1753
- * registered it, so finalizing is still right, but only value paid to `myPkScript` counts.
1754
- *
1755
- * @param vtxos - VTXOs at the cash contract's own pkScript, spent included; any other
1756
- * outpoint (subdust above all) would invalidate the proof.
1757
- * @returns Txs finalized, sats paid to this wallet, and the outpoints consumed to pay it.
1758
- */
1759
- private finalizePendingCashTxs;
1760
- /** Sum the outputs of an ark tx PSBT that pay the given scriptPubKey. */
1761
- private arkTxAmountPaidTo;
1762
- /**
1763
- * Send BTC and/or assets to one or more recipients, passed either as
1764
- * variadic `Recipient`s or as a single `SendParams` object — the latter
1765
- * also carries the virtual outputs to spend.
1766
- *
1767
- * @param args - Recipients, or a `SendParams` object
1768
- * @returns Promise resolving to the Arkade transaction ID
1769
- * @see SendParams
1770
- *
1771
- * @example
1772
- * ```typescript
1773
- * const txid = await wallet.send({
1774
- * address: 'ark1q...',
1775
- * amount: 1000, // (optional, default to dust) btc amount to send to the output
1776
- * assets: [{ assetId: 'abc123...', amount: 50n }] // (optional) list of assets to send
1777
- * });
1778
- *
1779
- * // choosing the inputs as well as the outputs
1780
- * const txid = await wallet.send({
1781
- * recipients: [{ address: 'ark1q...', amount: 1000 }],
1782
- * selectedVtxos: mine, // spent as given, nothing added
1783
- * });
1784
- * ```
1785
- */
1786
- send(...args: [SendParams] | [Recipient, ...Recipient[]]): Promise<string>;
1787
- private _sendImpl;
1788
- /**
1789
- * Shared submit/persist tail of `send` and {@link sendSelectedVtxosToSelf}; callers own coin
1790
- * selection, outputs and the synchronous epoch snapshot.
1791
- */
1792
- private _submitOffchainSpend;
1793
- /**
1794
- * @internal Migration primitive for {@link VtxoManager}: spend the wallet's own
1795
- * deprecated-signer VTXOs into one full-value output on the *active* signer, via the Ark send
1796
- * path (not `settle`) so arkd builds checkpoints against the active epoch. No boarding inputs.
1797
- * The caller must already be on the active signer and have sized the batch. Preserves all
1798
- * input assets; records no `TxSent` history.
1799
- */
1800
- sendSelectedVtxosToSelf(inputs: ExtendedVirtualCoin[], now?: TimeHeight): Promise<string>;
1801
- /**
1802
- * Build an offchain transaction from the given inputs and outputs,
1803
- * sign it, submit to the operator provider, and finalize.
1804
- *
1805
- * Signs whatever it is handed, ungated — see {@link settle} for the trade.
1806
- *
1807
- * @returns The Arkade transaction id and operator-signed checkpoint PSBTs (for bookkeeping)
1808
- */
1809
- buildAndSubmitOffchainTx(inputs: ExtendedVirtualCoin[], outputs: TransactionOutput[], serverUnrollScript?: CSVMultisigTapscript.Type, options?: {
1810
- validUntil?: number;
1811
- }): Promise<{
1812
- arkTxid: string;
1813
- signedCheckpointTxs: string[];
1814
- }>;
1815
- private _buildAndSubmitOffchainTx;
1816
- private updateDbAfterOffchainTx;
1817
- private updateDbAfterSettle;
1818
- }
1819
- /**
1820
- * Select virtual outputs to reach a target amount, prioritizing those closer to expiry
1821
- * @param coins List of virtual outputs to select from
1822
- * @param targetAmount Target amount to reach in satoshis
1823
- * @returns Selected virtual outputs and change amount
1824
- */
1825
- declare function selectVirtualCoins(coins: ExtendedVirtualCoin[], targetAmount: number): {
1826
- inputs: ExtendedVirtualCoin[];
1827
- changeAmount: bigint;
1828
- };
1829
- /**
1830
- * Raised when a wait is cancelled through its `AbortSignal` or `timeoutMs`. `name` is
1831
- * `"AbortError"`, so DOM and SDK aborts can be handled identically.
1832
- */
1833
- declare class AbortError extends Error {
1834
- constructor(message?: string);
1835
- }
1836
- /**
1837
- * A VTXO named for a spend or a hold is held, or already being spent by another operation.
1838
- * Match on `name`, not `instanceof`: only the name survives the service-worker boundary.
1839
- */
1840
- declare class VtxoReservedError extends Error {
1841
- readonly outpoints: readonly string[];
1842
- readonly holder: "in-flight" | "held";
1843
- readonly name = "VtxoReservedError";
1844
- constructor(outpoints: readonly string[], holder: "in-flight" | "held");
1845
- }
1846
- /** A hold placed by {@link Wallet.reserveVtxos}. */
1847
- interface VtxoReservation {
1848
- readonly outpoints: readonly Outpoint[];
1849
- /** Idempotent. */
1850
- release(): void;
1851
- }
1852
- /** @internal Submits an Arkade transaction for {@link Wallet.withSpendLock}'s caller. */
1853
- type OffchainSubmit = (inputs: ExtendedVirtualCoin[], outputs: TransactionOutput[]) => Promise<{
1854
- arkTxid: string;
1855
- signedCheckpointTxs: string[];
1856
- }>;
1857
- /** Options for {@link waitForIncomingFunds}. */
1858
- interface WaitForIncomingFundsOptions {
1859
- /**
1860
- * Cancels the wait. On abort the underlying subscription is stopped and
1861
- * the returned promise rejects — with the signal's `reason` when the
1862
- * caller supplied an `Error`, otherwise an {@link AbortError}.
1863
- */
1864
- signal?: AbortSignal;
1865
- /**
1866
- * Cancels the wait after this many milliseconds, rejecting with an
1867
- * {@link AbortError}. Equivalent to passing an `AbortSignal.timeout`
1868
- * signal, without requiring that API on the target platform.
1869
- */
1870
- timeoutMs?: number;
1871
- }
1872
- /**
1873
- * Wait for incoming funds to the wallet.
1874
- *
1875
- * Keeps live network watchers open until it settles. **Cancel it if you won't await it to
1876
- * completion** (`signal` / `timeoutMs`): a `Promise.race` against a timer abandons the loser
1877
- * without stopping its watchers, and in a loop stacks subscriptions until the process exits.
1878
- *
1879
- * @param wallet - The wallet to wait for incoming funds
1880
- * @param options - Cancellation options; see {@link WaitForIncomingFundsOptions}
1881
- * @returns A promise that resolves the next new coins received by the wallet's address
1882
- * @throws {AbortError} If cancelled via `signal` or `timeoutMs`
1883
- * @example
1884
- * ```typescript
1885
- * // Wake early on a deposit, but give up after 30s and release the watchers.
1886
- * try {
1887
- * const funds = await waitForIncomingFunds(wallet, { timeoutMs: 30_000 })
1888
- * } catch (e) {
1889
- * if ((e as Error).name !== "AbortError") throw e
1890
- * }
1891
- * ```
1892
- */
1893
- declare function waitForIncomingFunds(wallet: NotifiesIncomingFunds, options?: WaitForIncomingFundsOptions): Promise<IncomingFunds>;
1894
-
1895
- /**
1896
- * IndexedDB-based implementation of WalletRepository.
1897
- */
1898
- declare class IndexedDBWalletRepository implements WalletRepository {
1899
- readonly version: 2;
1900
- private readonly connection;
1901
- /** persistentWalletState asserts persistence beyond this process; it cannot detect browser eviction. */
1902
- constructor(dbName?: string, options?: {
1903
- persistentWalletState?: boolean;
1904
- });
1905
- clear(): Promise<void>;
1906
- [Symbol.asyncDispose](): Promise<void>;
1907
- getVtxosPage(address: string, page: PageRequest<Outpoint>): Promise<PageResult<ExtendedVirtualCoin, Outpoint>>;
1908
- saveVtxos(address: string, vtxos: ExtendedVirtualCoin[]): Promise<void>;
1909
- deleteVtxos(address: string): Promise<void>;
1910
- getVtxosForScriptPage(script: string, page: PageRequest<ScriptVtxoCursor>, options?: ScriptVtxoPageOptions): Promise<PageResult<StoredVtxo, ScriptVtxoCursor>>;
1911
- saveVtxosForScript(key: VtxoRepositoryKey, vtxos: ExtendedVirtualCoin[]): Promise<void>;
1912
- deleteVtxosForScript(script: string): Promise<void>;
1913
- getUtxosPage(address: string, page: PageRequest<Outpoint>): Promise<PageResult<ExtendedCoin, Outpoint>>;
1914
- private pageByAddress;
1915
- saveUtxos(addressOrBatch: string | ReadonlyMap<string, ExtendedCoin[]>, utxos?: ExtendedCoin[]): Promise<void>;
1916
- deleteUtxos(address: string): Promise<void>;
1917
- getTransactionHistoryPage(filter: TransactionHistoryPageFilter, page: PageRequest<TransactionHistoryPageCursor>): Promise<PageResult<ArkTransaction, TransactionHistoryPageCursor>>;
1918
- saveTransactions(address: string, txs: ArkTransaction[]): Promise<void>;
1919
- deleteTransactions(address: string): Promise<void>;
1920
- readonly atomicWalletState: AtomicWalletState;
1921
- getWalletState(): Promise<WalletState | null>;
1922
- saveWalletState(state: WalletState): Promise<void>;
1923
- private getDB;
1924
- }
1925
-
1926
- /**
1927
- * A {@link DescriptorProvider} decorator that adds a **keyring**: raw
1928
- * private keys imported from outside the wallet's derivation tree, each
1929
- * addressed by a `tr(<pubkey>)` descriptor.
1930
- *
1931
- * Resolution is union-shaped — `signWithDescriptor` /
1932
- * `signMessageWithDescriptor` serve a descriptor from the wrapped
1933
- * provider's derivation tree *or* from the keyring, whichever owns it —
1934
- * so the wallet's existing descriptor routing
1935
- * (`InputSignerRouter`) signs foreign-key contracts with no changes: an
1936
- * imported contract carrying `metadata.signingDescriptor` is signable by
1937
- * construction rather than throwing `MissingSigningDescriptorError`.
1938
- *
1939
- * Allocation is *not* extended: `getNextSigningDescriptor` always
1940
- * delegates to the wrapped provider. The keyring holds foreign keys the
1941
- * wallet was handed; it never mints receive addresses.
1942
- *
1943
- * Lifecycle: entries persist under
1944
- * `WalletRepository.getWalletState().settings.keyring` (same
1945
- * no-migration pattern as `HDDescriptorProvider`), so an import survives
1946
- * the restarts a recovery spans, and {@link deleteKey} purges it when
1947
- * recovery completes. The repository is the source of truth: the async
1948
- * signing/purge APIs converge on sibling instances' imports and purges
1949
- * (see {@link refresh}), so any tab/worker sharing the repo can complete
1950
- * a recovery another one started.
1951
- *
1952
- * **Keys are stored unencrypted.** This is a deliberate, scoped
1953
- * decision: the intended use is a short-lived, purge-on-completion hold
1954
- * of a key that guards funds already destined for this wallet. At-rest
1955
- * encryption is a possible hardening follow-up. Do not use this to hold
1956
- * long-lived key material.
1957
- *
1958
- * @example
1959
- * ```ts
1960
- * const provider = await KeyringDescriptorProvider.create(hdProvider, walletRepo);
1961
- * const descriptor = await provider.importKey(foreignPrivKey);
1962
- * // descriptor: tr(<x-only pubkey hex>)
1963
- * // ... import a contract with metadata.signingDescriptor = descriptor,
1964
- * // let the wallet's recovery machinery settle it, then:
1965
- * await provider.deleteKey(descriptor);
1966
- * ```
1967
- */
1968
- declare class KeyringDescriptorProvider implements DescriptorProvider {
1969
- /**
1970
- * The wrapped provider. Exposed so callers that need to reach a
1971
- * concrete provider type behind the decorator (e.g. the wallet's
1972
- * restore path, which branches on `HDDescriptorProvider`) can
1973
- * unwrap it rather than mis-classify the decorator.
1974
- */
1975
- readonly base: DescriptorProvider;
1976
- private readonly walletRepository;
1977
- /**
1978
- * In-memory mirror of the persisted keyring, keyed by x-only pubkey
1979
- * hex. Required because {@link isOurs} is synchronous while
1980
- * persistence is not. The **repository is the source of truth**: the
1981
- * async APIs write through to it and {@link refresh} re-seeds this
1982
- * mirror from it when a signing request names a foreign key the
1983
- * mirror doesn't know — a sibling instance (another tab/worker on
1984
- * the same repo) may have imported it after this instance was
1985
- * constructed. The sync views ({@link isOurs}, {@link hasKey},
1986
- * {@link listKeyringDescriptors}) answer from the last-known
1987
- * snapshot.
1988
- */
1989
- private readonly keys;
1990
- private constructor();
1991
- /**
1992
- * Wrap `base` with a keyring, loading any previously imported keys
1993
- * from the repository. Unlike `HDDescriptorProvider.create`, this
1994
- * *does* read at construction: `isOurs` is synchronous and must be
1995
- * able to answer for persisted keys from the first call.
1996
- */
1997
- static create(base: DescriptorProvider, walletRepository: WalletRepository): Promise<KeyringDescriptorProvider>;
1998
- /**
1999
- * Import a raw private key into the keyring and return its
2000
- * `tr(<x-only pubkey>)` descriptor handle. Idempotent: re-importing
2001
- * the same key returns the same descriptor and leaves storage
2002
- * unchanged.
2003
- */
2004
- importKey(privateKey: Uint8Array): Promise<string>;
2005
- /**
2006
- * Purge a keyring entry. Returns `true` when an entry was removed,
2007
- * `false` when the descriptor was not in the keyring (already
2008
- * purged, or never ours) — so a repeated purge is a safe no-op.
2009
- *
2010
- * Always goes through storage, never trusting the in-memory mirror:
2011
- * the entry may have been imported by a sibling instance after this
2012
- * one was constructed, and skipping the persistent purge on a memory
2013
- * miss would leave that key at rest forever.
2014
- */
2015
- deleteKey(descriptor: string): Promise<boolean>;
2016
- /** True iff `descriptor` resolves to a key held in the keyring. */
2017
- hasKey(descriptor: string): boolean;
2018
- /** The `tr(<pubkey>)` descriptors of every key currently held. */
2019
- listKeyringDescriptors(): string[];
2020
- /** Allocation is the wrapped provider's job; the keyring never mints. */
2021
- getNextSigningDescriptor(): Promise<string>;
2022
- /** Ours iff the wrapped provider claims it, or the keyring holds it. */
2023
- isOurs(descriptor: string): boolean;
2024
- /**
2025
- * Signs each request with the key its descriptor resolves to.
2026
- * Keyring-owned requests are signed here; every other request is
2027
- * handed to the wrapped provider in a single batched call, so a
2028
- * batch-signing identity behind a `StaticDescriptorProvider` still
2029
- * sees one interaction.
2030
- *
2031
- * Results are returned in request order regardless of how the
2032
- * requests split across the two signers.
2033
- */
2034
- signWithDescriptor(requests: DescriptorSigningRequest[]): Promise<Transaction[]>;
2035
- /** Signs a message with the keyring key, or delegates to the base. */
2036
- signMessageWithDescriptor(descriptor: string, message: Uint8Array, type?: "schnorr" | "ecdsa"): Promise<Uint8Array>;
2037
- /**
2038
- * Split requests into keyring-owned and base-delegated buckets.
2039
- * `mayBeStale` is set when a delegated descriptor is foreign-shaped —
2040
- * a sibling instance may have imported its key after this instance
2041
- * seeded the mirror, so the caller should {@link refresh} once and
2042
- * re-split before trusting the delegation.
2043
- */
2044
- private splitRequests;
2045
- /**
2046
- * True when `descriptor` is a bare `tr(<pubkey>)` the base provider
2047
- * does not own — the only shape a keyring entry can have, so the only
2048
- * kind of miss a {@link refresh} could turn into a hit.
2049
- */
2050
- private isForeignShaped;
2051
- /**
2052
- * Re-seed the in-memory mirror from the repository, converging on
2053
- * imports and purges made by sibling instances on the same repo.
2054
- * Full replacement, not a merge, so sibling *deletions* propagate
2055
- * too. Corrupt persisted settings throw, same as {@link create}.
2056
- *
2057
- * Only a *miss* triggers a refresh, so that convergence is one-sided:
2058
- * an entry this instance still believes it holds is never
2059
- * revalidated, and a sibling's purge can linger in this mirror until
2060
- * some unrelated foreign-shaped miss re-seeds it. Harmless today —
2061
- * `deleteKey`'s caller also deletes the contract row carrying the
2062
- * descriptor, so no signing request can name the stale entry — but it
2063
- * means the at-rest purge is not a memory purge for siblings.
2064
- */
2065
- private refresh;
2066
- /**
2067
- * The keyring key for `descriptor`, or `undefined` when the request
2068
- * belongs to the base provider. Base ownership wins on collision:
2069
- * a key already in the derivation tree keeps its established signing
2070
- * path, so importing it cannot reroute existing contracts.
2071
- */
2072
- private resolveKey;
2073
- /**
2074
- * Read-modify-write the keyring settings through `updateWalletState`,
2075
- * whose in-process mutex plus cross-context Web Lock keep concurrent
2076
- * imports/purges — including ones driven from other tabs/workers
2077
- * sharing the store — from clobbering each other's entries.
2078
- */
2079
- private mutate;
2080
- }
2081
-
2082
- export { maybeArkError as $, type AddressAllocationCapable as A, type BatchExpiryPolicy as B, VtxoReservedError as C, DEFAULT_MIN_BATCH_EXPIRY_SECONDS as D, type WaitForIncomingFundsOptions as E, ForeignDescriptorError as F, WalletCannotAllocateAddressError as G, type HDWalletCapable as H, type IncomingFunds as I, addArkadeCashRecord as J, KeyringDescriptorProvider as K, arkadeCashId as L, MAX_USED_SIGNING_DESCRIPTORS_LOOK_AHEAD as M, type NotifiesIncomingFunds as N, arkadeCashResolver as O, type ProviderConnectionState as P, assertValidBatchExpiry as Q, ReadonlyWallet as R, type ServerInfoSource as S, createArkadeCashTracker as T, defaultBatchExpiryPolicy as U, type VtxoReservation as V, Wallet as W, isAddressAllocationCapable as X, isArkError as Y, isHDAllocationCapable as Z, isHDWalletCapable as _, type HDAllocationCapable as a, mergeArkadeCashRecord as a0, resolveBatchExpiryPolicy as a1, resolveDescriptorSigner as a2, selectVirtualCoins as a3, signingDescriptorIndex as a4, strictSigningDescriptorIndex as a5, waitForIncomingFunds as a6, type ArkadeCashTx as b, type ArkadeCashRecord as c, type ArkadeCashClaimResult as d, type ReceiveRotatorFactory as e, type ReceiveRotatorBootOpts as f, type ReceiveRotatorBoot as g, Batch as h, AbortError as i, ArkError as j, ArkErrorName as k, ArkadeCash as l, type ArkadeCashAction as m, ArkadeCashCreateError as n, ArkadeCashOperatorMismatchError as o, type ArkadeCashUnclaimedReason as p, type ArkadeCashUnclaimedVtxo as q, type ArkadeCashVtxoRef as r, type BoardingUtxoGroup as s, IndexedDBWalletRepository as t, type ProviderKind as u, ProviderUnavailableError as v, REGTEST_MIN_BATCH_EXPIRY_SECONDS as w, ReadonlySingleKey as x, ServerResponseMismatchError as y, SingleKey as z };