@routstr/sdk 0.1.0 → 0.1.1

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.
@@ -0,0 +1,1134 @@
1
+ // core/errors.ts
2
+ var InsufficientBalanceError = class extends Error {
3
+ constructor(required, available, maxMintBalance = 0, maxMintUrl = "") {
4
+ super(
5
+ `Insufficient balance: need ${required} sats, have ${available} sats available. ` + (maxMintBalance > 0 ? `Largest mint balance: ${maxMintBalance} sats from ${maxMintUrl}` : "")
6
+ );
7
+ this.required = required;
8
+ this.available = available;
9
+ this.maxMintBalance = maxMintBalance;
10
+ this.maxMintUrl = maxMintUrl;
11
+ this.name = "InsufficientBalanceError";
12
+ }
13
+ };
14
+
15
+ // wallet/AuditLogger.ts
16
+ var AuditLogger = class _AuditLogger {
17
+ static instance = null;
18
+ static getInstance() {
19
+ if (!_AuditLogger.instance) {
20
+ _AuditLogger.instance = new _AuditLogger();
21
+ }
22
+ return _AuditLogger.instance;
23
+ }
24
+ async log(entry) {
25
+ const fullEntry = {
26
+ ...entry,
27
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
28
+ };
29
+ const logLine = JSON.stringify(fullEntry) + "\n";
30
+ if (typeof window === "undefined") {
31
+ try {
32
+ const fs = await import('fs');
33
+ const path = await import('path');
34
+ const logPath = path.join(process.cwd(), "audit.log");
35
+ fs.appendFileSync(logPath, logLine);
36
+ } catch (error) {
37
+ console.error("[AuditLogger] Failed to write to file:", error);
38
+ }
39
+ } else {
40
+ console.log("[AUDIT]", logLine.trim());
41
+ }
42
+ }
43
+ async logBalanceSnapshot(action, amounts, options) {
44
+ await this.log({
45
+ action,
46
+ totalBalance: amounts.totalBalance,
47
+ providerBalances: amounts.providerBalances,
48
+ mintBalances: amounts.mintBalances,
49
+ amount: options?.amount,
50
+ mintUrl: options?.mintUrl,
51
+ baseUrl: options?.baseUrl,
52
+ status: options?.status ?? "success",
53
+ details: options?.details
54
+ });
55
+ }
56
+ };
57
+ var auditLogger = AuditLogger.getInstance();
58
+
59
+ // wallet/tokenUtils.ts
60
+ function isNetworkErrorMessage(message) {
61
+ return message.includes("NetworkError when attempting to fetch resource") || message.includes("Failed to fetch") || message.includes("Load failed");
62
+ }
63
+ function getBalanceInSats(balance, unit) {
64
+ return unit === "msat" ? balance / 1e3 : balance;
65
+ }
66
+ function selectMintWithBalance(balances, units, amount, excludeMints = []) {
67
+ for (const mintUrl in balances) {
68
+ if (excludeMints.includes(mintUrl)) {
69
+ continue;
70
+ }
71
+ const balanceInSats = getBalanceInSats(balances[mintUrl], units[mintUrl]);
72
+ if (balanceInSats >= amount) {
73
+ return { selectedMintUrl: mintUrl, selectedMintBalance: balanceInSats };
74
+ }
75
+ }
76
+ return { selectedMintUrl: null, selectedMintBalance: 0 };
77
+ }
78
+
79
+ // wallet/CashuSpender.ts
80
+ var CashuSpender = class {
81
+ constructor(walletAdapter, storageAdapter, _providerRegistry, balanceManager) {
82
+ this.walletAdapter = walletAdapter;
83
+ this.storageAdapter = storageAdapter;
84
+ this._providerRegistry = _providerRegistry;
85
+ this.balanceManager = balanceManager;
86
+ }
87
+ _isBusy = false;
88
+ async _getBalanceState() {
89
+ const mintBalances = await this.walletAdapter.getBalances();
90
+ const units = this.walletAdapter.getMintUnits();
91
+ let totalMintBalance = 0;
92
+ const normalizedMintBalances = {};
93
+ for (const url in mintBalances) {
94
+ const balance = mintBalances[url];
95
+ const unit = units[url];
96
+ const balanceInSats = getBalanceInSats(balance, unit);
97
+ normalizedMintBalances[url] = balanceInSats;
98
+ totalMintBalance += balanceInSats;
99
+ }
100
+ const pendingDistribution = this.storageAdapter.getCachedTokenDistribution();
101
+ const providerBalances = {};
102
+ let totalProviderBalance = 0;
103
+ for (const pending of pendingDistribution) {
104
+ providerBalances[pending.baseUrl] = pending.amount;
105
+ totalProviderBalance += pending.amount;
106
+ }
107
+ const apiKeys = this.storageAdapter.getAllApiKeys();
108
+ for (const apiKey of apiKeys) {
109
+ if (!providerBalances[apiKey.baseUrl]) {
110
+ providerBalances[apiKey.baseUrl] = apiKey.balance;
111
+ totalProviderBalance += apiKey.balance;
112
+ }
113
+ }
114
+ return {
115
+ totalBalance: totalMintBalance + totalProviderBalance,
116
+ providerBalances,
117
+ mintBalances: normalizedMintBalances
118
+ };
119
+ }
120
+ async _logTransaction(action, options) {
121
+ const balanceState = await this._getBalanceState();
122
+ await auditLogger.logBalanceSnapshot(action, balanceState, options);
123
+ }
124
+ /**
125
+ * Check if the spender is currently in a critical operation
126
+ */
127
+ get isBusy() {
128
+ return this._isBusy;
129
+ }
130
+ /**
131
+ * Spend Cashu tokens with automatic mint selection and retry logic
132
+ * Throws errors on failure instead of returning failed SpendResult
133
+ */
134
+ async spend(options) {
135
+ const {
136
+ mintUrl,
137
+ amount,
138
+ baseUrl,
139
+ reuseToken = false,
140
+ p2pkPubkey,
141
+ excludeMints = [],
142
+ retryCount = 0
143
+ } = options;
144
+ this._isBusy = true;
145
+ try {
146
+ const result = await this._spendInternal({
147
+ mintUrl,
148
+ amount,
149
+ baseUrl,
150
+ reuseToken,
151
+ p2pkPubkey,
152
+ excludeMints,
153
+ retryCount
154
+ });
155
+ if (result.status === "failed" || !result.token) {
156
+ const errorMsg = result.error || `Insufficient balance. Need ${amount} sats.`;
157
+ if (this._isNetworkError(errorMsg)) {
158
+ throw new Error(
159
+ `Your mint ${mintUrl} is unreachable or is blocking your IP. Please try again later or switch mints.`
160
+ );
161
+ }
162
+ if (result.errorDetails) {
163
+ throw new InsufficientBalanceError(
164
+ result.errorDetails.required,
165
+ result.errorDetails.available,
166
+ result.errorDetails.maxMintBalance,
167
+ result.errorDetails.maxMintUrl
168
+ );
169
+ }
170
+ throw new Error(errorMsg);
171
+ }
172
+ return result;
173
+ } finally {
174
+ this._isBusy = false;
175
+ }
176
+ }
177
+ /**
178
+ * Check if error message indicates a network error
179
+ */
180
+ _isNetworkError(message) {
181
+ return isNetworkErrorMessage(message) || message.includes("Your mint") && message.includes("unreachable");
182
+ }
183
+ /**
184
+ * Internal spending logic
185
+ */
186
+ async _spendInternal(options) {
187
+ let {
188
+ mintUrl,
189
+ amount,
190
+ baseUrl,
191
+ reuseToken,
192
+ p2pkPubkey,
193
+ excludeMints,
194
+ retryCount
195
+ } = options;
196
+ console.log(
197
+ `[CashuSpender] _spendInternal: amount=${amount}, mintUrl=${mintUrl}, baseUrl=${baseUrl}, reuseToken=${reuseToken}`
198
+ );
199
+ let adjustedAmount = Math.ceil(amount);
200
+ if (!adjustedAmount || isNaN(adjustedAmount)) {
201
+ console.error(`[CashuSpender] _spendInternal: Invalid amount: ${amount}`);
202
+ return {
203
+ token: null,
204
+ status: "failed",
205
+ balance: 0,
206
+ error: "Please enter a valid amount"
207
+ };
208
+ }
209
+ if (reuseToken && baseUrl) {
210
+ console.log(
211
+ `[CashuSpender] _spendInternal: Attempting to reuse token for ${baseUrl}`
212
+ );
213
+ const existingResult = await this._tryReuseToken(
214
+ baseUrl,
215
+ adjustedAmount,
216
+ mintUrl
217
+ );
218
+ if (existingResult) {
219
+ console.log(
220
+ `[CashuSpender] _spendInternal: Successfully reused token, balance: ${existingResult.balance}`
221
+ );
222
+ return existingResult;
223
+ }
224
+ console.log(
225
+ `[CashuSpender] _spendInternal: Could not reuse token, will create new token`
226
+ );
227
+ }
228
+ const balances = await this.walletAdapter.getBalances();
229
+ const units = this.walletAdapter.getMintUnits();
230
+ let totalBalance = 0;
231
+ for (const url in balances) {
232
+ const balance = balances[url];
233
+ const unit = units[url];
234
+ const balanceInSats = getBalanceInSats(balance, unit);
235
+ totalBalance += balanceInSats;
236
+ }
237
+ const pendingDistribution = this.storageAdapter.getCachedTokenDistribution();
238
+ const totalPending = pendingDistribution.reduce(
239
+ (sum, item) => sum + item.amount,
240
+ 0
241
+ );
242
+ console.log(
243
+ `[CashuSpender] _spendInternal: totalBalance=${totalBalance}, totalPending=${totalPending}, adjustedAmount=${adjustedAmount}`
244
+ );
245
+ const totalAvailableBalance = totalBalance + totalPending;
246
+ if (totalAvailableBalance < adjustedAmount) {
247
+ console.error(
248
+ `[CashuSpender] _spendInternal: Insufficient balance, have=${totalAvailableBalance}, need=${adjustedAmount}`
249
+ );
250
+ return this._createInsufficientBalanceError(
251
+ adjustedAmount,
252
+ balances,
253
+ units,
254
+ totalAvailableBalance
255
+ );
256
+ }
257
+ let token = null;
258
+ let selectedMintUrl;
259
+ let spentAmount = adjustedAmount;
260
+ if (this.balanceManager) {
261
+ const tokenResult = await this.balanceManager.createProviderToken({
262
+ mintUrl,
263
+ baseUrl,
264
+ amount: adjustedAmount,
265
+ p2pkPubkey,
266
+ excludeMints,
267
+ retryCount
268
+ });
269
+ if (!tokenResult.success || !tokenResult.token) {
270
+ if ((tokenResult.error || "").includes("Insufficient balance")) {
271
+ return this._createInsufficientBalanceError(
272
+ adjustedAmount,
273
+ balances,
274
+ units,
275
+ totalAvailableBalance
276
+ );
277
+ }
278
+ return {
279
+ token: null,
280
+ status: "failed",
281
+ balance: 0,
282
+ error: tokenResult.error || "Failed to create token"
283
+ };
284
+ }
285
+ token = tokenResult.token;
286
+ selectedMintUrl = tokenResult.selectedMintUrl;
287
+ spentAmount = tokenResult.amountSpent || adjustedAmount;
288
+ } else {
289
+ try {
290
+ token = await this.walletAdapter.sendToken(
291
+ mintUrl,
292
+ adjustedAmount,
293
+ p2pkPubkey
294
+ );
295
+ selectedMintUrl = mintUrl;
296
+ } catch (error) {
297
+ const errorMsg = error instanceof Error ? error.message : String(error);
298
+ return {
299
+ token: null,
300
+ status: "failed",
301
+ balance: 0,
302
+ error: `Error generating token: ${errorMsg}`
303
+ };
304
+ }
305
+ }
306
+ if (token && baseUrl) {
307
+ this.storageAdapter.setToken(baseUrl, token);
308
+ }
309
+ this._logTransaction("spend", {
310
+ amount: spentAmount,
311
+ mintUrl: selectedMintUrl || mintUrl,
312
+ baseUrl,
313
+ status: "success"
314
+ });
315
+ console.log(
316
+ `[CashuSpender] _spendInternal: Successfully spent ${spentAmount}, returning token with balance=${spentAmount}`
317
+ );
318
+ return {
319
+ token,
320
+ status: "success",
321
+ balance: spentAmount,
322
+ unit: (selectedMintUrl ? units[selectedMintUrl] : units[mintUrl]) || "sat"
323
+ };
324
+ }
325
+ /**
326
+ * Try to reuse an existing token
327
+ */
328
+ async _tryReuseToken(baseUrl, amount, mintUrl) {
329
+ const storedToken = this.storageAdapter.getToken(baseUrl);
330
+ if (!storedToken) return null;
331
+ const pendingDistribution = this.storageAdapter.getCachedTokenDistribution();
332
+ const balanceForBaseUrl = pendingDistribution.find((b) => b.baseUrl === baseUrl)?.amount || 0;
333
+ console.log("RESUINGDSR GSODGNSD", balanceForBaseUrl, amount);
334
+ if (balanceForBaseUrl > amount) {
335
+ const units = this.walletAdapter.getMintUnits();
336
+ const unit = units[mintUrl] || "sat";
337
+ return {
338
+ token: storedToken,
339
+ status: "success",
340
+ balance: balanceForBaseUrl,
341
+ unit
342
+ };
343
+ }
344
+ if (this.balanceManager) {
345
+ const topUpAmount = Math.ceil(amount * 1.2 - balanceForBaseUrl);
346
+ const topUpResult = await this.balanceManager.topUp({
347
+ mintUrl,
348
+ baseUrl,
349
+ amount: topUpAmount
350
+ });
351
+ console.log("TOPUP ", topUpResult);
352
+ if (topUpResult.success && topUpResult.toppedUpAmount) {
353
+ const newBalance = balanceForBaseUrl + topUpResult.toppedUpAmount;
354
+ const units = this.walletAdapter.getMintUnits();
355
+ const unit = units[mintUrl] || "sat";
356
+ this._logTransaction("topup", {
357
+ amount: topUpResult.toppedUpAmount,
358
+ mintUrl,
359
+ baseUrl,
360
+ status: "success"
361
+ });
362
+ return {
363
+ token: storedToken,
364
+ status: "success",
365
+ balance: newBalance,
366
+ unit
367
+ };
368
+ }
369
+ const providerBalance = await this._getProviderTokenBalance(
370
+ baseUrl,
371
+ storedToken
372
+ );
373
+ console.log(providerBalance);
374
+ if (providerBalance <= 0) {
375
+ this.storageAdapter.removeToken(baseUrl);
376
+ }
377
+ }
378
+ return null;
379
+ }
380
+ /**
381
+ * Refund specific providers without retrying spend
382
+ */
383
+ async refundProviders(baseUrls, mintUrl, refundApiKeys = false) {
384
+ const results = [];
385
+ const pendingDistribution = this.storageAdapter.getCachedTokenDistribution();
386
+ const toRefund = pendingDistribution.filter(
387
+ (p) => baseUrls.includes(p.baseUrl)
388
+ );
389
+ const refundResults = await Promise.allSettled(
390
+ toRefund.map(async (pending) => {
391
+ const token = this.storageAdapter.getToken(pending.baseUrl);
392
+ console.log(token, this.balanceManager);
393
+ if (!token || !this.balanceManager) {
394
+ return { baseUrl: pending.baseUrl, success: false };
395
+ }
396
+ const tokenBalance = await this.balanceManager.getTokenBalance(
397
+ token,
398
+ pending.baseUrl
399
+ );
400
+ if (tokenBalance.reserved > 0) {
401
+ return { baseUrl: pending.baseUrl, success: false };
402
+ }
403
+ const result = await this.balanceManager.refund({
404
+ mintUrl,
405
+ baseUrl: pending.baseUrl,
406
+ token
407
+ });
408
+ console.log(result);
409
+ if (result.success) {
410
+ this.storageAdapter.removeToken(pending.baseUrl);
411
+ }
412
+ return { baseUrl: pending.baseUrl, success: result.success };
413
+ })
414
+ );
415
+ results.push(
416
+ ...refundResults.map(
417
+ (r) => r.status === "fulfilled" ? r.value : { baseUrl: "", success: false }
418
+ )
419
+ );
420
+ if (refundApiKeys) {
421
+ const apiKeyDistribution = this.storageAdapter.getApiKeyDistribution();
422
+ const apiKeysToRefund = apiKeyDistribution.filter(
423
+ (p) => baseUrls.includes(p.baseUrl)
424
+ );
425
+ for (const apiKeyEntry of apiKeysToRefund) {
426
+ const apiKeyEntryFull = this.storageAdapter.getApiKey(
427
+ apiKeyEntry.baseUrl
428
+ );
429
+ if (apiKeyEntryFull && this.balanceManager) {
430
+ const refundResult = await this.balanceManager.refundApiKey({
431
+ mintUrl,
432
+ baseUrl: apiKeyEntry.baseUrl,
433
+ apiKey: apiKeyEntryFull.key
434
+ });
435
+ if (refundResult.success) {
436
+ this.storageAdapter.updateApiKeyBalance(apiKeyEntry.baseUrl, 0);
437
+ }
438
+ results.push({
439
+ baseUrl: apiKeyEntry.baseUrl,
440
+ success: refundResult.success
441
+ });
442
+ } else {
443
+ results.push({
444
+ baseUrl: apiKeyEntry.baseUrl,
445
+ success: false
446
+ });
447
+ }
448
+ }
449
+ }
450
+ return results;
451
+ }
452
+ /**
453
+ * Create an insufficient balance error result
454
+ */
455
+ _createInsufficientBalanceError(required, balances, units, availableBalance) {
456
+ let maxBalance = 0;
457
+ let maxMintUrl = "";
458
+ for (const mintUrl in balances) {
459
+ const balance = balances[mintUrl];
460
+ const unit = units[mintUrl];
461
+ const balanceInSats = getBalanceInSats(balance, unit);
462
+ if (balanceInSats > maxBalance) {
463
+ maxBalance = balanceInSats;
464
+ maxMintUrl = mintUrl;
465
+ }
466
+ }
467
+ const error = new InsufficientBalanceError(
468
+ required,
469
+ availableBalance ?? maxBalance,
470
+ maxBalance,
471
+ maxMintUrl
472
+ );
473
+ return {
474
+ token: null,
475
+ status: "failed",
476
+ balance: 0,
477
+ error: error.message,
478
+ errorDetails: {
479
+ required,
480
+ available: availableBalance ?? maxBalance,
481
+ maxMintBalance: maxBalance,
482
+ maxMintUrl
483
+ }
484
+ };
485
+ }
486
+ async _getProviderTokenBalance(baseUrl, token) {
487
+ try {
488
+ const response = await fetch(`${baseUrl}v1/wallet/info`, {
489
+ headers: {
490
+ Authorization: `Bearer ${token}`
491
+ }
492
+ });
493
+ if (response.ok) {
494
+ const data = await response.json();
495
+ return data.balance / 1e3;
496
+ }
497
+ } catch {
498
+ return 0;
499
+ }
500
+ return 0;
501
+ }
502
+ };
503
+
504
+ // wallet/BalanceManager.ts
505
+ var BalanceManager = class {
506
+ constructor(walletAdapter, storageAdapter, providerRegistry) {
507
+ this.walletAdapter = walletAdapter;
508
+ this.storageAdapter = storageAdapter;
509
+ this.providerRegistry = providerRegistry;
510
+ }
511
+ /**
512
+ * Unified refund - handles both NIP-60 and legacy wallet refunds
513
+ */
514
+ async refund(options) {
515
+ const { mintUrl, baseUrl, token: providedToken } = options;
516
+ const storedToken = providedToken || this.storageAdapter.getToken(baseUrl);
517
+ if (!storedToken) {
518
+ console.log("[BalanceManager] No token to refund, returning early");
519
+ return { success: true, message: "No API key to refund" };
520
+ }
521
+ let fetchResult;
522
+ try {
523
+ fetchResult = await this._fetchRefundToken(baseUrl, storedToken);
524
+ if (!fetchResult.success) {
525
+ return {
526
+ success: false,
527
+ message: fetchResult.error || "Refund failed",
528
+ requestId: fetchResult.requestId
529
+ };
530
+ }
531
+ if (!fetchResult.token) {
532
+ return {
533
+ success: false,
534
+ message: "No token received from refund",
535
+ requestId: fetchResult.requestId
536
+ };
537
+ }
538
+ if (fetchResult.error === "No balance to refund") {
539
+ console.log(
540
+ "[BalanceManager] No balance to refund, removing stored token"
541
+ );
542
+ this.storageAdapter.removeToken(baseUrl);
543
+ return { success: true, message: "No balance to refund" };
544
+ }
545
+ const receiveResult = await this.walletAdapter.receiveToken(
546
+ fetchResult.token
547
+ );
548
+ const totalAmountMsat = receiveResult.unit === "msat" ? receiveResult.amount : receiveResult.amount * 1e3;
549
+ if (!providedToken) {
550
+ this.storageAdapter.removeToken(baseUrl);
551
+ }
552
+ return {
553
+ success: receiveResult.success,
554
+ refundedAmount: totalAmountMsat,
555
+ requestId: fetchResult.requestId
556
+ };
557
+ } catch (error) {
558
+ console.error("[BalanceManager] Refund error", error);
559
+ return this._handleRefundError(error, mintUrl, fetchResult?.requestId);
560
+ }
561
+ }
562
+ /**
563
+ * Refund API key balance - convert remaining API key balance to cashu token
564
+ */
565
+ async refundApiKey(options) {
566
+ const { mintUrl, baseUrl, apiKey } = options;
567
+ if (!apiKey) {
568
+ return { success: false, message: "No API key to refund" };
569
+ }
570
+ let fetchResult;
571
+ try {
572
+ fetchResult = await this._fetchRefundTokenWithApiKey(baseUrl, apiKey);
573
+ if (!fetchResult.success) {
574
+ return {
575
+ success: false,
576
+ message: fetchResult.error || "API key refund failed",
577
+ requestId: fetchResult.requestId
578
+ };
579
+ }
580
+ if (!fetchResult.token) {
581
+ return {
582
+ success: false,
583
+ message: "No token received from API key refund",
584
+ requestId: fetchResult.requestId
585
+ };
586
+ }
587
+ if (fetchResult.error === "No balance to refund") {
588
+ return { success: false, message: "No balance to refund" };
589
+ }
590
+ const receiveResult = await this.walletAdapter.receiveToken(
591
+ fetchResult.token
592
+ );
593
+ const totalAmountMsat = receiveResult.unit === "msat" ? receiveResult.amount : receiveResult.amount * 1e3;
594
+ return {
595
+ success: receiveResult.success,
596
+ refundedAmount: totalAmountMsat,
597
+ requestId: fetchResult.requestId
598
+ };
599
+ } catch (error) {
600
+ console.error("[BalanceManager] API key refund error", error);
601
+ return this._handleRefundError(error, mintUrl, fetchResult?.requestId);
602
+ }
603
+ }
604
+ /**
605
+ * Fetch refund token from provider API using API key authentication
606
+ */
607
+ async _fetchRefundTokenWithApiKey(baseUrl, apiKey) {
608
+ if (!baseUrl) {
609
+ return {
610
+ success: false,
611
+ error: "No base URL configured"
612
+ };
613
+ }
614
+ const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
615
+ const url = `${normalizedBaseUrl}v1/wallet/refund`;
616
+ const controller = new AbortController();
617
+ const timeoutId = setTimeout(() => {
618
+ controller.abort();
619
+ }, 6e4);
620
+ try {
621
+ const response = await fetch(url, {
622
+ method: "POST",
623
+ headers: {
624
+ Authorization: `Bearer ${apiKey}`,
625
+ "Content-Type": "application/json"
626
+ },
627
+ signal: controller.signal
628
+ });
629
+ clearTimeout(timeoutId);
630
+ const requestId = response.headers.get("x-routstr-request-id") || void 0;
631
+ if (!response.ok) {
632
+ const errorData = await response.json().catch(() => ({}));
633
+ return {
634
+ success: false,
635
+ requestId,
636
+ error: `API key refund failed: ${errorData?.detail || response.statusText}`
637
+ };
638
+ }
639
+ const data = await response.json();
640
+ return {
641
+ success: true,
642
+ token: data.token,
643
+ requestId
644
+ };
645
+ } catch (error) {
646
+ clearTimeout(timeoutId);
647
+ console.error(
648
+ "[BalanceManager._fetchRefundTokenWithApiKey] Fetch error",
649
+ error
650
+ );
651
+ if (error instanceof Error) {
652
+ if (error.name === "AbortError") {
653
+ return {
654
+ success: false,
655
+ error: "Request timed out after 1 minute"
656
+ };
657
+ }
658
+ return {
659
+ success: false,
660
+ error: error.message
661
+ };
662
+ }
663
+ return {
664
+ success: false,
665
+ error: "Unknown error occurred during API key refund request"
666
+ };
667
+ }
668
+ }
669
+ /**
670
+ * Top up API key balance with a cashu token
671
+ */
672
+ async topUp(options) {
673
+ const { mintUrl, baseUrl, amount, token: providedToken } = options;
674
+ if (!amount || amount <= 0) {
675
+ return { success: false, message: "Invalid top up amount" };
676
+ }
677
+ const storedToken = providedToken || this.storageAdapter.getToken(baseUrl);
678
+ if (!storedToken) {
679
+ return { success: false, message: "No API key available for top up" };
680
+ }
681
+ let cashuToken = null;
682
+ let requestId;
683
+ try {
684
+ const tokenResult = await this.createProviderToken({
685
+ mintUrl,
686
+ baseUrl,
687
+ amount
688
+ });
689
+ if (!tokenResult.success || !tokenResult.token) {
690
+ return {
691
+ success: false,
692
+ message: tokenResult.error || "Unable to create top up token"
693
+ };
694
+ }
695
+ cashuToken = tokenResult.token;
696
+ const topUpResult = await this._postTopUp(
697
+ baseUrl,
698
+ storedToken,
699
+ cashuToken
700
+ );
701
+ requestId = topUpResult.requestId;
702
+ console.log(topUpResult);
703
+ if (!topUpResult.success) {
704
+ await this._recoverFailedTopUp(cashuToken);
705
+ return {
706
+ success: false,
707
+ message: topUpResult.error || "Top up failed",
708
+ requestId,
709
+ recoveredToken: true
710
+ };
711
+ }
712
+ return {
713
+ success: true,
714
+ toppedUpAmount: amount,
715
+ requestId
716
+ };
717
+ } catch (error) {
718
+ if (cashuToken) {
719
+ await this._recoverFailedTopUp(cashuToken);
720
+ }
721
+ return this._handleTopUpError(error, mintUrl, requestId);
722
+ }
723
+ }
724
+ async createProviderToken(options) {
725
+ const {
726
+ mintUrl,
727
+ baseUrl,
728
+ amount,
729
+ retryCount = 0,
730
+ excludeMints = [],
731
+ p2pkPubkey
732
+ } = options;
733
+ const adjustedAmount = Math.ceil(amount);
734
+ if (!adjustedAmount || isNaN(adjustedAmount)) {
735
+ return { success: false, error: "Invalid top up amount" };
736
+ }
737
+ const balances = await this.walletAdapter.getBalances();
738
+ const units = this.walletAdapter.getMintUnits();
739
+ let totalMintBalance = 0;
740
+ for (const url in balances) {
741
+ const unit = units[url];
742
+ const balanceInSats = getBalanceInSats(balances[url], unit);
743
+ totalMintBalance += balanceInSats;
744
+ }
745
+ const pendingDistribution = this.storageAdapter.getCachedTokenDistribution();
746
+ const refundablePending = pendingDistribution.filter((entry) => entry.baseUrl !== baseUrl).reduce((sum, entry) => sum + entry.amount, 0);
747
+ if (totalMintBalance < adjustedAmount && totalMintBalance + refundablePending >= adjustedAmount && retryCount < 1) {
748
+ await this._refundOtherProvidersForTopUp(baseUrl, mintUrl);
749
+ return this.createProviderToken({
750
+ ...options,
751
+ retryCount: retryCount + 1
752
+ });
753
+ }
754
+ const providerMints = baseUrl && this.providerRegistry ? this.providerRegistry.getProviderMints(baseUrl) : [];
755
+ let requiredAmount = adjustedAmount;
756
+ const supportedMintsOnly = providerMints.length > 0;
757
+ let candidates = this._selectCandidateMints({
758
+ balances,
759
+ units,
760
+ amount: requiredAmount,
761
+ preferredMintUrl: mintUrl,
762
+ excludeMints,
763
+ allowedMints: supportedMintsOnly ? providerMints : void 0
764
+ });
765
+ if (candidates.length === 0 && supportedMintsOnly) {
766
+ requiredAmount += 2;
767
+ candidates = this._selectCandidateMints({
768
+ balances,
769
+ units,
770
+ amount: requiredAmount,
771
+ preferredMintUrl: mintUrl,
772
+ excludeMints
773
+ });
774
+ }
775
+ if (candidates.length === 0) {
776
+ let maxBalance = 0;
777
+ let maxMintUrl = "";
778
+ for (const mintUrl2 in balances) {
779
+ const balance = balances[mintUrl2];
780
+ const unit = units[mintUrl2];
781
+ const balanceInSats = getBalanceInSats(balance, unit);
782
+ if (balanceInSats > maxBalance) {
783
+ maxBalance = balanceInSats;
784
+ maxMintUrl = mintUrl2;
785
+ }
786
+ }
787
+ const error = new InsufficientBalanceError(
788
+ adjustedAmount,
789
+ totalMintBalance,
790
+ maxBalance,
791
+ maxMintUrl
792
+ );
793
+ return { success: false, error: error.message };
794
+ }
795
+ let lastError;
796
+ for (const candidateMint of candidates) {
797
+ try {
798
+ const token = await this.walletAdapter.sendToken(
799
+ candidateMint,
800
+ requiredAmount,
801
+ p2pkPubkey
802
+ );
803
+ return {
804
+ success: true,
805
+ token,
806
+ selectedMintUrl: candidateMint,
807
+ amountSpent: requiredAmount
808
+ };
809
+ } catch (error) {
810
+ if (error instanceof Error) {
811
+ lastError = error.message;
812
+ if (isNetworkErrorMessage(error.message)) {
813
+ continue;
814
+ }
815
+ }
816
+ return {
817
+ success: false,
818
+ error: lastError || "Failed to create top up token"
819
+ };
820
+ }
821
+ }
822
+ return {
823
+ success: false,
824
+ error: lastError || "All candidate mints failed while creating top up token"
825
+ };
826
+ }
827
+ _selectCandidateMints(options) {
828
+ const {
829
+ balances,
830
+ units,
831
+ amount,
832
+ preferredMintUrl,
833
+ excludeMints,
834
+ allowedMints
835
+ } = options;
836
+ const candidates = [];
837
+ const { selectedMintUrl: firstMint } = selectMintWithBalance(
838
+ balances,
839
+ units,
840
+ amount,
841
+ excludeMints
842
+ );
843
+ if (firstMint && (!allowedMints || allowedMints.length === 0 || allowedMints.includes(firstMint))) {
844
+ candidates.push(firstMint);
845
+ }
846
+ const canUseMint = (mint) => {
847
+ if (excludeMints.includes(mint)) return false;
848
+ if (allowedMints && allowedMints.length > 0 && !allowedMints.includes(mint)) {
849
+ return false;
850
+ }
851
+ const rawBalance = balances[mint] || 0;
852
+ const unit = units[mint];
853
+ const balanceInSats = getBalanceInSats(rawBalance, unit);
854
+ return balanceInSats >= amount;
855
+ };
856
+ if (preferredMintUrl && canUseMint(preferredMintUrl) && !candidates.includes(preferredMintUrl)) {
857
+ candidates.push(preferredMintUrl);
858
+ }
859
+ for (const mint in balances) {
860
+ if (mint === preferredMintUrl || candidates.includes(mint)) continue;
861
+ if (canUseMint(mint)) {
862
+ candidates.push(mint);
863
+ }
864
+ }
865
+ return candidates;
866
+ }
867
+ async _refundOtherProvidersForTopUp(baseUrl, mintUrl) {
868
+ const pendingDistribution = this.storageAdapter.getCachedTokenDistribution();
869
+ const toRefund = pendingDistribution.filter(
870
+ (pending) => pending.baseUrl !== baseUrl
871
+ );
872
+ const refundResults = await Promise.allSettled(
873
+ toRefund.map(async (pending) => {
874
+ const token = this.storageAdapter.getToken(pending.baseUrl);
875
+ if (!token) {
876
+ return { baseUrl: pending.baseUrl, success: false };
877
+ }
878
+ const tokenBalance = await this.getTokenBalance(token, pending.baseUrl);
879
+ if (tokenBalance.reserved > 0) {
880
+ return { baseUrl: pending.baseUrl, success: false };
881
+ }
882
+ const result = await this.refund({
883
+ mintUrl,
884
+ baseUrl: pending.baseUrl,
885
+ token
886
+ });
887
+ return { baseUrl: pending.baseUrl, success: result.success };
888
+ })
889
+ );
890
+ for (const result of refundResults) {
891
+ if (result.status === "fulfilled" && result.value.success) {
892
+ this.storageAdapter.removeToken(result.value.baseUrl);
893
+ }
894
+ }
895
+ }
896
+ /**
897
+ * Fetch refund token from provider API
898
+ */
899
+ async _fetchRefundToken(baseUrl, storedToken) {
900
+ if (!baseUrl) {
901
+ return {
902
+ success: false,
903
+ error: "No base URL configured"
904
+ };
905
+ }
906
+ const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
907
+ const url = `${normalizedBaseUrl}v1/wallet/refund`;
908
+ const controller = new AbortController();
909
+ const timeoutId = setTimeout(() => {
910
+ controller.abort();
911
+ }, 6e4);
912
+ try {
913
+ const response = await fetch(url, {
914
+ method: "POST",
915
+ headers: {
916
+ Authorization: `Bearer ${storedToken}`,
917
+ "Content-Type": "application/json"
918
+ },
919
+ signal: controller.signal
920
+ });
921
+ clearTimeout(timeoutId);
922
+ const requestId = response.headers.get("x-routstr-request-id") || void 0;
923
+ if (!response.ok) {
924
+ const errorData = await response.json().catch(() => ({}));
925
+ if (response.status === 400 && errorData?.detail === "No balance to refund") {
926
+ this.storageAdapter.removeToken(baseUrl);
927
+ return {
928
+ success: false,
929
+ requestId,
930
+ error: "No balance to refund"
931
+ };
932
+ }
933
+ return {
934
+ success: false,
935
+ requestId,
936
+ error: `Refund request failed with status ${response.status}: ${errorData?.detail || response.statusText}`
937
+ };
938
+ }
939
+ const data = await response.json();
940
+ console.log("refund rsule", data);
941
+ return {
942
+ success: true,
943
+ token: data.token,
944
+ requestId
945
+ };
946
+ } catch (error) {
947
+ clearTimeout(timeoutId);
948
+ console.error("[BalanceManager._fetchRefundToken] Fetch error", error);
949
+ if (error instanceof Error) {
950
+ if (error.name === "AbortError") {
951
+ return {
952
+ success: false,
953
+ error: "Request timed out after 1 minute"
954
+ };
955
+ }
956
+ return {
957
+ success: false,
958
+ error: error.message
959
+ };
960
+ }
961
+ return {
962
+ success: false,
963
+ error: "Unknown error occurred during refund request"
964
+ };
965
+ }
966
+ }
967
+ /**
968
+ * Post topup request to provider API
969
+ */
970
+ async _postTopUp(baseUrl, storedToken, cashuToken) {
971
+ if (!baseUrl) {
972
+ return {
973
+ success: false,
974
+ error: "No base URL configured"
975
+ };
976
+ }
977
+ const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
978
+ const url = `${normalizedBaseUrl}v1/wallet/topup?cashu_token=${encodeURIComponent(
979
+ cashuToken
980
+ )}`;
981
+ const controller = new AbortController();
982
+ const timeoutId = setTimeout(() => {
983
+ controller.abort();
984
+ }, 6e4);
985
+ try {
986
+ const response = await fetch(url, {
987
+ method: "POST",
988
+ headers: {
989
+ Authorization: `Bearer ${storedToken}`,
990
+ "Content-Type": "application/json"
991
+ },
992
+ signal: controller.signal
993
+ });
994
+ clearTimeout(timeoutId);
995
+ const requestId = response.headers.get("x-routstr-request-id") || void 0;
996
+ if (!response.ok) {
997
+ const errorData = await response.json().catch(() => ({}));
998
+ return {
999
+ success: false,
1000
+ requestId,
1001
+ error: errorData?.detail || `Top up failed with status ${response.status}`
1002
+ };
1003
+ }
1004
+ return { success: true, requestId };
1005
+ } catch (error) {
1006
+ clearTimeout(timeoutId);
1007
+ console.error("[BalanceManager._postTopUp] Fetch error", error);
1008
+ if (error instanceof Error) {
1009
+ if (error.name === "AbortError") {
1010
+ return {
1011
+ success: false,
1012
+ error: "Request timed out after 1 minute"
1013
+ };
1014
+ }
1015
+ return {
1016
+ success: false,
1017
+ error: error.message
1018
+ };
1019
+ }
1020
+ return {
1021
+ success: false,
1022
+ error: "Unknown error occurred during top up request"
1023
+ };
1024
+ }
1025
+ }
1026
+ /**
1027
+ * Attempt to receive token back after failed top up
1028
+ */
1029
+ async _recoverFailedTopUp(cashuToken) {
1030
+ try {
1031
+ await this.walletAdapter.receiveToken(cashuToken);
1032
+ } catch (error) {
1033
+ console.error(
1034
+ "[BalanceManager._recoverFailedTopUp] Failed to recover token",
1035
+ error
1036
+ );
1037
+ }
1038
+ }
1039
+ /**
1040
+ * Handle refund errors with specific error types
1041
+ */
1042
+ _handleRefundError(error, mintUrl, requestId) {
1043
+ if (error instanceof Error) {
1044
+ if (isNetworkErrorMessage(error.message)) {
1045
+ return {
1046
+ success: false,
1047
+ message: `Failed to connect to the mint: ${mintUrl}`,
1048
+ requestId
1049
+ };
1050
+ }
1051
+ if (error.message.includes("Wallet not found")) {
1052
+ return {
1053
+ success: false,
1054
+ message: `Wallet couldn't be loaded. Please save this refunded cashu token manually.`,
1055
+ requestId
1056
+ };
1057
+ }
1058
+ return {
1059
+ success: false,
1060
+ message: error.message,
1061
+ requestId
1062
+ };
1063
+ }
1064
+ return {
1065
+ success: false,
1066
+ message: "Refund failed",
1067
+ requestId
1068
+ };
1069
+ }
1070
+ /**
1071
+ * Get token balance from provider
1072
+ */
1073
+ async getTokenBalance(token, baseUrl) {
1074
+ try {
1075
+ const response = await fetch(`${baseUrl}v1/wallet/info`, {
1076
+ headers: {
1077
+ Authorization: `Bearer ${token}`
1078
+ }
1079
+ });
1080
+ if (response.ok) {
1081
+ const data = await response.json();
1082
+ console.log("TOKENA FASJDFAS", data);
1083
+ return {
1084
+ amount: data.balance,
1085
+ reserved: data.reserved ?? 0,
1086
+ unit: "msat",
1087
+ apiKey: data.api_key
1088
+ };
1089
+ } else {
1090
+ console.log(response.status);
1091
+ const data = await response.json();
1092
+ console.log("FAILED ", data);
1093
+ }
1094
+ } catch (error) {
1095
+ console.error("ERRORR IN RESTPONSE", error);
1096
+ }
1097
+ return { amount: -1, reserved: 0, unit: "sat", apiKey: "" };
1098
+ }
1099
+ /**
1100
+ * Handle topup errors with specific error types
1101
+ */
1102
+ _handleTopUpError(error, mintUrl, requestId) {
1103
+ if (error instanceof Error) {
1104
+ if (isNetworkErrorMessage(error.message)) {
1105
+ return {
1106
+ success: false,
1107
+ message: `Failed to connect to the mint: ${mintUrl}`,
1108
+ requestId
1109
+ };
1110
+ }
1111
+ if (error.message.includes("Wallet not found")) {
1112
+ return {
1113
+ success: false,
1114
+ message: "Wallet couldn't be loaded. The cashu token was recovered locally.",
1115
+ requestId
1116
+ };
1117
+ }
1118
+ return {
1119
+ success: false,
1120
+ message: error.message,
1121
+ requestId
1122
+ };
1123
+ }
1124
+ return {
1125
+ success: false,
1126
+ message: "Top up failed",
1127
+ requestId
1128
+ };
1129
+ }
1130
+ };
1131
+
1132
+ export { BalanceManager, CashuSpender };
1133
+ //# sourceMappingURL=index.mjs.map
1134
+ //# sourceMappingURL=index.mjs.map