@mixrpay/agent-sdk 0.4.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,1431 @@
1
+ /**
2
+ * MixrPay Agent SDK - Type definitions
3
+ *
4
+ * This file contains all TypeScript types and interfaces used throughout the SDK.
5
+ */
6
+ /**
7
+ * Configuration options for AgentWallet.
8
+ *
9
+ * @example Minimal configuration
10
+ * ```typescript
11
+ * const config: AgentWalletConfig = {
12
+ * sessionKey: 'sk_live_abc123...'
13
+ * };
14
+ * ```
15
+ *
16
+ * @example Full configuration
17
+ * ```typescript
18
+ * const config: AgentWalletConfig = {
19
+ * sessionKey: 'sk_live_abc123...',
20
+ * maxPaymentUsd: 5.0,
21
+ * onPayment: (p) => console.log(`Paid $${p.amountUsd}`),
22
+ * logLevel: 'info',
23
+ * timeout: 60000,
24
+ * };
25
+ * ```
26
+ */
27
+ interface AgentWalletConfig {
28
+ /**
29
+ * Session key granted by the wallet owner.
30
+ *
31
+ * Format: `sk_live_` (mainnet) or `sk_test_` (testnet) followed by 64 hex characters.
32
+ *
33
+ * Get session keys from:
34
+ * - The wallet owner's MixrPay dashboard
35
+ * - Programmatically via the MixrPay API
36
+ * - The MixrPay widget session key management
37
+ *
38
+ * @example 'sk_live_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'
39
+ */
40
+ sessionKey: string;
41
+ /**
42
+ * Optional smart wallet address.
43
+ *
44
+ * If not provided, will be derived from the session key.
45
+ * Only needed in advanced scenarios where the session key address
46
+ * differs from the wallet address.
47
+ */
48
+ walletAddress?: string;
49
+ /**
50
+ * Optional client-side maximum payment per request in USD.
51
+ *
52
+ * This is an additional safety limit on the client side, independent
53
+ * of the session key's limits. Useful for preventing accidental
54
+ * large payments due to bugs or misconfiguration.
55
+ *
56
+ * @example 5.0 - Maximum $5 per request
57
+ */
58
+ maxPaymentUsd?: number;
59
+ /**
60
+ * Optional callback when a payment is successfully made.
61
+ *
62
+ * Use this to track payments in your application, update UI,
63
+ * or log payment events.
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * onPayment: (payment) => {
68
+ * console.log(`Paid $${payment.amountUsd} for ${payment.description}`);
69
+ * analytics.track('payment', payment);
70
+ * }
71
+ * ```
72
+ */
73
+ onPayment?: (payment: PaymentEvent) => void;
74
+ /**
75
+ * x402 facilitator endpoint.
76
+ *
77
+ * The facilitator processes the payment and forwards the request.
78
+ * Default: 'https://x402.org/facilitator'
79
+ */
80
+ facilitatorUrl?: string;
81
+ /**
82
+ * MixrPay API base URL.
83
+ *
84
+ * Default: 'http://localhost:3000' (or MIXRPAY_BASE_URL env var)
85
+ */
86
+ baseUrl?: string;
87
+ /**
88
+ * Request timeout in milliseconds.
89
+ *
90
+ * Default: 30000 (30 seconds)
91
+ */
92
+ timeout?: number;
93
+ /**
94
+ * Log level for SDK operations.
95
+ *
96
+ * - 'debug': Verbose logging for development
97
+ * - 'info': Important events (payments, etc.)
98
+ * - 'warn': Warnings only
99
+ * - 'error': Errors only
100
+ * - 'none': No logging (default)
101
+ *
102
+ * @example 'info' - Log payments and important events
103
+ */
104
+ logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'none';
105
+ }
106
+ /**
107
+ * Record of a payment made by the SDK.
108
+ *
109
+ * This is emitted via the `onPayment` callback and stored in the payment history.
110
+ */
111
+ interface PaymentEvent {
112
+ /** Payment amount in USD */
113
+ amountUsd: number;
114
+ /** Recipient wallet address */
115
+ recipient: string;
116
+ /** Transaction hash on the blockchain (if available) */
117
+ txHash: string | null;
118
+ /** Timestamp when the payment was made */
119
+ timestamp: Date;
120
+ /** Description of what was paid for (from the server) */
121
+ description?: string;
122
+ /** URL that triggered the payment */
123
+ url?: string;
124
+ }
125
+ /**
126
+ * Information about a session key.
127
+ */
128
+ interface SessionKeyInfo {
129
+ /** The session key's address (derived public key) */
130
+ address: string;
131
+ /** Whether the session key is currently valid */
132
+ isValid: boolean;
133
+ /** Spending limits configured for this session key */
134
+ limits: {
135
+ /** Maximum amount per transaction in USD (null = no limit) */
136
+ perTxUsd: number | null;
137
+ /** Maximum amount per day in USD (null = no limit) */
138
+ dailyUsd: number | null;
139
+ /** Maximum total amount in USD (null = no limit) */
140
+ totalUsd: number | null;
141
+ };
142
+ /** Current usage statistics */
143
+ usage: {
144
+ /** Amount spent today in USD */
145
+ todayUsd: number;
146
+ /** Total amount spent in USD */
147
+ totalUsd: number;
148
+ /** Number of transactions made */
149
+ txCount: number;
150
+ };
151
+ /** When the session key expires (null = never) */
152
+ expiresAt: Date | null;
153
+ /** When the session key was created */
154
+ createdAt: Date | null;
155
+ /** Optional name given to this session key */
156
+ name?: string;
157
+ }
158
+ /**
159
+ * Spending statistics for the current session.
160
+ */
161
+ interface SpendingStats {
162
+ /** Total amount spent in USD during this session */
163
+ totalSpentUsd: number;
164
+ /** Number of payment transactions made */
165
+ txCount: number;
166
+ /** Remaining daily limit in USD (null if no limit or unknown) */
167
+ remainingDailyUsd: number | null;
168
+ /** Remaining total limit in USD (null if no limit or unknown) */
169
+ remainingTotalUsd: number | null;
170
+ /** When the session key expires (null if never or unknown) */
171
+ expiresAt: Date | null;
172
+ }
173
+ /**
174
+ * Result of running diagnostics on the wallet.
175
+ */
176
+ interface DiagnosticsResult {
177
+ /** Whether all checks passed */
178
+ healthy: boolean;
179
+ /** List of issues found (empty if healthy) */
180
+ issues: string[];
181
+ /** Individual check results */
182
+ checks: {
183
+ /** Session key format is valid */
184
+ sessionKeyFormat?: boolean;
185
+ /** Can connect to MixrPay API */
186
+ apiConnectivity?: boolean;
187
+ /** Session key is valid and not expired */
188
+ sessionKeyValid?: boolean;
189
+ /** Wallet has USDC balance */
190
+ hasBalance?: boolean;
191
+ };
192
+ /** SDK version */
193
+ sdkVersion: string;
194
+ /** Network name (Base or Base Sepolia) */
195
+ network: string;
196
+ /** Wallet address */
197
+ walletAddress: string;
198
+ }
199
+ /**
200
+ * Options for creating a session authorization with a MixrPay merchant.
201
+ */
202
+ interface CreateSessionOptions {
203
+ /**
204
+ * The merchant's MixrPay public key.
205
+ * Format: `pk_live_...` or `pk_test_...`
206
+ */
207
+ merchantPublicKey: string;
208
+ /**
209
+ * Maximum spending limit for this session in USD.
210
+ * @default 25.00
211
+ */
212
+ spendingLimitUsd?: number;
213
+ /**
214
+ * Number of days this session should be valid.
215
+ * @default 7
216
+ */
217
+ durationDays?: number;
218
+ }
219
+ /**
220
+ * Status of a session authorization.
221
+ */
222
+ type SessionAuthStatus = 'pending' | 'active' | 'expired' | 'revoked';
223
+ /**
224
+ * A session authorization with a MixrPay merchant.
225
+ *
226
+ * This represents a user-approved spending permission for a specific merchant.
227
+ */
228
+ interface SessionAuthorization {
229
+ /** Unique session ID */
230
+ id: string;
231
+ /** Merchant ID */
232
+ merchantId: string;
233
+ /** Merchant name */
234
+ merchantName: string;
235
+ /** Current session status */
236
+ status: SessionAuthStatus;
237
+ /** Maximum spending limit in USD */
238
+ spendingLimitUsd: number;
239
+ /** Amount already spent in USD */
240
+ amountUsedUsd: number;
241
+ /** Remaining spending limit in USD */
242
+ remainingLimitUsd: number;
243
+ /** When the session expires */
244
+ expiresAt: Date;
245
+ /** When the session was created */
246
+ createdAt: Date;
247
+ }
248
+ /**
249
+ * Options for calling a MixrPay merchant's API.
250
+ */
251
+ interface CallMerchantApiOptions {
252
+ /**
253
+ * The merchant API URL to call.
254
+ */
255
+ url: string;
256
+ /**
257
+ * HTTP method (default: 'POST').
258
+ */
259
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
260
+ /**
261
+ * Request body (will be JSON-serialized if object).
262
+ */
263
+ body?: unknown;
264
+ /**
265
+ * Additional headers to include.
266
+ */
267
+ headers?: Record<string, string>;
268
+ /**
269
+ * The merchant's MixrPay public key.
270
+ * Required to identify which session to use.
271
+ */
272
+ merchantPublicKey: string;
273
+ /**
274
+ * Expected price in USD for this request.
275
+ * Used for client-side validation.
276
+ */
277
+ priceUsd?: number;
278
+ /**
279
+ * Feature slug for tracking/analytics.
280
+ */
281
+ feature?: string;
282
+ }
283
+ /**
284
+ * Options for charging against a session.
285
+ */
286
+ interface ChargeSessionOptions {
287
+ /** Feature slug for tracking */
288
+ feature?: string;
289
+ /** Idempotency key to prevent double-charges */
290
+ idempotencyKey?: string;
291
+ /** Additional metadata */
292
+ metadata?: Record<string, unknown>;
293
+ }
294
+ /**
295
+ * Result of a session charge.
296
+ */
297
+ interface ChargeResult {
298
+ /** Whether the charge succeeded */
299
+ success: boolean;
300
+ /** Charge ID */
301
+ chargeId: string;
302
+ /** Amount charged in USD */
303
+ amountUsd: number;
304
+ /** Transaction hash (if on-chain) */
305
+ txHash?: string;
306
+ /** Remaining session balance in USD */
307
+ remainingSessionBalanceUsd: number;
308
+ }
309
+ /**
310
+ * Statistics about session authorizations.
311
+ *
312
+ * This provides an overview of all sessions managed by the wallet.
313
+ */
314
+ interface SessionStats {
315
+ /** Number of active sessions */
316
+ activeCount: number;
317
+ /** Number of expired sessions */
318
+ expiredCount: number;
319
+ /** Number of revoked sessions */
320
+ revokedCount: number;
321
+ /** Total amount authorized across all active sessions in USD */
322
+ totalAuthorizedUsd: number;
323
+ /** Total amount spent across all sessions in USD */
324
+ totalSpentUsd: number;
325
+ /** Total remaining across all active sessions in USD */
326
+ totalRemainingUsd: number;
327
+ /** List of active sessions (summary) */
328
+ activeSessions: Array<{
329
+ id: string;
330
+ merchantName: string;
331
+ merchantPublicKey: string;
332
+ spendingLimitUsd: number;
333
+ remainingUsd: number;
334
+ expiresAt: Date;
335
+ }>;
336
+ }
337
+
338
+ /**
339
+ * MixrPay Agent SDK - AgentWallet
340
+ *
341
+ * Main class for AI agents to make x402 payments. Provides a simple interface
342
+ * for making HTTP requests that automatically handle payments using session keys.
343
+ *
344
+ * @example Quick Start
345
+ * ```typescript
346
+ * import { AgentWallet } from '@mixrpay/agent-sdk';
347
+ *
348
+ * // Initialize with your session key
349
+ * const wallet = new AgentWallet({ sessionKey: 'sk_live_...' });
350
+ *
351
+ * // Make requests - payments handled automatically!
352
+ * const response = await wallet.fetch('https://api.example.com/ai/query', {
353
+ * method: 'POST',
354
+ * body: JSON.stringify({ prompt: 'Hello world' })
355
+ * });
356
+ *
357
+ * console.log(await response.json());
358
+ * ```
359
+ */
360
+
361
+ /** Current SDK version */
362
+ declare const SDK_VERSION = "0.4.1";
363
+ /** Supported networks */
364
+ declare const NETWORKS: {
365
+ readonly BASE_MAINNET: {
366
+ readonly chainId: 8453;
367
+ readonly name: "Base";
368
+ readonly isTestnet: false;
369
+ };
370
+ readonly BASE_SEPOLIA: {
371
+ readonly chainId: 84532;
372
+ readonly name: "Base Sepolia";
373
+ readonly isTestnet: true;
374
+ };
375
+ };
376
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';
377
+ /**
378
+ * A wallet wrapper for AI agents that handles x402 payments automatically.
379
+ *
380
+ * The AgentWallet makes it easy for AI agents to access paid APIs. When a server
381
+ * returns a 402 Payment Required response, the SDK automatically handles the payment
382
+ * using a session key and retries the request.
383
+ *
384
+ * ## Features
385
+ * - 🔐 **Secure**: Session keys have built-in spending limits
386
+ * - 🤖 **Agent-Ready**: Works with any AI framework (Vercel AI SDK, LangChain, etc.)
387
+ * - ⚡ **Automatic**: No manual payment handling needed
388
+ * - 📊 **Tracking**: Built-in spending statistics and payment history
389
+ * - 🔄 **Drop-in**: Uses the same interface as native `fetch()`
390
+ *
391
+ * ## Quick Start
392
+ *
393
+ * ```typescript
394
+ * const wallet = new AgentWallet({
395
+ * sessionKey: 'sk_live_...', // Get this from the wallet owner
396
+ * onPayment: (p) => console.log(`Paid $${p.amountUsd}`)
397
+ * });
398
+ *
399
+ * // Just use fetch() - payments are automatic!
400
+ * const response = await wallet.fetch('https://api.example.com/endpoint');
401
+ * ```
402
+ *
403
+ * ## Session Keys
404
+ *
405
+ * Session keys are granted by wallet owners and have spending limits:
406
+ * - **Per-transaction limit**: Maximum amount per single request
407
+ * - **Daily limit**: Maximum total per 24 hours
408
+ * - **Total limit**: Maximum lifetime spend
409
+ * - **Expiration**: When the key becomes invalid
410
+ *
411
+ * Keys are prefixed with `sk_live_` (mainnet) or `sk_test_` (testnet).
412
+ *
413
+ * @see {@link AgentWalletConfig} for configuration options
414
+ * @see {@link PaymentEvent} for payment tracking
415
+ */
416
+ declare class AgentWallet {
417
+ private readonly sessionKey;
418
+ private readonly walletAddress;
419
+ private readonly maxPaymentUsd?;
420
+ private readonly onPayment?;
421
+ private readonly baseUrl;
422
+ private readonly timeout;
423
+ private readonly logger;
424
+ private payments;
425
+ private totalSpentUsd;
426
+ private sessionKeyInfo?;
427
+ private sessionKeyInfoFetchedAt?;
428
+ /**
429
+ * Create a new AgentWallet instance.
430
+ *
431
+ * @param config - Configuration options
432
+ * @throws {InvalidSessionKeyError} If the session key format is invalid
433
+ *
434
+ * @example Basic initialization
435
+ * ```typescript
436
+ * const wallet = new AgentWallet({
437
+ * sessionKey: 'sk_live_abc123...'
438
+ * });
439
+ * ```
440
+ *
441
+ * @example With all options
442
+ * ```typescript
443
+ * const wallet = new AgentWallet({
444
+ * sessionKey: 'sk_live_abc123...',
445
+ * maxPaymentUsd: 5.0, // Client-side safety limit
446
+ * onPayment: (p) => log(p), // Track payments
447
+ * logLevel: 'info', // Enable logging
448
+ * timeout: 60000, // 60s timeout
449
+ * });
450
+ * ```
451
+ */
452
+ constructor(config: AgentWalletConfig);
453
+ /**
454
+ * Validate the configuration before initialization.
455
+ */
456
+ private validateConfig;
457
+ /**
458
+ * Make an HTTP request, automatically handling x402 payment if required.
459
+ *
460
+ * This is a drop-in replacement for the native `fetch()` function.
461
+ * If the server returns 402 Payment Required:
462
+ * 1. Parse payment requirements from response
463
+ * 2. Sign transferWithAuthorization using session key
464
+ * 3. Retry request with X-PAYMENT header
465
+ *
466
+ * @param url - Request URL
467
+ * @param init - Request options (same as native fetch)
468
+ * @returns Response from the server
469
+ *
470
+ * @throws {InsufficientBalanceError} If wallet doesn't have enough USDC
471
+ * @throws {SessionKeyExpiredError} If session key has expired
472
+ * @throws {SpendingLimitExceededError} If payment would exceed limits
473
+ * @throws {PaymentFailedError} If payment transaction failed
474
+ *
475
+ * @example GET request
476
+ * ```typescript
477
+ * const response = await wallet.fetch('https://api.example.com/data');
478
+ * const data = await response.json();
479
+ * ```
480
+ *
481
+ * @example POST request with JSON
482
+ * ```typescript
483
+ * const response = await wallet.fetch('https://api.example.com/generate', {
484
+ * method: 'POST',
485
+ * headers: { 'Content-Type': 'application/json' },
486
+ * body: JSON.stringify({ prompt: 'Hello world' })
487
+ * });
488
+ * ```
489
+ */
490
+ fetch(url: string, init?: RequestInit): Promise<Response>;
491
+ /**
492
+ * Handle a 402 Payment Required response.
493
+ */
494
+ private handlePaymentRequired;
495
+ /**
496
+ * Handle payment-specific errors from the response.
497
+ */
498
+ private handlePaymentError;
499
+ /**
500
+ * Get the wallet address.
501
+ *
502
+ * @returns The Ethereum address of the smart wallet
503
+ */
504
+ getWalletAddress(): `0x${string}`;
505
+ /**
506
+ * Check if using testnet session key.
507
+ *
508
+ * @returns true if using Base Sepolia (testnet), false if using Base Mainnet
509
+ */
510
+ isTestnet(): boolean;
511
+ /**
512
+ * Get the network information.
513
+ *
514
+ * @returns Network details including chain ID and name
515
+ */
516
+ getNetwork(): typeof NETWORKS.BASE_MAINNET | typeof NETWORKS.BASE_SEPOLIA;
517
+ /**
518
+ * Get current USDC balance of the wallet.
519
+ *
520
+ * @returns USDC balance in USD
521
+ *
522
+ * @example
523
+ * ```typescript
524
+ * const balance = await wallet.getBalance();
525
+ * console.log(`Balance: $${balance.toFixed(2)}`);
526
+ * ```
527
+ */
528
+ getBalance(): Promise<number>;
529
+ /**
530
+ * Get information about the session key.
531
+ *
532
+ * @param refresh - Force refresh from server (default: use cache if < 60s old)
533
+ * @returns Session key details including limits and expiration
534
+ *
535
+ * @example
536
+ * ```typescript
537
+ * const info = await wallet.getSessionKeyInfo();
538
+ * console.log(`Daily limit: $${info.limits.dailyUsd}`);
539
+ * console.log(`Expires: ${info.expiresAt}`);
540
+ * ```
541
+ */
542
+ getSessionKeyInfo(refresh?: boolean): Promise<SessionKeyInfo>;
543
+ /**
544
+ * Get spending stats for this session key.
545
+ *
546
+ * @returns Spending statistics
547
+ *
548
+ * @example
549
+ * ```typescript
550
+ * const stats = await wallet.getSpendingStats();
551
+ * console.log(`Spent: $${stats.totalSpentUsd.toFixed(2)}`);
552
+ * console.log(`Remaining daily: $${stats.remainingDailyUsd?.toFixed(2) ?? 'unlimited'}`);
553
+ * ```
554
+ */
555
+ getSpendingStats(): Promise<SpendingStats>;
556
+ /**
557
+ * Get list of payments made in this session.
558
+ *
559
+ * @returns Array of payment events
560
+ */
561
+ getPaymentHistory(): PaymentEvent[];
562
+ /**
563
+ * Get the total amount spent in this session.
564
+ *
565
+ * @returns Total spent in USD
566
+ */
567
+ getTotalSpent(): number;
568
+ /**
569
+ * Run diagnostics to verify the wallet is properly configured.
570
+ *
571
+ * This is useful for debugging integration issues.
572
+ *
573
+ * @returns Diagnostic results with status and any issues found
574
+ *
575
+ * @example
576
+ * ```typescript
577
+ * const diagnostics = await wallet.runDiagnostics();
578
+ * if (diagnostics.healthy) {
579
+ * console.log('✅ Wallet is ready to use');
580
+ * } else {
581
+ * console.log('❌ Issues found:');
582
+ * diagnostics.issues.forEach(issue => console.log(` - ${issue}`));
583
+ * }
584
+ * ```
585
+ */
586
+ runDiagnostics(): Promise<DiagnosticsResult>;
587
+ /**
588
+ * Enable or disable debug logging.
589
+ *
590
+ * @param enable - true to enable debug logging, false to disable
591
+ *
592
+ * @example
593
+ * ```typescript
594
+ * wallet.setDebug(true); // Enable detailed logs
595
+ * await wallet.fetch(...);
596
+ * wallet.setDebug(false); // Disable logs
597
+ * ```
598
+ */
599
+ setDebug(enable: boolean): void;
600
+ /**
601
+ * Set the log level.
602
+ *
603
+ * @param level - 'debug' | 'info' | 'warn' | 'error' | 'none'
604
+ */
605
+ setLogLevel(level: LogLevel): void;
606
+ /**
607
+ * Create the X-Session-Auth header for secure API authentication.
608
+ * Uses signature-based authentication - private key is NEVER transmitted.
609
+ *
610
+ * @returns Headers object with X-Session-Auth
611
+ */
612
+ private getSessionAuthHeaders;
613
+ /**
614
+ * Get an existing session or create a new one with a MixrPay merchant.
615
+ *
616
+ * This is the recommended way to interact with MixrPay-enabled APIs.
617
+ * If an active session exists, it will be returned. Otherwise, a new
618
+ * session authorization request will be created and confirmed.
619
+ *
620
+ * @param options - Session creation options
621
+ * @returns Active session authorization
622
+ *
623
+ * @throws {MixrPayError} If merchant is not found or session creation fails
624
+ *
625
+ * @example
626
+ * ```typescript
627
+ * const session = await wallet.getOrCreateSession({
628
+ * merchantPublicKey: 'pk_live_abc123...',
629
+ * spendingLimitUsd: 25.00,
630
+ * durationDays: 7,
631
+ * });
632
+ *
633
+ * console.log(`Session active: $${session.remainingLimitUsd} remaining`);
634
+ * ```
635
+ */
636
+ getOrCreateSession(options: CreateSessionOptions): Promise<SessionAuthorization>;
637
+ /**
638
+ * Get session status for a specific merchant.
639
+ *
640
+ * @param merchantPublicKey - The merchant's public key
641
+ * @returns Session authorization or null if not found
642
+ */
643
+ getSessionByMerchant(merchantPublicKey: string): Promise<SessionAuthorization | null>;
644
+ /**
645
+ * List all session authorizations for this wallet.
646
+ *
647
+ * @returns Array of session authorizations
648
+ *
649
+ * @example
650
+ * ```typescript
651
+ * const sessions = await wallet.listSessions();
652
+ * for (const session of sessions) {
653
+ * console.log(`${session.merchantName}: $${session.remainingLimitUsd} remaining`);
654
+ * }
655
+ * ```
656
+ */
657
+ listSessions(): Promise<SessionAuthorization[]>;
658
+ /**
659
+ * Revoke a session authorization.
660
+ *
661
+ * After revocation, no further charges can be made against this session.
662
+ *
663
+ * @param sessionId - The session ID to revoke
664
+ * @returns true if revoked successfully
665
+ *
666
+ * @example
667
+ * ```typescript
668
+ * const revoked = await wallet.revokeSession('sess_abc123');
669
+ * if (revoked) {
670
+ * console.log('Session revoked successfully');
671
+ * }
672
+ * ```
673
+ */
674
+ revokeSession(sessionId: string): Promise<boolean>;
675
+ /**
676
+ * Get statistics about all session authorizations.
677
+ *
678
+ * This provides an overview of active, expired, and revoked sessions,
679
+ * along with aggregate spending information.
680
+ *
681
+ * @returns Session statistics
682
+ *
683
+ * @example
684
+ * ```typescript
685
+ * const stats = await wallet.getSessionStats();
686
+ * console.log(`Active sessions: ${stats.activeCount}`);
687
+ * console.log(`Total authorized: $${stats.totalAuthorizedUsd.toFixed(2)}`);
688
+ * console.log(`Total remaining: $${stats.totalRemainingUsd.toFixed(2)}`);
689
+ *
690
+ * for (const session of stats.activeSessions) {
691
+ * console.log(`${session.merchantName}: $${session.remainingUsd} remaining`);
692
+ * }
693
+ * ```
694
+ */
695
+ getSessionStats(): Promise<SessionStats>;
696
+ /**
697
+ * Charge against an active session authorization.
698
+ *
699
+ * This is useful when you need to manually charge a session outside of
700
+ * the `callMerchantApi()` flow.
701
+ *
702
+ * @param sessionId - The session ID to charge
703
+ * @param amountUsd - Amount to charge in USD
704
+ * @param options - Additional charge options
705
+ * @returns Charge result
706
+ *
707
+ * @example
708
+ * ```typescript
709
+ * const result = await wallet.chargeSession('sess_abc123', 0.05, {
710
+ * feature: 'ai-generation',
711
+ * idempotencyKey: 'unique-key-123',
712
+ * });
713
+ *
714
+ * console.log(`Charged $${result.amountUsd}, remaining: $${result.remainingSessionBalanceUsd}`);
715
+ * ```
716
+ */
717
+ chargeSession(sessionId: string, amountUsd: number, options?: ChargeSessionOptions): Promise<ChargeResult>;
718
+ /**
719
+ * Call a MixrPay merchant's API with automatic session management.
720
+ *
721
+ * This is the recommended way to interact with MixrPay-enabled APIs.
722
+ * It automatically:
723
+ * 1. Gets or creates a session authorization
724
+ * 2. Adds the `X-Mixr-Session` header to the request
725
+ * 3. Handles payment errors and session expiration
726
+ *
727
+ * @param options - API call options
728
+ * @returns Response from the merchant API
729
+ *
730
+ * @example
731
+ * ```typescript
732
+ * const response = await wallet.callMerchantApi({
733
+ * url: 'https://api.merchant.com/generate',
734
+ * merchantPublicKey: 'pk_live_abc123...',
735
+ * method: 'POST',
736
+ * body: { prompt: 'Hello world' },
737
+ * priceUsd: 0.05,
738
+ * });
739
+ *
740
+ * const data = await response.json();
741
+ * ```
742
+ */
743
+ callMerchantApi(options: CallMerchantApiOptions): Promise<Response>;
744
+ /**
745
+ * Parse session response data into SessionAuthorization object.
746
+ */
747
+ private parseSessionResponse;
748
+ /**
749
+ * Get authentication headers for MCP wallet-based authentication.
750
+ *
751
+ * These headers prove wallet ownership without transmitting the private key.
752
+ * Use for direct pay-per-call mode (no session needed).
753
+ *
754
+ * @returns Headers object with X-Mixr-Wallet, X-Mixr-Signature, X-Mixr-Timestamp
755
+ *
756
+ * @example
757
+ * ```typescript
758
+ * const headers = await wallet.getMCPAuthHeaders();
759
+ * const response = await fetch('https://mixrpay.com/api/mcp', {
760
+ * method: 'POST',
761
+ * headers: {
762
+ * 'Content-Type': 'application/json',
763
+ * ...headers,
764
+ * },
765
+ * body: JSON.stringify({
766
+ * jsonrpc: '2.0',
767
+ * method: 'tools/list',
768
+ * id: 1,
769
+ * }),
770
+ * });
771
+ * ```
772
+ */
773
+ getMCPAuthHeaders(): Promise<Record<string, string>>;
774
+ /**
775
+ * List available MCP tools from the MixrPay gateway.
776
+ *
777
+ * Returns all tools exposed by MCP providers on the MixrPay marketplace.
778
+ * Each tool includes pricing information.
779
+ *
780
+ * @returns Array of MCP tools with pricing and metadata
781
+ *
782
+ * @example
783
+ * ```typescript
784
+ * const tools = await wallet.listMCPTools();
785
+ * for (const tool of tools) {
786
+ * console.log(`${tool.name}: $${tool.priceUsd} - ${tool.description}`);
787
+ * }
788
+ * ```
789
+ */
790
+ listMCPTools(): Promise<MCPTool[]>;
791
+ /**
792
+ * Call an MCP tool with wallet authentication (direct pay per call).
793
+ *
794
+ * This method signs a fresh auth message for each call, charging
795
+ * directly from your wallet balance without needing a session.
796
+ *
797
+ * @param toolName - The tool name in format "merchant/tool"
798
+ * @param args - Arguments to pass to the tool
799
+ * @returns Tool execution result
800
+ *
801
+ * @example
802
+ * ```typescript
803
+ * const result = await wallet.callMCPTool('firecrawl/scrape', {
804
+ * url: 'https://example.com',
805
+ * });
806
+ * console.log(result.data);
807
+ * console.log(`Charged: $${result.chargedUsd}`);
808
+ * ```
809
+ */
810
+ callMCPTool(toolName: string, args?: Record<string, unknown>): Promise<MCPToolResult>;
811
+ /**
812
+ * Run an AI agent with LLM and tool execution.
813
+ *
814
+ * This method orchestrates a full agentic loop:
815
+ * - Multi-turn reasoning with LLM
816
+ * - Automatic tool execution
817
+ * - Bundled billing (single charge at end)
818
+ * - Optional streaming via SSE
819
+ *
820
+ * @param options - Agent run options
821
+ * @returns Agent run result with response and cost breakdown
822
+ *
823
+ * @example Basic usage
824
+ * ```typescript
825
+ * const result = await wallet.runAgent({
826
+ * sessionId: 'sess_abc123',
827
+ * messages: [{ role: 'user', content: 'Find AI startups in SF' }],
828
+ * });
829
+ *
830
+ * console.log(result.response);
831
+ * console.log(`Cost: $${result.cost.totalUsd.toFixed(4)}`);
832
+ * ```
833
+ *
834
+ * @example With custom config
835
+ * ```typescript
836
+ * const result = await wallet.runAgent({
837
+ * sessionId: 'sess_abc123',
838
+ * messages: [{ role: 'user', content: 'Research quantum computing' }],
839
+ * config: {
840
+ * model: 'gpt-4o',
841
+ * maxIterations: 15,
842
+ * tools: ['platform/exa-search', 'platform/firecrawl-scrape'],
843
+ * systemPrompt: 'You are a research assistant.',
844
+ * },
845
+ * });
846
+ * ```
847
+ *
848
+ * @example With streaming
849
+ * ```typescript
850
+ * await wallet.runAgent({
851
+ * sessionId: 'sess_abc123',
852
+ * messages: [{ role: 'user', content: 'Analyze this company' }],
853
+ * stream: true,
854
+ * onEvent: (event) => {
855
+ * if (event.type === 'llm_chunk') {
856
+ * process.stdout.write(event.delta);
857
+ * } else if (event.type === 'tool_call') {
858
+ * console.log(`Calling tool: ${event.tool}`);
859
+ * }
860
+ * },
861
+ * });
862
+ * ```
863
+ */
864
+ runAgent(options: AgentRunOptions): Promise<AgentRunResult>;
865
+ /**
866
+ * Internal: Handle streaming agent run via SSE
867
+ */
868
+ private runAgentStreaming;
869
+ /**
870
+ * Internal: Parse SSE event into typed event object
871
+ */
872
+ private parseSSEEvent;
873
+ /**
874
+ * Get the status of an agent run by ID.
875
+ *
876
+ * @param runId - The agent run ID
877
+ * @param sessionId - The session ID (for authentication)
878
+ * @returns Agent run status and results
879
+ *
880
+ * @example
881
+ * ```typescript
882
+ * const status = await wallet.getAgentRunStatus('run_abc123', 'sess_xyz789');
883
+ * console.log(`Status: ${status.status}`);
884
+ * if (status.status === 'completed') {
885
+ * console.log(status.response);
886
+ * }
887
+ * ```
888
+ */
889
+ getAgentRunStatus(runId: string, sessionId: string): Promise<AgentRunStatusResult>;
890
+ /**
891
+ * Call an MCP tool using session authorization (pre-authorized spending limit).
892
+ *
893
+ * Use this when you've already created a session with the tool provider
894
+ * and want to use that spending limit instead of direct wallet charges.
895
+ *
896
+ * @param sessionId - The session ID for the tool provider
897
+ * @param toolName - The tool name in format "merchant/tool"
898
+ * @param args - Arguments to pass to the tool
899
+ * @returns Tool execution result
900
+ *
901
+ * @example
902
+ * ```typescript
903
+ * // Create session with provider first
904
+ * const session = await wallet.getOrCreateSession({
905
+ * merchantPublicKey: 'pk_live_firecrawl_...',
906
+ * spendingLimitUsd: 50,
907
+ * });
908
+ *
909
+ * // Use session for multiple calls
910
+ * const result = await wallet.callMCPToolWithSession(
911
+ * session.id,
912
+ * 'firecrawl/scrape',
913
+ * { url: 'https://example.com' }
914
+ * );
915
+ * ```
916
+ */
917
+ callMCPToolWithSession(sessionId: string, toolName: string, args?: Record<string, unknown>): Promise<MCPToolResult>;
918
+ }
919
+ /**
920
+ * MCP Tool definition returned by listMCPTools()
921
+ */
922
+ interface MCPTool {
923
+ /** Tool name in format "merchant/tool" */
924
+ name: string;
925
+ /** Human-readable description with price */
926
+ description: string;
927
+ /** JSON Schema for tool input parameters */
928
+ inputSchema: Record<string, unknown>;
929
+ /** Price per call in USD */
930
+ priceUsd: number;
931
+ /** Merchant/provider name */
932
+ merchantName: string;
933
+ /** Merchant slug for session creation */
934
+ merchantSlug: string;
935
+ /** Whether the provider is domain-verified */
936
+ verified: boolean;
937
+ }
938
+ /**
939
+ * Result from calling an MCP tool
940
+ */
941
+ interface MCPToolResult {
942
+ /** The tool's response data */
943
+ data: unknown;
944
+ /** Amount charged in USD */
945
+ chargedUsd: number;
946
+ /** On-chain transaction hash (if available) */
947
+ txHash?: string;
948
+ /** Execution latency in milliseconds */
949
+ latencyMs?: number;
950
+ }
951
+ /**
952
+ * Message in an agent conversation
953
+ */
954
+ interface AgentMessage {
955
+ /** Message role */
956
+ role: 'user' | 'assistant' | 'system' | 'tool';
957
+ /** Message content */
958
+ content: string;
959
+ }
960
+ /**
961
+ * Configuration for an agent run
962
+ */
963
+ interface AgentRunConfig {
964
+ /** LLM model to use (default: gpt-4o-mini) */
965
+ model?: string;
966
+ /** Maximum iterations before stopping (default: 10, max: 25) */
967
+ maxIterations?: number;
968
+ /** Specific tools to enable (e.g., ['platform/exa-search', 'platform/firecrawl-scrape']) */
969
+ tools?: string[];
970
+ /** Custom system prompt for the agent */
971
+ systemPrompt?: string;
972
+ }
973
+ /**
974
+ * Options for running an agent
975
+ */
976
+ interface AgentRunOptions {
977
+ /** Session ID for authentication and billing */
978
+ sessionId: string;
979
+ /** Conversation messages */
980
+ messages: AgentMessage[];
981
+ /** Agent configuration */
982
+ config?: AgentRunConfig;
983
+ /** Enable SSE streaming (default: false) */
984
+ stream?: boolean;
985
+ /** Unique key for idempotency */
986
+ idempotencyKey?: string;
987
+ /** Callback for streaming events */
988
+ onEvent?: (event: AgentRunEvent) => void;
989
+ }
990
+ /**
991
+ * Result from an agent run
992
+ */
993
+ interface AgentRunResult {
994
+ /** Unique run ID */
995
+ runId: string;
996
+ /** Run status */
997
+ status: 'completed' | 'failed';
998
+ /** Final response from the agent */
999
+ response: string;
1000
+ /** Number of iterations performed */
1001
+ iterations: number;
1002
+ /** Tools used during the run */
1003
+ toolsUsed: string[];
1004
+ /** Cost breakdown */
1005
+ cost: {
1006
+ /** LLM cost in USD */
1007
+ llmUsd: number;
1008
+ /** Tool execution cost in USD */
1009
+ toolsUsd: number;
1010
+ /** Total cost in USD */
1011
+ totalUsd: number;
1012
+ };
1013
+ /** Token usage */
1014
+ tokens: {
1015
+ /** Prompt tokens used */
1016
+ prompt: number;
1017
+ /** Completion tokens used */
1018
+ completion: number;
1019
+ };
1020
+ /** Remaining session balance in USD */
1021
+ sessionRemainingUsd: number;
1022
+ /** On-chain transaction hash for payment */
1023
+ txHash?: string;
1024
+ }
1025
+ /**
1026
+ * Streaming events from an agent run
1027
+ */
1028
+ type AgentRunEvent = {
1029
+ type: 'run_start';
1030
+ runId: string;
1031
+ } | {
1032
+ type: 'iteration_start';
1033
+ iteration: number;
1034
+ } | {
1035
+ type: 'llm_chunk';
1036
+ delta: string;
1037
+ } | {
1038
+ type: 'tool_call';
1039
+ tool: string;
1040
+ arguments: unknown;
1041
+ } | {
1042
+ type: 'tool_result';
1043
+ tool: string;
1044
+ success: boolean;
1045
+ costUsd: number;
1046
+ error?: string;
1047
+ } | {
1048
+ type: 'iteration_complete';
1049
+ iteration: number;
1050
+ tokens?: {
1051
+ prompt?: number;
1052
+ completion?: number;
1053
+ };
1054
+ costUsd?: number;
1055
+ } | {
1056
+ type: 'complete';
1057
+ runId: string;
1058
+ response: string;
1059
+ totalCostUsd: number;
1060
+ txHash?: string;
1061
+ iterations: number;
1062
+ toolsUsed: string[];
1063
+ } | {
1064
+ type: 'error';
1065
+ error: string;
1066
+ partialCostUsd?: number;
1067
+ };
1068
+ /**
1069
+ * Result from getting agent run status
1070
+ */
1071
+ interface AgentRunStatusResult {
1072
+ /** Unique run ID */
1073
+ runId: string;
1074
+ /** Run status */
1075
+ status: 'running' | 'completed' | 'failed' | 'interrupted';
1076
+ /** Final response (if completed) */
1077
+ response?: string;
1078
+ /** Number of iterations performed */
1079
+ iterations: number;
1080
+ /** Tools used during the run */
1081
+ toolsUsed: string[];
1082
+ /** Cost breakdown */
1083
+ cost: {
1084
+ llmUsd: number;
1085
+ toolsUsd: number;
1086
+ totalUsd: number;
1087
+ };
1088
+ /** Token usage */
1089
+ tokens: {
1090
+ prompt: number;
1091
+ completion: number;
1092
+ };
1093
+ /** On-chain transaction hash */
1094
+ txHash?: string;
1095
+ /** Error message (if failed) */
1096
+ error?: string;
1097
+ /** When the run started */
1098
+ startedAt: Date;
1099
+ /** When the run completed */
1100
+ completedAt?: Date;
1101
+ }
1102
+
1103
+ /**
1104
+ * MixrPay Agent SDK - Custom Errors
1105
+ *
1106
+ * These errors provide clear, actionable messages for common x402 payment failures.
1107
+ * Each error includes:
1108
+ * - A clear description of what went wrong
1109
+ * - Relevant data for programmatic handling
1110
+ * - Suggestions for how to fix the issue
1111
+ *
1112
+ * @example Handling errors
1113
+ * ```typescript
1114
+ * try {
1115
+ * await wallet.fetch('https://api.example.com/query');
1116
+ * } catch (error) {
1117
+ * if (error instanceof InsufficientBalanceError) {
1118
+ * console.log(`Need $${error.required}, have $${error.available}`);
1119
+ * console.log('Top up at:', error.topUpUrl);
1120
+ * }
1121
+ * }
1122
+ * ```
1123
+ */
1124
+ /**
1125
+ * Base error class for all MixrPay SDK errors.
1126
+ *
1127
+ * All SDK errors extend this class, making it easy to catch all MixrPay-related
1128
+ * errors in a single catch block.
1129
+ *
1130
+ * @example
1131
+ * ```typescript
1132
+ * try {
1133
+ * await wallet.fetch(...);
1134
+ * } catch (error) {
1135
+ * if (error instanceof MixrPayError) {
1136
+ * // Handle any MixrPay error
1137
+ * console.log(error.message);
1138
+ * }
1139
+ * }
1140
+ * ```
1141
+ */
1142
+ declare class MixrPayError extends Error {
1143
+ /** Error code for programmatic handling */
1144
+ readonly code: string;
1145
+ constructor(message: string, code?: string);
1146
+ }
1147
+ /**
1148
+ * Thrown when the wallet doesn't have enough USDC for the payment.
1149
+ *
1150
+ * This error indicates the smart wallet needs to be topped up with more USDC.
1151
+ *
1152
+ * ## Resolution
1153
+ * 1. Direct the user to top up their wallet
1154
+ * 2. Use a smaller transaction (if possible)
1155
+ * 3. Wait for pending deposits to confirm
1156
+ *
1157
+ * @example
1158
+ * ```typescript
1159
+ * catch (error) {
1160
+ * if (error instanceof InsufficientBalanceError) {
1161
+ * console.log(`Need $${error.required.toFixed(2)}, have $${error.available.toFixed(2)}`);
1162
+ * console.log(`Top up at: ${error.topUpUrl}`);
1163
+ * }
1164
+ * }
1165
+ * ```
1166
+ */
1167
+ declare class InsufficientBalanceError extends MixrPayError {
1168
+ /** Amount required for the payment in USD */
1169
+ readonly required: number;
1170
+ /** Current available balance in USD */
1171
+ readonly available: number;
1172
+ /** URL where the user can top up their wallet */
1173
+ readonly topUpUrl: string;
1174
+ constructor(required: number, available: number);
1175
+ }
1176
+ /**
1177
+ * Thrown when the session key has expired.
1178
+ *
1179
+ * Session keys have an expiration date set by the wallet owner. Once expired,
1180
+ * the key can no longer authorize payments.
1181
+ *
1182
+ * ## Resolution
1183
+ * 1. Request a new session key from the wallet owner
1184
+ * 2. Create a new session key (if you have wallet access)
1185
+ *
1186
+ * @example
1187
+ * ```typescript
1188
+ * catch (error) {
1189
+ * if (error instanceof SessionKeyExpiredError) {
1190
+ * console.log(`Session key expired at ${error.expiredAt}`);
1191
+ * // Request new key from wallet owner
1192
+ * }
1193
+ * }
1194
+ * ```
1195
+ */
1196
+ declare class SessionKeyExpiredError extends MixrPayError {
1197
+ /** When the session key expired */
1198
+ readonly expiredAt: string;
1199
+ constructor(expiredAt: string);
1200
+ }
1201
+ /**
1202
+ * Thrown when a payment would exceed session key spending limits.
1203
+ *
1204
+ * Session keys can have three types of limits:
1205
+ * - **per_tx**: Maximum per single transaction
1206
+ * - **daily**: Maximum total per 24-hour period
1207
+ * - **total**: Maximum lifetime spend
1208
+ * - **client_max**: Client-side limit set in AgentWalletConfig
1209
+ *
1210
+ * ## Resolution
1211
+ * - **per_tx**: Use a smaller transaction or request higher limit
1212
+ * - **daily**: Wait until tomorrow or request higher limit
1213
+ * - **total**: Request a new session key with higher limit
1214
+ * - **client_max**: Increase maxPaymentUsd in config or remove it
1215
+ *
1216
+ * @example
1217
+ * ```typescript
1218
+ * catch (error) {
1219
+ * if (error instanceof SpendingLimitExceededError) {
1220
+ * if (error.limitType === 'daily') {
1221
+ * console.log('Daily limit reached. Try again tomorrow.');
1222
+ * } else if (error.limitType === 'per_tx') {
1223
+ * console.log(`Max per transaction is $${error.limit}`);
1224
+ * }
1225
+ * }
1226
+ * }
1227
+ * ```
1228
+ */
1229
+ declare class SpendingLimitExceededError extends MixrPayError {
1230
+ /** Type of limit that was exceeded */
1231
+ readonly limitType: 'per_tx' | 'daily' | 'total' | 'client_max' | string;
1232
+ /** The limit amount in USD */
1233
+ readonly limit: number;
1234
+ /** The amount that was attempted in USD */
1235
+ readonly attempted: number;
1236
+ constructor(limitType: string, limit: number, attempted: number);
1237
+ }
1238
+ /**
1239
+ * Thrown when a payment transaction fails.
1240
+ *
1241
+ * This is a general error for payment failures that don't fit other categories.
1242
+ * Check the `reason` property for more details.
1243
+ *
1244
+ * ## Common Causes
1245
+ * - Network issues
1246
+ * - Invalid payment parameters
1247
+ * - Server-side errors
1248
+ * - Blockchain congestion
1249
+ *
1250
+ * @example
1251
+ * ```typescript
1252
+ * catch (error) {
1253
+ * if (error instanceof PaymentFailedError) {
1254
+ * console.log(`Payment failed: ${error.reason}`);
1255
+ * if (error.txHash) {
1256
+ * console.log(`Check transaction: https://basescan.org/tx/${error.txHash}`);
1257
+ * }
1258
+ * }
1259
+ * }
1260
+ * ```
1261
+ */
1262
+ declare class PaymentFailedError extends MixrPayError {
1263
+ /** Detailed reason for the failure */
1264
+ readonly reason: string;
1265
+ /** Transaction hash if the tx was submitted (for debugging) */
1266
+ readonly txHash?: string;
1267
+ constructor(reason: string, txHash?: string);
1268
+ }
1269
+ /**
1270
+ * Thrown when the session key format is invalid.
1271
+ *
1272
+ * Session keys must:
1273
+ * - Start with `sk_live_` (mainnet) or `sk_test_` (testnet)
1274
+ * - Be followed by exactly 64 hexadecimal characters
1275
+ * - Total length: 72 characters
1276
+ *
1277
+ * ## Common Issues
1278
+ * - Incomplete copy/paste
1279
+ * - Extra whitespace
1280
+ * - Using API key instead of session key
1281
+ * - Using public key instead of private key
1282
+ *
1283
+ * @example
1284
+ * ```typescript
1285
+ * catch (error) {
1286
+ * if (error instanceof InvalidSessionKeyError) {
1287
+ * console.log(`Invalid key: ${error.reason}`);
1288
+ * console.log('Get a valid session key from your MixrPay server /wallet/sessions');
1289
+ * }
1290
+ * }
1291
+ * ```
1292
+ */
1293
+ declare class InvalidSessionKeyError extends MixrPayError {
1294
+ /** Detailed reason why the key is invalid */
1295
+ readonly reason: string;
1296
+ constructor(reason?: string);
1297
+ }
1298
+ /**
1299
+ * Thrown when a session authorization has expired.
1300
+ *
1301
+ * Session authorizations have an expiration date set when created. Once expired,
1302
+ * the session can no longer be used for payments.
1303
+ *
1304
+ * ## Resolution
1305
+ * Create a new session with the merchant using `wallet.getOrCreateSession()`.
1306
+ * The SDK will automatically create a new session on the next `callMerchantApi()` call.
1307
+ *
1308
+ * @example
1309
+ * ```typescript
1310
+ * catch (error) {
1311
+ * if (error instanceof SessionExpiredError) {
1312
+ * console.log(`Session ${error.sessionId} expired at ${error.expiredAt}`);
1313
+ * // SDK will auto-create new session on next callMerchantApi()
1314
+ * }
1315
+ * }
1316
+ * ```
1317
+ */
1318
+ declare class SessionExpiredError extends MixrPayError {
1319
+ /** ID of the expired session */
1320
+ readonly sessionId: string;
1321
+ /** When the session expired (ISO string or Date) */
1322
+ readonly expiredAt?: string;
1323
+ constructor(sessionId: string, expiredAt?: string);
1324
+ }
1325
+ /**
1326
+ * Thrown when a payment would exceed the session's spending limit.
1327
+ *
1328
+ * Each session authorization has a spending limit set by the user. Once the limit
1329
+ * is reached, no more payments can be made until a new session is created.
1330
+ *
1331
+ * ## Resolution
1332
+ * - Create a new session with a higher limit
1333
+ * - Wait for the current session to be renewed (if auto-renewal is enabled)
1334
+ *
1335
+ * @example
1336
+ * ```typescript
1337
+ * catch (error) {
1338
+ * if (error instanceof SessionLimitExceededError) {
1339
+ * console.log(`Session limit: $${error.limit}, requested: $${error.requested}`);
1340
+ * console.log(`Remaining: $${error.remaining}`);
1341
+ * }
1342
+ * }
1343
+ * ```
1344
+ */
1345
+ declare class SessionLimitExceededError extends MixrPayError {
1346
+ /** ID of the session */
1347
+ readonly sessionId?: string;
1348
+ /** The session's spending limit in USD */
1349
+ readonly limit: number;
1350
+ /** The amount requested in USD */
1351
+ readonly requested: number;
1352
+ /** Remaining balance in the session (limit - used) */
1353
+ readonly remaining: number;
1354
+ constructor(limit: number, requested: number, remaining: number, sessionId?: string);
1355
+ }
1356
+ /**
1357
+ * Thrown when a session ID is invalid or not found.
1358
+ *
1359
+ * This can happen if:
1360
+ * - The session ID was incorrectly formatted
1361
+ * - The session was deleted
1362
+ * - The session belongs to a different user/merchant
1363
+ *
1364
+ * ## Resolution
1365
+ * Create a new session using `wallet.getOrCreateSession()`.
1366
+ *
1367
+ * @example
1368
+ * ```typescript
1369
+ * catch (error) {
1370
+ * if (error instanceof SessionNotFoundError) {
1371
+ * console.log(`Session ${error.sessionId} not found`);
1372
+ * const newSession = await wallet.getOrCreateSession({ ... });
1373
+ * }
1374
+ * }
1375
+ * ```
1376
+ */
1377
+ declare class SessionNotFoundError extends MixrPayError {
1378
+ /** The session ID that was not found */
1379
+ readonly sessionId: string;
1380
+ constructor(sessionId: string);
1381
+ }
1382
+ /**
1383
+ * Thrown when attempting to use a session that has been revoked.
1384
+ *
1385
+ * Sessions can be revoked by:
1386
+ * - The user (wallet owner)
1387
+ * - The merchant
1388
+ * - Automatically by the system (e.g., suspicious activity)
1389
+ *
1390
+ * ## Resolution
1391
+ * Create a new session using `wallet.getOrCreateSession()`.
1392
+ *
1393
+ * @example
1394
+ * ```typescript
1395
+ * catch (error) {
1396
+ * if (error instanceof SessionRevokedError) {
1397
+ * console.log(`Session ${error.sessionId} was revoked`);
1398
+ * if (error.reason) console.log(`Reason: ${error.reason}`);
1399
+ * }
1400
+ * }
1401
+ * ```
1402
+ */
1403
+ declare class SessionRevokedError extends MixrPayError {
1404
+ /** The session ID that was revoked */
1405
+ readonly sessionId: string;
1406
+ /** Optional reason for revocation */
1407
+ readonly reason?: string;
1408
+ constructor(sessionId: string, reason?: string);
1409
+ }
1410
+ /**
1411
+ * Check if an error is a MixrPay SDK error.
1412
+ *
1413
+ * @param error - The error to check
1414
+ * @returns true if the error is a MixrPayError or subclass
1415
+ *
1416
+ * @example
1417
+ * ```typescript
1418
+ * try {
1419
+ * await wallet.fetch(...);
1420
+ * } catch (error) {
1421
+ * if (isMixrPayError(error)) {
1422
+ * console.log('MixrPay error:', error.code, error.message);
1423
+ * } else {
1424
+ * console.log('Other error:', error);
1425
+ * }
1426
+ * }
1427
+ * ```
1428
+ */
1429
+ declare function isMixrPayError(error: unknown): error is MixrPayError;
1430
+
1431
+ export { type AgentMessage, type AgentRunConfig, type AgentRunEvent, type AgentRunOptions, type AgentRunResult, type AgentRunStatusResult, AgentWallet, type AgentWalletConfig, type CallMerchantApiOptions, type ChargeResult, InsufficientBalanceError, InvalidSessionKeyError, MixrPayError, type PaymentEvent, PaymentFailedError, SDK_VERSION, type SessionAuthorization, SessionExpiredError, SessionKeyExpiredError, SessionLimitExceededError, SessionNotFoundError, SessionRevokedError, type SessionStats, SpendingLimitExceededError, type SpendingStats, isMixrPayError };