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