@routstr/sdk 0.1.0 → 0.1.2

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