@routstr/sdk 0.3.3 → 0.3.5

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 (39) hide show
  1. package/dist/client/index.d.mts +9 -5
  2. package/dist/client/index.d.ts +9 -5
  3. package/dist/client/index.js +107 -136
  4. package/dist/client/index.js.map +1 -1
  5. package/dist/client/index.mjs +107 -136
  6. package/dist/client/index.mjs.map +1 -1
  7. package/dist/discovery/index.d.mts +8 -2
  8. package/dist/discovery/index.d.ts +8 -2
  9. package/dist/discovery/index.js +27 -16
  10. package/dist/discovery/index.js.map +1 -1
  11. package/dist/discovery/index.mjs +27 -16
  12. package/dist/discovery/index.mjs.map +1 -1
  13. package/dist/index.d.mts +10 -8
  14. package/dist/index.d.ts +10 -8
  15. package/dist/index.js +179 -193
  16. package/dist/index.js.map +1 -1
  17. package/dist/index.mjs +178 -194
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/{interfaces-C5fLD3jB.d.mts → interfaces-Bp0Ngmqv.d.mts} +1 -1
  20. package/dist/{interfaces-BxDEka72.d.ts → interfaces-CIfd_phZ.d.ts} +1 -1
  21. package/dist/{interfaces-BWJJTCXO.d.mts → interfaces-Cxi8R4TT.d.mts} +1 -1
  22. package/dist/{interfaces-B62Rw-dd.d.ts → interfaces-D2FDCLyP.d.ts} +1 -1
  23. package/dist/storage/index.d.mts +9 -7
  24. package/dist/storage/index.d.ts +9 -7
  25. package/dist/storage/index.js +52 -37
  26. package/dist/storage/index.js.map +1 -1
  27. package/dist/storage/index.mjs +52 -37
  28. package/dist/storage/index.mjs.map +1 -1
  29. package/dist/{store-h7m23ffq.d.ts → store-BD5zF9Hp.d.ts} +4 -4
  30. package/dist/{store-DGeLPv9E.d.mts → store-CBSyK2qg.d.mts} +4 -4
  31. package/dist/{types-BYj_8c5c.d.mts → types-DPQM6tIG.d.mts} +10 -1
  32. package/dist/{types-BYj_8c5c.d.ts → types-DPQM6tIG.d.ts} +10 -1
  33. package/dist/wallet/index.d.mts +8 -6
  34. package/dist/wallet/index.d.ts +8 -6
  35. package/dist/wallet/index.js +80 -57
  36. package/dist/wallet/index.js.map +1 -1
  37. package/dist/wallet/index.mjs +80 -57
  38. package/dist/wallet/index.mjs.map +1 -1
  39. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import { StoreApi } from 'zustand/vanilla';
2
- import { D as DiscoveryAdapter } from './interfaces-BxDEka72.js';
3
- import { P as ProviderRegistry, S as StorageAdapter } from './interfaces-B62Rw-dd.js';
4
- import { M as Model, P as ProviderInfo } from './types-BYj_8c5c.js';
2
+ import { D as DiscoveryAdapter } from './interfaces-CIfd_phZ.js';
3
+ import { P as ProviderRegistry, S as StorageAdapter } from './interfaces-D2FDCLyP.js';
4
+ import { M as Model, P as ProviderInfo, S as SdkLogger } from './types-DPQM6tIG.js';
5
5
 
