@arkade-os/sdk 0.5.0-rc.11 → 0.5.0-rc.13

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