@arkade-os/sdk 0.3.0-alpha.7 → 0.3.1-alpha.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 (88) hide show
  1. package/README.md +115 -14
  2. package/dist/cjs/adapters/expo.js +8 -0
  3. package/dist/cjs/arknote/index.js +3 -3
  4. package/dist/cjs/forfeit.js +5 -2
  5. package/dist/cjs/identity/singleKey.js +5 -4
  6. package/dist/cjs/index.js +7 -3
  7. package/dist/cjs/{bip322 → intent}/index.js +37 -55
  8. package/dist/cjs/providers/ark.js +62 -23
  9. package/dist/cjs/providers/expoArk.js +82 -0
  10. package/dist/cjs/providers/expoIndexer.js +105 -0
  11. package/dist/cjs/providers/indexer.js +3 -1
  12. package/dist/cjs/providers/utils.js +122 -0
  13. package/dist/cjs/script/base.js +1 -2
  14. package/dist/cjs/script/tapscript.js +20 -21
  15. package/dist/cjs/script/vhtlc.js +2 -2
  16. package/dist/cjs/tree/signingSession.js +7 -8
  17. package/dist/cjs/tree/txTree.js +3 -4
  18. package/dist/cjs/tree/validation.js +2 -3
  19. package/dist/cjs/utils/arkTransaction.js +117 -12
  20. package/dist/cjs/utils/unknownFields.js +5 -5
  21. package/dist/cjs/wallet/index.js +1 -1
  22. package/dist/cjs/wallet/onchain.js +4 -5
  23. package/dist/cjs/wallet/serviceWorker/utils.js +2 -9
  24. package/dist/cjs/wallet/serviceWorker/wallet.js +4 -8
  25. package/dist/cjs/wallet/serviceWorker/worker.js +25 -23
  26. package/dist/cjs/wallet/unroll.js +6 -7
  27. package/dist/cjs/wallet/utils.js +11 -0
  28. package/dist/cjs/wallet/vtxo-manager.js +381 -0
  29. package/dist/cjs/wallet/wallet.js +130 -143
  30. package/dist/esm/adapters/expo.js +3 -0
  31. package/dist/esm/arknote/index.js +2 -2
  32. package/dist/esm/forfeit.js +4 -1
  33. package/dist/esm/identity/singleKey.js +7 -6
  34. package/dist/esm/index.js +7 -6
  35. package/dist/esm/{bip322 → intent}/index.js +31 -48
  36. package/dist/esm/providers/ark.js +62 -23
  37. package/dist/esm/providers/expoArk.js +78 -0
  38. package/dist/esm/providers/expoIndexer.js +101 -0
  39. package/dist/esm/providers/indexer.js +3 -1
  40. package/dist/esm/providers/utils.js +87 -0
  41. package/dist/esm/script/base.js +1 -2
  42. package/dist/esm/script/tapscript.js +1 -2
  43. package/dist/esm/script/vhtlc.js +1 -1
  44. package/dist/esm/tree/signingSession.js +8 -9
  45. package/dist/esm/tree/txTree.js +3 -4
  46. package/dist/esm/tree/validation.js +2 -3
  47. package/dist/esm/utils/arkTransaction.js +108 -5
  48. package/dist/esm/utils/unknownFields.js +1 -1
  49. package/dist/esm/wallet/index.js +1 -1
  50. package/dist/esm/wallet/onchain.js +1 -2
  51. package/dist/esm/wallet/serviceWorker/utils.js +1 -8
  52. package/dist/esm/wallet/serviceWorker/wallet.js +5 -9
  53. package/dist/esm/wallet/serviceWorker/worker.js +26 -24
  54. package/dist/esm/wallet/unroll.js +2 -3
  55. package/dist/esm/wallet/utils.js +8 -0
  56. package/dist/esm/wallet/vtxo-manager.js +372 -0
  57. package/dist/esm/wallet/wallet.js +124 -137
  58. package/dist/types/adapters/expo.d.ts +4 -0
  59. package/dist/types/arknote/index.d.ts +1 -1
  60. package/dist/types/forfeit.d.ts +2 -2
  61. package/dist/types/identity/index.d.ts +1 -1
  62. package/dist/types/identity/singleKey.d.ts +1 -1
  63. package/dist/types/index.d.ts +8 -7
  64. package/dist/types/intent/index.d.ts +41 -0
  65. package/dist/types/providers/ark.d.ts +190 -22
  66. package/dist/types/providers/expoArk.d.ts +22 -0
  67. package/dist/types/providers/expoIndexer.d.ts +18 -0
  68. package/dist/types/providers/indexer.d.ts +8 -8
  69. package/dist/types/providers/utils.d.ts +18 -0
  70. package/dist/types/script/base.d.ts +3 -2
  71. package/dist/types/tree/signingSession.d.ts +10 -10
  72. package/dist/types/utils/anchor.d.ts +2 -2
  73. package/dist/types/utils/arkTransaction.d.ts +16 -4
  74. package/dist/types/utils/unknownFields.d.ts +2 -2
  75. package/dist/types/wallet/index.d.ts +47 -7
  76. package/dist/types/wallet/onchain.d.ts +1 -1
  77. package/dist/types/wallet/serviceWorker/utils.d.ts +1 -2
  78. package/dist/types/wallet/serviceWorker/wallet.d.ts +2 -2
  79. package/dist/types/wallet/serviceWorker/worker.d.ts +3 -1
  80. package/dist/types/wallet/unroll.d.ts +1 -1
  81. package/dist/types/wallet/utils.d.ts +2 -0
  82. package/dist/types/wallet/vtxo-manager.d.ts +207 -0
  83. package/dist/types/wallet/wallet.d.ts +16 -4
  84. package/package.json +11 -3
  85. package/dist/cjs/bip322/errors.js +0 -13
  86. package/dist/esm/bip322/errors.js +0 -9
  87. package/dist/types/bip322/errors.d.ts +0 -6
  88. package/dist/types/bip322/index.d.ts +0 -57