6
6
  interface UsageTrackingEntry {
7
7
  id: string;
@@ -167,6 +167,6 @@ declare const createSdkStore: ({ driver, }: SdkStoreOptions) => {
167
167
  };
168
168
  declare const createDiscoveryAdapterFromStore: (store: SdkStore) => DiscoveryAdapter;
169
169
  declare const createStorageAdapterFromStore: (store: SdkStore) => StorageAdapter;
170
- declare const createProviderRegistryFromStore: (store: SdkStore) => ProviderRegistry;
170
+ declare const createProviderRegistryFromStore: (store: SdkStore, logger?: SdkLogger) => ProviderRegistry;
171
171
 
172
172
  export { type ListUsageTrackingOptions as L, type SdkStore as S, type UsageTrackingDriver as U, type StorageDriver as a, type UsageTrackingEntry as b, createDiscoveryAdapterFromStore as c, createProviderRegistryFromStore as d, createSdkStore as e, createStorageAdapterFromStore as f };
@@ -1,7 +1,7 @@
1
1
  import { StoreApi } from 'zustand/vanilla';
2
- import { D as DiscoveryAdapter } from './interfaces-BWJJTCXO.mjs';
3
- import { P as ProviderRegistry, S as StorageAdapter } from './interfaces-C5fLD3jB.mjs';
4
- import { M as Model, P as ProviderInfo } from './types-BYj_8c5c.mjs';
2
+ import { D as DiscoveryAdapter } from './interfaces-Cxi8R4TT.mjs';
3
+ import { P as ProviderRegistry, S as StorageAdapter } from './interfaces-Bp0Ngmqv.mjs';
4
+ import { M as Model, P as ProviderInfo, S as SdkLogger } from './types-DPQM6tIG.mjs';
5
5
 
6
6
  interface UsageTrackingEntry {
7
7
  id: string;
@@ -167,6 +167,6 @@ declare const createSdkStore: ({ driver, }: SdkStoreOptions) => {
167
167
  };
168
168
  declare const createDiscoveryAdapterFromStore: (store: SdkStore) => DiscoveryAdapter;
169
169
  declare const createStorageAdapterFromStore: (store: SdkStore) => StorageAdapter;
170
- declare const createProviderRegistryFromStore: (store: SdkStore) => ProviderRegistry;
170
+ declare const createProviderRegistryFromStore: (store: SdkStore, logger?: SdkLogger) => ProviderRegistry;
171
171
 
172
172
  export { type ListUsageTrackingOptions as L, type SdkStore as S, type UsageTrackingDriver as U, type StorageDriver as a, type UsageTrackingEntry as b, createDiscoveryAdapterFromStore as c, createProviderRegistryFromStore as d, createSdkStore as e, createStorageAdapterFromStore as f };
@@ -2,6 +2,15 @@
2
2
  * Core types for the Routstr SDK
3
3
  * These types are shared across wallet and client modules
4
4
  */
5
+ interface SdkLogger {
6
+ log(...args: unknown[]): void;
7
+ warn(...args: unknown[]): void;
8
+ error(...args: unknown[]): void;
9
+ debug(...args: unknown[]): void;
10
+ child(prefix: string): SdkLogger;
11
+ }
12
+ declare const consoleLogger: SdkLogger;
13
+ declare const noopLogger: SdkLogger;
5
14
  interface MessageContentType {
6
15
  type: "text" | "image_url" | "file";
7
16
  text?: string;
@@ -222,4 +231,4 @@ interface MintDiscoveryResult {
222
231
  infoFromProviders: Record<string, ProviderInfo>;
223
232
  }
224
233
 
225
- export type { APIErrorVerdict as A, CandidateProvider as C, FetchAIResponseParams as F, ImageData as I, Model as M, ProviderInfo as P, RefundResult as R, SpendResult as S, TransactionHistory as T, UsageStats as U, Message as a, AnnotationData as b, MessageContentType as c, MintDiscoveryResult as d, MintSelection as e, ModelArchitecture as f, ModelDiscoveryResult as g, ModelPricing as h, ModelSatsPricing as i, PendingTokenEntry as j, PerRequestLimits as k, StreamingResult as l, TopUpResult as m };
234
+ export { type APIErrorVerdict as A, type CandidateProvider as C, type FetchAIResponseParams as F, type ImageData as I, type Model as M, type ProviderInfo as P, type RefundResult as R, type SdkLogger as S, type TransactionHistory as T, type UsageStats as U, type Message as a, type AnnotationData as b, type MessageContentType as c, type MintDiscoveryResult as d, type MintSelection as e, type ModelArchitecture as f, type ModelDiscoveryResult as g, type ModelPricing as h, type ModelSatsPricing as i, type PendingTokenEntry as j, type PerRequestLimits as k, type SpendResult as l, type StreamingResult as m, type TopUpResult as n, consoleLogger as o, noopLogger as p };
@@ -2,6 +2,15 @@
2
2
  * Core types for the Routstr SDK
3
3
  * These types are shared across wallet and client modules
4
4
  */
5
+ interface SdkLogger {
6
+ log(...args: unknown[]): void;
7
+ warn(...args: unknown[]): void;
8
+ error(...args: unknown[]): void;
9
+ debug(...args: unknown[]): void;
10
+ child(prefix: string): SdkLogger;
11
+ }
12
+ declare const consoleLogger: SdkLogger;
13
+ declare const noopLogger: SdkLogger;
5
14
  interface MessageContentType {
6
15
  type: "text" | "image_url" | "file";
7
16
  text?: string;
@@ -222,4 +231,4 @@ interface MintDiscoveryResult {
222
231
  infoFromProviders: Record<string, ProviderInfo>;
223
232
  }
224
233
 
225
- export type { APIErrorVerdict as A, CandidateProvider as C, FetchAIResponseParams as F, ImageData as I, Model as M, ProviderInfo as P, RefundResult as R, SpendResult as S, TransactionHistory as T, UsageStats as U, Message as a, AnnotationData as b, MessageContentType as c, MintDiscoveryResult as d, MintSelection as e, ModelArchitecture as f, ModelDiscoveryResult as g, ModelPricing as h, ModelSatsPricing as i, PendingTokenEntry as j, PerRequestLimits as k, StreamingResult as l, TopUpResult as m };
234
+ export { type APIErrorVerdict as A, type CandidateProvider as C, type FetchAIResponseParams as F, type ImageData as I, type Model as M, type ProviderInfo as P, type RefundResult as R, type SdkLogger as S, type TransactionHistory as T, type UsageStats as U, type Message as a, type AnnotationData as b, type MessageContentType as c, type MintDiscoveryResult as d, type MintSelection as e, type ModelArchitecture as f, type ModelDiscoveryResult as g, type ModelPricing as h, type ModelSatsPricing as i, type PendingTokenEntry as j, type PerRequestLimits as k, type SpendResult as l, type StreamingResult as m, type TopUpResult as n, consoleLogger as o, noopLogger as p };
@@ -1,7 +1,7 @@
1
- import { W as WalletAdapter, S as StorageAdapter, P as ProviderRegistry } from '../interfaces-C5fLD3jB.mjs';
2
- export { A as ApiKeyEntry, C as ChildKeyEntry, R as RoutstrClientOptions, a as StreamingCallbacks, X as XCashuTokenEntry } from '../interfaces-C5fLD3jB.mjs';
3
- import { R as RefundResult, m as TopUpResult, S as SpendResult } from '../types-BYj_8c5c.mjs';
4
- export { P as ProviderInfo } from '../types-BYj_8c5c.mjs';
1
+ import { W as WalletAdapter, S as StorageAdapter, P as ProviderRegistry } from '../interfaces-Bp0Ngmqv.mjs';
2
+ export { A as ApiKeyEntry, C as ChildKeyEntry, R as RoutstrClientOptions, a as StreamingCallbacks, X as XCashuTokenEntry } from '../interfaces-Bp0Ngmqv.mjs';
3
+ import { S as SdkLogger, R as RefundResult, n as TopUpResult, l as SpendResult } from '../types-DPQM6tIG.mjs';
4
+ export { P as ProviderInfo } from '../types-DPQM6tIG.mjs';
5
5
 
6
6
  /**
7
7
  * BalanceManager - Handles refunding and topping up tokens from providers
@@ -73,7 +73,8 @@ declare class BalanceManager {
73
73
  private providerWalletOps;
74
74
  /** Cooldown (ms) between opposite operations on the same provider */
75
75
  private static readonly PROVIDER_WALLET_COOLDOWN_MS;
76
- constructor(walletAdapter: WalletAdapter, storageAdapter: StorageAdapter, providerRegistry?: ProviderRegistry | undefined, cashuSpender?: CashuSpender);
76
+ private readonly logger;
77
+ constructor(walletAdapter: WalletAdapter, storageAdapter: StorageAdapter, providerRegistry?: ProviderRegistry | undefined, cashuSpender?: CashuSpender, logger?: SdkLogger);
77
78
  /**
78
79
  * Check whether a wallet operation (topup/refund) may run for a provider.
79
80
  * Returns the reason when blocked.
@@ -178,7 +179,8 @@ declare class CashuSpender {
178
179
  private balanceManager?;
179
180
  private _isBusy;
180
181
  private debugLevel;
181
- constructor(walletAdapter: WalletAdapter, storageAdapter: StorageAdapter, _providerRegistry?: unknown | undefined, balanceManager?: BalanceManager | undefined);
182
+ private readonly logger;
183
+ constructor(walletAdapter: WalletAdapter, storageAdapter: StorageAdapter, _providerRegistry?: unknown | undefined, balanceManager?: BalanceManager | undefined, logger?: SdkLogger);
182
184
  receiveToken(token: string): Promise<{
183
185
  success: boolean;
184
186
  amount: number;
@@ -1,7 +1,7 @@
1
- import { W as WalletAdapter, S as StorageAdapter, P as ProviderRegistry } from '../interfaces-B62Rw-dd.js';
2
- export { A as ApiKeyEntry, C as ChildKeyEntry, R as RoutstrClientOptions, a as StreamingCallbacks, X as XCashuTokenEntry } from '../interfaces-B62Rw-dd.js';
3
- import { R as RefundResult, m as TopUpResult, S as SpendResult } from '../types-BYj_8c5c.js';
4
- export { P as ProviderInfo } from '../types-BYj_8c5c.js';
1
+ import { W as WalletAdapter, S as StorageAdapter, P as ProviderRegistry } from '../interfaces-D2FDCLyP.js';
2
+ export { A as ApiKeyEntry, C as ChildKeyEntry, R as RoutstrClientOptions, a as StreamingCallbacks, X as XCashuTokenEntry } from '../interfaces-D2FDCLyP.js';
3
+ import { S as SdkLogger, R as RefundResult, n as TopUpResult, l as SpendResult } from '../types-DPQM6tIG.js';
4
+ export { P as ProviderInfo } from '../types-DPQM6tIG.js';
5
5
 
6
6
  /**
7
7
  * BalanceManager - Handles refunding and topping up tokens from providers
@@ -73,7 +73,8 @@ declare class BalanceManager {
73
73
  private providerWalletOps;
74
74
  /** Cooldown (ms) between opposite operations on the same provider */
75
75
  private static readonly PROVIDER_WALLET_COOLDOWN_MS;
76
- constructor(walletAdapter: WalletAdapter, storageAdapter: StorageAdapter, providerRegistry?: ProviderRegistry | undefined, cashuSpender?: CashuSpender);
76
+ private readonly logger;
77
+ constructor(walletAdapter: WalletAdapter, storageAdapter: StorageAdapter, providerRegistry?: ProviderRegistry | undefined, cashuSpender?: CashuSpender, logger?: SdkLogger);
77
78
  /**
78
79
  * Check whether a wallet operation (topup/refund) may run for a provider.
79
80
  * Returns the reason when blocked.
@@ -178,7 +179,8 @@ declare class CashuSpender {
178
179
  private balanceManager?;
179
180
  private _isBusy;
180
181
  private debugLevel;
181
- constructor(walletAdapter: WalletAdapter, storageAdapter: StorageAdapter, _providerRegistry?: unknown | undefined, balanceManager?: BalanceManager | undefined);
182
+ private readonly logger;
183
+ constructor(walletAdapter: WalletAdapter, storageAdapter: StorageAdapter, _providerRegistry?: unknown | undefined, balanceManager?: BalanceManager | undefined, logger?: SdkLogger);
182
184
  receiveToken(token: string): Promise<{
183
185
  success: boolean;
184
186
  amount: number;
@@ -2,6 +2,19 @@
2
2
 
3
3
  var cashuTs = require('@cashu/cashu-ts');
4
4
 
5
+ // core/types.ts
6
+ function makeConsoleLogger(prefix) {
7
+ const fmt = (args) => prefix ? [prefix, ...args] : args;
8
+ return {
9
+ log: (...args) => console.log(...fmt(args)),
10
+ warn: (...args) => console.warn(...fmt(args)),
11
+ error: (...args) => console.error(...fmt(args)),
12
+ debug: (...args) => console.log(...fmt(args)),
13
+ child: (p) => makeConsoleLogger(prefix ? `${prefix}:${p}` : p)
14
+ };
15
+ }
16
+ var consoleLogger = makeConsoleLogger();
17
+
5
18
  // core/errors.ts
6
19
  var InsufficientBalanceError = class extends Error {
7
20
  constructor(required, available, maxMintBalance = 0, maxMintUrl = "", customMessage) {
@@ -80,14 +93,16 @@ function selectMintWithBalance(balances, units, amount, excludeMints = []) {
80
93
  return { selectedMintUrl: null, selectedMintBalance: 0 };
81
94
  }
82
95
  var CashuSpender = class {
83
- constructor(walletAdapter, storageAdapter, _providerRegistry, balanceManager) {
96
+ constructor(walletAdapter, storageAdapter, _providerRegistry, balanceManager, logger) {
84
97
  this.walletAdapter = walletAdapter;
85
98
  this.storageAdapter = storageAdapter;
86
99
  this._providerRegistry = _providerRegistry;
87
100
  this.balanceManager = balanceManager;
101
+ this.logger = (logger ?? consoleLogger).child("CashuSpender");
88
102
  }
89
103
  _isBusy = false;
90
104
  debugLevel = "WARN";
105
+ logger;
91
106
  async receiveToken(token) {
92
107
  try {
93
108
  const result = await this.walletAdapter.receiveToken(token);
@@ -183,13 +198,13 @@ var CashuSpender = class {
183
198
  if (levelPriority[level] >= levelPriority[this.debugLevel]) {
184
199
  switch (level) {
185
200
  case "DEBUG":
186
- console.log(...args);
201
+ this.logger.log(...args);
187
202
  break;
188
203
  case "WARN":
189
- console.warn(...args);
204
+ this.logger.warn(...args);
190
205
  break;
191
206
  case "ERROR":
192
- console.error(...args);
207
+ this.logger.error(...args);
193
208
  break;
194
209
  }
195
210
  }
@@ -537,19 +552,50 @@ var CashuSpender = class {
537
552
  apiKeyEntry.baseUrl
538
553
  );
539
554
  if (apiKeyEntryFull && this.balanceManager) {
555
+ try {
556
+ const balanceResult = await this.balanceManager.getTokenBalance(
557
+ apiKeyEntryFull.key,
558
+ apiKeyEntry.baseUrl
559
+ );
560
+ if (balanceResult.isInvalidApiKey) {
561
+ this.storageAdapter.removeApiKey(apiKeyEntry.baseUrl);
562
+ results.push({
563
+ baseUrl: apiKeyEntry.baseUrl,
564
+ success: true
565
+ });
566
+ continue;
567
+ }
568
+ if (balanceResult.amount >= 0) {
569
+ const balanceSat = balanceResult.unit === "msat" ? Math.floor(balanceResult.amount / 1e3) : balanceResult.amount;
570
+ this.storageAdapter.updateApiKeyBalance(
571
+ apiKeyEntry.baseUrl,
572
+ balanceSat
573
+ );
574
+ }
575
+ } catch {
576
+ }
577
+ const refreshedEntry = this.storageAdapter.getApiKey(
578
+ apiKeyEntry.baseUrl
579
+ );
580
+ if (!refreshedEntry) continue;
540
581
  const refundResult = await this.balanceManager.refundApiKey({
541
582
  mintUrl,
542
583
  baseUrl: apiKeyEntry.baseUrl,
543
- apiKey: apiKeyEntryFull.key,
584
+ apiKey: refreshedEntry.key,
544
585
  forceRefund
545
586
  });
546
587
  if (refundResult.success) {
547
588
  this.storageAdapter.removeApiKey(apiKeyEntry.baseUrl);
548
589
  } else {
549
- this.storageAdapter.updateApiKeyBalance(
550
- apiKeyEntry.baseUrl,
551
- apiKeyEntry.amount
590
+ const currentEntry = this.storageAdapter.getApiKey(
591
+ apiKeyEntry.baseUrl
552
592
  );
593
+ if (currentEntry) {
594
+ this.storageAdapter.updateApiKeyBalance(
595
+ apiKeyEntry.baseUrl,
596
+ currentEntry.balance
597
+ );
598
+ }
553
599
  }
554
600
  results.push({
555
601
  baseUrl: apiKeyEntry.baseUrl,
@@ -616,10 +662,11 @@ var CashuSpender = class {
616
662
 
617
663
  // wallet/BalanceManager.ts
618
664
  var BalanceManager = class _BalanceManager {
619
- constructor(walletAdapter, storageAdapter, providerRegistry, cashuSpender) {
665
+ constructor(walletAdapter, storageAdapter, providerRegistry, cashuSpender, logger) {
620
666
  this.walletAdapter = walletAdapter;
621
667
  this.storageAdapter = storageAdapter;
622
668
  this.providerRegistry = providerRegistry;
669
+ this.logger = (logger ?? consoleLogger).child("BalanceManager");
623
670
  if (cashuSpender) {
624
671
  this.cashuSpender = cashuSpender;
625
672
  } else {
@@ -636,6 +683,7 @@ var BalanceManager = class _BalanceManager {
636
683
  providerWalletOps = /* @__PURE__ */ new Map();
637
684
  /** Cooldown (ms) between opposite operations on the same provider */
638
685
  static PROVIDER_WALLET_COOLDOWN_MS = 1e4;
686
+ logger;
639
687
  /**
640
688
  * Check whether a wallet operation (topup/refund) may run for a provider.
641
689
  * Returns the reason when blocked.
@@ -710,7 +758,7 @@ var BalanceManager = class _BalanceManager {
710
758
  const { mintUrl, baseUrl, apiKey, forceRefund } = options;
711
759
  const guard = this._canRunProviderWalletOperation(baseUrl, "refund");
712
760
  if (!guard.allowed) {
713
- console.log(`[BalanceManager] Skipping refund for ${baseUrl} - ${guard.reason}`);
761
+ this.logger.log(`Skipping refund for ${baseUrl} - ${guard.reason}`);
714
762
  return { success: false, message: guard.reason };
715
763
  }
716
764
  this._beginProviderWalletOperation(baseUrl, "refund");
@@ -730,9 +778,7 @@ var BalanceManager = class _BalanceManager {
730
778
  if (apiKeyEntry?.lastUsed) {
731
779
  const fiveMinutesAgo = Date.now() - 5 * 60 * 1e3;
732
780
  if (apiKeyEntry.lastUsed > fiveMinutesAgo) {
733
- console.log(
734
- `[BalanceManager] Skipping refund for ${baseUrl} - used ${Math.round((Date.now() - apiKeyEntry.lastUsed) / 1e3)}s ago`
735
- );
781
+ this.logger.log(`Skipping refund for ${baseUrl} - used ${Math.round((Date.now() - apiKeyEntry.lastUsed) / 1e3)}s ago`);
736
782
  return {
737
783
  success: false,
738
784
  message: "API key was used recently, skipping refund"
@@ -758,7 +804,8 @@ var BalanceManager = class _BalanceManager {
758
804
  };
759
805
  }
760
806
  if (fetchResult.error === "No balance to refund") {
761
- return { success: false, message: "No balance to refund" };
807
+ this.storageAdapter.removeApiKey(baseUrl);
808
+ return { success: true, message: "No balance to refund, key cleaned up" };
762
809
  }
763
810
  const receiveResult = await this.cashuSpender.receiveToken(
764
811
  fetchResult.token
@@ -774,7 +821,7 @@ var BalanceManager = class _BalanceManager {
774
821
  requestId: fetchResult.requestId
775
822
  };
776
823
  } catch (error) {
777
- console.error("[BalanceManager] API key refund error", error);
824
+ this.logger.error("API key refund error", error);
778
825
  return this._handleRefundError(error, mintUrl, fetchResult?.requestId);
779
826
  }
780
827
  }
@@ -826,7 +873,7 @@ var BalanceManager = class _BalanceManager {
826
873
  };
827
874
  } catch (error) {
828
875
  clearTimeout(timeoutId);
829
- console.error("[BalanceManager.fetchRefundToken] Fetch error", error);
876
+ this.logger.error("fetchRefundToken fetch error", error);
830
877
  if (error instanceof Error) {
831
878
  if (error.name === "AbortError") {
832
879
  return {
@@ -852,7 +899,7 @@ var BalanceManager = class _BalanceManager {
852
899
  const { mintUrl, baseUrl, amount, token: providedToken } = options;
853
900
  const guard = this._canRunProviderWalletOperation(baseUrl, "topup");
854
901
  if (!guard.allowed) {
855
- console.log(`[BalanceManager] Skipping topup for ${baseUrl} - ${guard.reason}`);
902
+ this.logger.log(`Skipping topup for ${baseUrl} - ${guard.reason}`);
856
903
  return { success: false, message: guard.reason };
857
904
  }
858
905
  this._beginProviderWalletOperation(baseUrl, "topup");
@@ -889,7 +936,7 @@ var BalanceManager = class _BalanceManager {
889
936
  cashuToken = tokenResult.token;
890
937
  const topUpResult = await this._postTopUp(baseUrl, apiKey, cashuToken);
891
938
  requestId = topUpResult.requestId;
892
- console.log(topUpResult);
939
+ this.logger.log("topUpResult:", topUpResult);
893
940
  if (!topUpResult.success) {
894
941
  await this._recoverFailedTopUp(cashuToken);
895
942
  return {
@@ -905,10 +952,7 @@ var BalanceManager = class _BalanceManager {
905
952
  requestId
906
953
  };
907
954
  } catch (error) {
908
- console.log(
909
- "DEBUG",
910
- `[TopuPU] topup: Topup result for ${baseUrl}: error=${error}`
911
- );
955
+ this.logger.log(`topup error for ${baseUrl}: ${error}`);
912
956
  if (cashuToken) {
913
957
  await this._recoverFailedTopUp(cashuToken);
914
958
  }
@@ -925,13 +969,9 @@ var BalanceManager = class _BalanceManager {
925
969
  p2pkPubkey
926
970
  } = options;
927
971
  const adjustedAmount = Math.ceil(amount);
928
- console.log(
929
- `[BalanceManager.createProviderToken] Starting: baseUrl=${baseUrl}, mintUrl=${mintUrl}, amount=${amount}, adjustedAmount=${adjustedAmount}, retryCount=${retryCount}`
930
- );
972
+ this.logger.log(`createProviderToken: baseUrl=${baseUrl} mintUrl=${mintUrl} amount=${amount} adjustedAmount=${adjustedAmount} retryCount=${retryCount}`);
931
973
  if (!adjustedAmount || isNaN(adjustedAmount)) {
932
- console.error(
933
- `[BalanceManager.createProviderToken] FAILURE: Invalid amount - amount=${amount}, adjustedAmount=${adjustedAmount}`
934
- );
974
+ this.logger.error(`createProviderToken: invalid amount=${amount}`);
935
975
  return { success: false, error: "Invalid top up amount" };
936
976
  }
937
977
  const balanceState = await this.getBalanceState();
@@ -962,9 +1002,7 @@ var BalanceManager = class _BalanceManager {
962
1002
  { url: "", balance: 0 }
963
1003
  ).url
964
1004
  );
965
- console.error(
966
- `[BalanceManager.createProviderToken] FAILURE: Insufficient balance - required=${adjustedAmount}, available=${totalMintBalance + targetProviderBalance}, totalMintBalance=${totalMintBalance}, targetProviderBalance=${targetProviderBalance}, refundableProviderBalance=${refundableProviderBalance}`
967
- );
1005
+ this.logger.error(`createProviderToken: insufficient balance required=${adjustedAmount} available=${totalMintBalance + targetProviderBalance} totalMint=${totalMintBalance} targetProvider=${targetProviderBalance}`);
968
1006
  return { success: false, error: error.message };
969
1007
  }
970
1008
  const providerMints = baseUrl && this.providerRegistry ? this.providerRegistry.getProviderMints(baseUrl) : [];
@@ -1000,9 +1038,7 @@ var BalanceManager = class _BalanceManager {
1000
1038
  maxMintUrl = mintUrl2;
1001
1039
  }
1002
1040
  }
1003
- console.error(
1004
- `[BalanceManager.createProviderToken] FAILURE: No candidate mints found - requiredAmount=${requiredAmount}, totalMintBalance=${totalMintBalance}, maxBalance=${maxBalance}, maxMintUrl=${maxMintUrl}, providerMints=${JSON.stringify(providerMints)}`
1005
- );
1041
+ this.logger.error(`createProviderToken: no candidate mints required=${requiredAmount} totalMint=${totalMintBalance} maxBalance=${maxBalance} maxMint=${maxMintUrl}`);
1006
1042
  const error = new InsufficientBalanceError(
1007
1043
  adjustedAmount,
1008
1044
  totalMintBalance,
@@ -1014,17 +1050,13 @@ var BalanceManager = class _BalanceManager {
1014
1050
  let lastError;
1015
1051
  for (const candidateMint of candidates) {
1016
1052
  try {
1017
- console.log(
1018
- `[BalanceManager.createProviderToken] Attempting mint: ${candidateMint}, amount: ${requiredAmount}`
1019
- );
1053
+ this.logger.log(`createProviderToken: attempting mint=${candidateMint} amount=${requiredAmount}`);
1020
1054
  const token = await this.walletAdapter.sendToken(
1021
1055
  candidateMint,
1022
1056
  requiredAmount,
1023
1057
  p2pkPubkey
1024
1058
  );
1025
- console.log(
1026
- `[BalanceManager.createProviderToken] SUCCESS: Token created from mint ${candidateMint}, all mint balances: ${JSON.stringify(Object.fromEntries(Object.entries(balances).map(([mint, balance]) => [mint, getBalanceInSats(balance, units[mint])])))}`
1027
- );
1059
+ this.logger.log(`createProviderToken: success from mint=${candidateMint}`);
1028
1060
  return {
1029
1061
  success: true,
1030
1062
  token,
@@ -1033,15 +1065,11 @@ var BalanceManager = class _BalanceManager {
1033
1065
  };
1034
1066
  } catch (error) {
1035
1067
  const errorMsg = error instanceof Error ? error.message : String(error);
1036
- console.error(
1037
- `[BalanceManager.createProviderToken] FAILURE: Mint ${candidateMint} failed with error: ${errorMsg}`
1038
- );
1068
+ this.logger.error(`createProviderToken: mint=${candidateMint} failed: ${errorMsg}`);
1039
1069
  if (error instanceof Error) {
1040
1070
  lastError = errorMsg;
1041
1071
  if (isNetworkErrorMessage(error.message)) {
1042
- console.warn(
1043
- `[BalanceManager.createProviderToken] Network error from ${candidateMint}, trying next mint...`
1044
- );
1072
+ this.logger.warn(`createProviderToken: network error from ${candidateMint}, trying next mint...`);
1045
1073
  continue;
1046
1074
  }
1047
1075
  }
@@ -1051,9 +1079,7 @@ var BalanceManager = class _BalanceManager {
1051
1079
  };
1052
1080
  }
1053
1081
  }
1054
- console.error(
1055
- `[BalanceManager.createProviderToken] FAILURE: All candidate mints exhausted - lastError=${lastError}, candidates=${JSON.stringify(candidates)}`
1056
- );
1082
+ this.logger.error(`createProviderToken: all candidate mints exhausted lastError=${lastError}`);
1057
1083
  return {
1058
1084
  success: false,
1059
1085
  error: lastError || "All candidate mints failed while creating top up token"
@@ -1168,7 +1194,7 @@ var BalanceManager = class _BalanceManager {
1168
1194
  return { success: true, requestId };
1169
1195
  } catch (error) {
1170
1196
  clearTimeout(timeoutId);
1171
- console.error("[BalanceManager._postTopUp] Fetch error", error);
1197
+ this.logger.error("_postTopUp fetch error", error);
1172
1198
  if (error instanceof Error) {
1173
1199
  if (error.name === "AbortError") {
1174
1200
  return {
@@ -1194,10 +1220,7 @@ var BalanceManager = class _BalanceManager {
1194
1220
  try {
1195
1221
  await this.cashuSpender.receiveToken(cashuToken);
1196
1222
  } catch (error) {
1197
- console.error(
1198
- "[BalanceManager._recoverFailedTopUp] Failed to recover token",
1199
- error
1200
- );
1223
+ this.logger.error("_recoverFailedTopUp: failed to recover token", error);
1201
1224
  }
1202
1225
  }
1203
1226
  /**
@@ -1250,9 +1273,9 @@ var BalanceManager = class _BalanceManager {
1250
1273
  apiKey: data.api_key
1251
1274
  };
1252
1275
  } else {
1253
- console.log(response.status);
1276
+ this.logger.warn(`getTokenBalance: status=${response.status}`);
1254
1277
  const data = await response.json();
1255
- console.log("FAILED ", data);
1278
+ this.logger.warn("getTokenBalance: FAILED", data);
1256
1279
  const isInvalidApiKey = response.status === 401 && data?.detail?.error?.code === "invalid_api_key" && data?.detail?.error?.message?.includes("proofs already spent");
1257
1280
  return {
1258
1281
  amount: -1,
@@ -1263,7 +1286,7 @@ var BalanceManager = class _BalanceManager {
1263
1286
  };
1264
1287
  }
1265
1288
  } catch (error) {
1266
- console.error("ERRORR IN RESTPONSE", error);
1289
+ this.logger.error("getTokenBalance error", error);
1267
1290
  }
1268
1291
  return { amount: -1, reserved: 0, unit: "sat", apiKey: "" };
1269
1292
  }