@arkade-os/sdk 0.5.0-rc.9 → 0.5.0

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