@@ -0,0 +1,372 @@
1
+ import { isRecoverable, isSubdust } from './index.js';
2
+ /**
3
+ * Default renewal configuration values
4
+ */
5
+ export const DEFAULT_RENEWAL_CONFIG = {
6
+ thresholdPercentage: 10,
7
+ };
8
+ /**
9
+ * Filter VTXOs that are recoverable (swept and still spendable, or preconfirmed subdust)
10
+ *
11
+ * Recovery strategy:
12
+ * - Always recover swept VTXOs (they've been taken by the server)
13
+ * - Only recover subdust preconfirmed VTXOs (to avoid locking liquidity on settled VTXOs with long expiry)
14
+ *
15
+ * @param vtxos - Array of virtual coins to check
16
+ * @param dustAmount - Dust threshold to identify subdust
17
+ * @returns Array of recoverable VTXOs
18
+ */
19
+ function getRecoverableVtxos(vtxos, dustAmount) {
20
+ return vtxos.filter((vtxo) => {
21
+ // Always recover swept VTXOs
22
+ if (isRecoverable(vtxo)) {
23
+ return true;
24
+ }
25
+ // Recover preconfirmed subdust to consolidate small amounts
26
+ if (vtxo.virtualStatus.state === "preconfirmed" &&
27
+ isSubdust(vtxo, dustAmount)) {
28
+ return true;
29
+ }
30
+ return false;
31
+ });
32
+ }
33
+ /**
34
+ * Get recoverable VTXOs including subdust coins if the total value exceeds dust threshold.
35
+ *
36
+ * Decision is based on the combined total of ALL recoverable VTXOs (regular + subdust),
37
+ * not just the subdust portion alone.
38
+ *
39
+ * @param vtxos - Array of virtual coins to check
40
+ * @param dustAmount - Dust threshold amount in satoshis
41
+ * @returns Object containing recoverable VTXOs and whether subdust should be included
42
+ */
43
+ function getRecoverableWithSubdust(vtxos, dustAmount) {
44
+ const recoverableVtxos = getRecoverableVtxos(vtxos, dustAmount);
45
+ // Separate subdust from regular recoverable
46
+ const subdust = [];
47
+ const regular = [];
48
+ for (const vtxo of recoverableVtxos) {
49
+ if (isSubdust(vtxo, dustAmount)) {
50
+ subdust.push(vtxo);
51
+ }
52
+ else {
53
+ regular.push(vtxo);
54
+ }
55
+ }
56
+ // Calculate totals
57
+ const regularTotal = regular.reduce((sum, vtxo) => sum + BigInt(vtxo.value), 0n);
58
+ const subdustTotal = subdust.reduce((sum, vtxo) => sum + BigInt(vtxo.value), 0n);
59
+ const combinedTotal = regularTotal + subdustTotal;
60
+ // Include subdust only if the combined total exceeds dust threshold
61
+ const shouldIncludeSubdust = combinedTotal >= dustAmount;
62
+ const vtxosToRecover = shouldIncludeSubdust ? recoverableVtxos : regular;
63
+ const totalAmount = vtxosToRecover.reduce((sum, vtxo) => sum + BigInt(vtxo.value), 0n);
64
+ return {
65
+ vtxosToRecover,
66
+ includesSubdust: shouldIncludeSubdust,
67
+ totalAmount,
68
+ };
69
+ }
70
+ /**
71
+ * Check if a VTXO is expiring soon based on threshold
72
+ *
73
+ * @param vtxo - The virtual coin to check
74
+ * @param thresholdMs - Threshold in milliseconds from now
75
+ * @returns true if VTXO expires within threshold, false otherwise
76
+ */
77
+ export function isVtxoExpiringSoon(vtxo, thresholdMs) {
78
+ const { batchExpiry } = vtxo.virtualStatus;
79
+ // No expiry set means it doesn't expire
80
+ if (!batchExpiry) {
81
+ return false;
82
+ }
83
+ const now = Date.now();
84
+ const timeUntilExpiry = batchExpiry - now;
85
+ return timeUntilExpiry > 0 && timeUntilExpiry <= thresholdMs;
86
+ }
87
+ /**
88
+ * Filter VTXOs that are expiring soon
89
+ *
90
+ * @param vtxos - Array of virtual coins to check
91
+ * @param thresholdMs - Threshold in milliseconds from now
92
+ * @returns Array of VTXOs expiring within threshold
93
+ */
94
+ export function getExpiringVtxos(vtxos, thresholdMs) {
95
+ return vtxos.filter((vtxo) => isVtxoExpiringSoon(vtxo, thresholdMs));
96
+ }
97
+ /**
98
+ * Calculate expiry threshold in milliseconds based on batch expiry and percentage
99
+ *
100
+ * @param batchExpiry - Batch expiry timestamp in milliseconds
101
+ * @param percentage - Percentage of total time (0-100)
102
+ * @returns Threshold timestamp in milliseconds from now
103
+ *
104
+ * @example
105
+ * // VTXO expires in 10 days, threshold is 10%
106
+ * const expiry = Date.now() + 10 * 24 * 60 * 60 * 1000;
107
+ * const threshold = calculateExpiryThreshold(expiry, 10);
108
+ * // Returns 1 day in milliseconds (10% of 10 days)
109
+ */
110
+ export function calculateExpiryThreshold(batchExpiry, percentage) {
111
+ if (percentage < 0 || percentage > 100) {
112
+ throw new Error("Percentage must be between 0 and 100");
113
+ }
114
+ const now = Date.now();
115
+ const totalTime = batchExpiry - now;
116
+ if (totalTime <= 0) {
117
+ // Already expired
118
+ return 0;
119
+ }
120
+ // Calculate threshold as percentage of total time
121
+ return Math.floor((totalTime * percentage) / 100);
122
+ }
123
+ /**
124
+ * Get the minimum expiry time from a list of VTXOs
125
+ *
126
+ * @param vtxos - Array of virtual coins
127
+ * @returns Minimum batch expiry timestamp, or undefined if no VTXOs have expiry
128
+ */
129
+ export function getMinimumExpiry(vtxos) {
130
+ const expiries = vtxos
131
+ .map((v) => v.virtualStatus.batchExpiry)
132
+ .filter((e) => e !== undefined);
133
+ if (expiries.length === 0) {
134
+ return undefined;
135
+ }
136
+ return Math.min(...expiries);
137
+ }
138
+ /**
139
+ * Calculate dynamic threshold based on the earliest expiring VTXO
140
+ *
141
+ * @param vtxos - Array of virtual coins
142
+ * @param percentage - Percentage of time until expiry (0-100)
143
+ * @returns Threshold in milliseconds, or undefined if no VTXOs have expiry
144
+ */
145
+ export function calculateDynamicThreshold(vtxos, percentage) {
146
+ const minExpiry = getMinimumExpiry(vtxos);
147
+ if (!minExpiry) {
148
+ return undefined;
149
+ }
150
+ return calculateExpiryThreshold(minExpiry, percentage);
151
+ }
152
+ /**
153
+ * VtxoManager is a unified class for managing VTXO lifecycle operations including
154
+ * recovery of swept/expired VTXOs and renewal to prevent expiration.
155
+ *
156
+ * Key Features:
157
+ * - **Recovery**: Reclaim swept or expired VTXOs back to the wallet
158
+ * - **Renewal**: Refresh VTXO expiration time before they expire
159
+ * - **Smart subdust handling**: Automatically includes subdust VTXOs when economically viable
160
+ * - **Expiry monitoring**: Check for VTXOs that are expiring soon
161
+ *
162
+ * VTXOs become recoverable when:
163
+ * - The Ark server sweeps them (virtualStatus.state === "swept") and they remain spendable
164
+ * - They are preconfirmed subdust (to consolidate small amounts without locking liquidity on settled VTXOs)
165
+ *
166
+ * @example
167
+ * ```typescript
168
+ * // Initialize with renewal config
169
+ * const manager = new VtxoManager(wallet, {
170
+ * enabled: true,
171
+ * thresholdPercentage: 10
172
+ * });
173
+ *
174
+ * // Check recoverable balance
175
+ * const balance = await manager.getRecoverableBalance();
176
+ * if (balance.recoverable > 0n) {
177
+ * console.log(`Can recover ${balance.recoverable} sats`);
178
+ * const txid = await manager.recoverVtxos();
179
+ * }
180
+ *
181
+ * // Check for expiring VTXOs
182
+ * const expiring = await manager.getExpiringVtxos();
183
+ * if (expiring.length > 0) {
184
+ * console.log(`${expiring.length} VTXOs expiring soon`);
185
+ * const txid = await manager.renewVtxos();
186
+ * }
187
+ * ```
188
+ */
189
+ export class VtxoManager {
190
+ constructor(wallet, renewalConfig) {
191
+ this.wallet = wallet;
192
+ this.renewalConfig = renewalConfig;
193
+ }
194
+ // ========== Recovery Methods ==========
195
+ /**
196
+ * Recover swept/expired VTXOs by settling them back to the wallet's Ark address.
197
+ *
198
+ * This method:
199
+ * 1. Fetches all VTXOs (including recoverable ones)
200
+ * 2. Filters for swept but still spendable VTXOs and preconfirmed subdust
201
+ * 3. Includes subdust VTXOs if the total value >= dust threshold
202
+ * 4. Settles everything back to the wallet's Ark address
203
+ *
204
+ * Note: Settled VTXOs with long expiry are NOT recovered to avoid locking liquidity unnecessarily.
205
+ * Only preconfirmed subdust is recovered to consolidate small amounts.
206
+ *
207
+ * @param eventCallback - Optional callback to receive settlement events
208
+ * @returns Settlement transaction ID
209
+ * @throws Error if no recoverable VTXOs found
210
+ *
211
+ * @example
212
+ * ```typescript
213
+ * const manager = new VtxoManager(wallet);
214
+ *
215
+ * // Simple recovery
216
+ * const txid = await manager.recoverVtxos();
217
+ *
218
+ * // With event callback
219
+ * const txid = await manager.recoverVtxos((event) => {
220
+ * console.log('Settlement event:', event.type);
221
+ * });
222
+ * ```
223
+ */
224
+ async recoverVtxos(eventCallback) {
225
+ // Get all VTXOs including recoverable ones
226
+ const allVtxos = await this.wallet.getVtxos({
227
+ withRecoverable: true,
228
+ withUnrolled: false,
229
+ });
230
+ // Get dust amount from wallet
231
+ const dustAmount = "dustAmount" in this.wallet
232
+ ? this.wallet.dustAmount
233
+ : 1000n;
234
+ // Filter recoverable VTXOs and handle subdust logic
235
+ const { vtxosToRecover, includesSubdust, totalAmount } = getRecoverableWithSubdust(allVtxos, dustAmount);
236
+ if (vtxosToRecover.length === 0) {
237
+ throw new Error("No recoverable VTXOs found");
238
+ }
239
+ const arkAddress = await this.wallet.getAddress();
240
+ // Settle all recoverable VTXOs back to the wallet
241
+ return this.wallet.settle({
242
+ inputs: vtxosToRecover,
243
+ outputs: [
244
+ {
245
+ address: arkAddress,
246
+ amount: totalAmount,
247
+ },
248
+ ],
249
+ }, eventCallback);
250
+ }
251
+ /**
252
+ * Get information about recoverable balance without executing recovery.
253
+ *
254
+ * Useful for displaying to users before they decide to recover funds.
255
+ *
256
+ * @returns Object containing recoverable amounts and subdust information
257
+ *
258
+ * @example
259
+ * ```typescript
260
+ * const manager = new VtxoManager(wallet);
261
+ * const balance = await manager.getRecoverableBalance();
262
+ *
263
+ * if (balance.recoverable > 0n) {
264
+ * console.log(`You can recover ${balance.recoverable} sats`);
265
+ * if (balance.includesSubdust) {
266
+ * console.log(`This includes ${balance.subdust} sats from subdust VTXOs`);
267
+ * }
268
+ * }
269
+ * ```
270
+ */
271
+ async getRecoverableBalance() {
272
+ const allVtxos = await this.wallet.getVtxos({
273
+ withRecoverable: true,
274
+ withUnrolled: false,
275
+ });
276
+ const dustAmount = "dustAmount" in this.wallet
277
+ ? this.wallet.dustAmount
278
+ : 1000n;
279
+ const { vtxosToRecover, includesSubdust, totalAmount } = getRecoverableWithSubdust(allVtxos, dustAmount);
280
+ // Calculate subdust amount separately for reporting
281
+ const subdustAmount = vtxosToRecover
282
+ .filter((v) => BigInt(v.value) < dustAmount)
283
+ .reduce((sum, v) => sum + BigInt(v.value), 0n);
284
+ return {
285
+ recoverable: totalAmount,
286
+ subdust: subdustAmount,
287
+ includesSubdust,
288
+ vtxoCount: vtxosToRecover.length,
289
+ };
290
+ }
291
+ // ========== Renewal Methods ==========
292
+ /**
293
+ * Get VTXOs that are expiring soon based on renewal configuration
294
+ *
295
+ * @param thresholdPercentage - Optional override for threshold percentage (0-100)
296
+ * @returns Array of expiring VTXOs, empty array if renewal is disabled or no VTXOs expiring
297
+ *
298
+ * @example
299
+ * ```typescript
300
+ * const manager = new VtxoManager(wallet, { enabled: true, thresholdPercentage: 10 });
301
+ * const expiringVtxos = await manager.getExpiringVtxos();
302
+ * if (expiringVtxos.length > 0) {
303
+ * console.log(`${expiringVtxos.length} VTXOs expiring soon`);
304
+ * }
305
+ * ```
306
+ */
307
+ async getExpiringVtxos(thresholdPercentage) {
308
+ if (!this.renewalConfig?.enabled) {
309
+ return [];
310
+ }
311
+ const vtxos = await this.wallet.getVtxos();
312
+ const percentage = thresholdPercentage ??
313
+ this.renewalConfig.thresholdPercentage ??
314
+ DEFAULT_RENEWAL_CONFIG.thresholdPercentage;
315
+ const threshold = calculateDynamicThreshold(vtxos, percentage);
316
+ if (!threshold) {
317
+ return [];
318
+ }
319
+ return getExpiringVtxos(vtxos, threshold);
320
+ }
321
+ /**
322
+ * Renew VTXOs by settling them back to the wallet's address
323
+ *
324
+ * This method collects all spendable VTXOs (including recoverable ones) and settles
325
+ * them back to the wallet, effectively refreshing their expiration time. This is the
326
+ * primary way to prevent VTXOs from expiring.
327
+ *
328
+ * @param eventCallback - Optional callback for settlement events
329
+ * @returns Settlement transaction ID
330
+ * @throws Error if no VTXOs available to renew
331
+ * @throws Error if total amount is below dust threshold
332
+ *
333
+ * @example
334
+ * ```typescript
335
+ * const manager = new VtxoManager(wallet);
336
+ *
337
+ * // Simple renewal
338
+ * const txid = await manager.renewVtxos();
339
+ *
340
+ * // With event callback
341
+ * const txid = await manager.renewVtxos((event) => {
342
+ * console.log('Settlement event:', event.type);
343
+ * });
344
+ * ```
345
+ */
346
+ async renewVtxos(eventCallback) {
347
+ // Get all VTXOs (including recoverable ones)
348
+ const vtxos = await this.wallet.getVtxos({ withRecoverable: true });
349
+ if (vtxos.length === 0) {
350
+ throw new Error("No VTXOs available to renew");
351
+ }
352
+ const totalAmount = vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
353
+ // Get dust amount from wallet
354
+ const dustAmount = "dustAmount" in this.wallet
355
+ ? this.wallet.dustAmount
356
+ : 1000n;
357
+ // Check if total amount is above dust threshold
358
+ if (BigInt(totalAmount) < dustAmount) {
359
+ throw new Error(`Total amount ${totalAmount} is below dust threshold ${dustAmount}`);
360
+ }
361
+ const arkAddress = await this.wallet.getAddress();
362
+ return this.wallet.settle({
363
+ inputs: vtxos,
364
+ outputs: [
365
+ {
366
+ address: arkAddress,
367
+ amount: BigInt(totalAmount),
368
+ },
369
+ ],
370
+ }, eventCallback);
371
+ }
372
+ }