@mixrpay/agent-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of @mixrpay/agent-sdk might be problematic. Click here for more details.

@@ -0,0 +1,961 @@
1
+ import { Hex } from 'viem';
2
+
3
+ /**
4
+ * MixrPay Agent SDK - Type definitions
5
+ *
6
+ * This file contains all TypeScript types and interfaces used throughout the SDK.
7
+ */
8
+ /**
9
+ * Configuration options for AgentWallet.
10
+ *
11
+ * @example Minimal configuration
12
+ * ```typescript
13
+ * const config: AgentWalletConfig = {
14
+ * sessionKey: 'sk_live_abc123...'
15
+ * };
16
+ * ```
17
+ *
18
+ * @example Full configuration
19
+ * ```typescript
20
+ * const config: AgentWalletConfig = {
21
+ * sessionKey: 'sk_live_abc123...',
22
+ * maxPaymentUsd: 5.0,
23
+ * onPayment: (p) => console.log(`Paid $${p.amountUsd}`),
24
+ * logLevel: 'info',
25
+ * timeout: 60000,
26
+ * };
27
+ * ```
28
+ */
29
+ interface AgentWalletConfig {
30
+ /**
31
+ * Session key granted by the wallet owner.
32
+ *
33
+ * Format: `sk_live_` (mainnet) or `sk_test_` (testnet) followed by 64 hex characters.
34
+ *
35
+ * Get session keys from:
36
+ * - The wallet owner's MixrPay dashboard
37
+ * - Programmatically via the MixrPay API
38
+ * - The MixrPay widget session key management
39
+ *
40
+ * @example 'sk_live_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'
41
+ */
42
+ sessionKey: string;
43
+ /**
44
+ * Optional smart wallet address.
45
+ *
46
+ * If not provided, will be derived from the session key.
47
+ * Only needed in advanced scenarios where the session key address
48
+ * differs from the wallet address.
49
+ */
50
+ walletAddress?: string;
51
+ /**
52
+ * Optional client-side maximum payment per request in USD.
53
+ *
54
+ * This is an additional safety limit on the client side, independent
55
+ * of the session key's limits. Useful for preventing accidental
56
+ * large payments due to bugs or misconfiguration.
57
+ *
58
+ * @example 5.0 - Maximum $5 per request
59
+ */
60
+ maxPaymentUsd?: number;
61
+ /**
62
+ * Optional callback when a payment is successfully made.
63
+ *
64
+ * Use this to track payments in your application, update UI,
65
+ * or log payment events.
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * onPayment: (payment) => {
70
+ * console.log(`Paid $${payment.amountUsd} for ${payment.description}`);
71
+ * analytics.track('payment', payment);
72
+ * }
73
+ * ```
74
+ */
75
+ onPayment?: (payment: PaymentEvent) => void;
76
+ /**
77
+ * x402 facilitator endpoint.
78
+ *
79
+ * The facilitator processes the payment and forwards the request.
80
+ * Default: 'https://x402.org/facilitator'
81
+ */
82
+ facilitatorUrl?: string;
83
+ /**
84
+ * MixrPay API base URL.
85
+ *
86
+ * Default: 'http://localhost:3000' (or MIXRPAY_BASE_URL env var)
87
+ */
88
+ baseUrl?: string;
89
+ /**
90
+ * Request timeout in milliseconds.
91
+ *
92
+ * Default: 30000 (30 seconds)
93
+ */
94
+ timeout?: number;
95
+ /**
96
+ * Log level for SDK operations.
97
+ *
98
+ * - 'debug': Verbose logging for development
99
+ * - 'info': Important events (payments, etc.)
100
+ * - 'warn': Warnings only
101
+ * - 'error': Errors only
102
+ * - 'none': No logging (default)
103
+ *
104
+ * @example 'info' - Log payments and important events
105
+ */
106
+ logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'none';
107
+ }
108
+ /**
109
+ * Record of a payment made by the SDK.
110
+ *
111
+ * This is emitted via the `onPayment` callback and stored in the payment history.
112
+ */
113
+ interface PaymentEvent {
114
+ /** Payment amount in USD */
115
+ amountUsd: number;
116
+ /** Recipient wallet address */
117
+ recipient: string;
118
+ /** Transaction hash on the blockchain (if available) */
119
+ txHash: string | null;
120
+ /** Timestamp when the payment was made */
121
+ timestamp: Date;
122
+ /** Description of what was paid for (from the server) */
123
+ description?: string;
124
+ /** URL that triggered the payment */
125
+ url?: string;
126
+ }
127
+ /**
128
+ * Payment requirements parsed from a 402 response.
129
+ *
130
+ * This represents what the server is asking for in exchange for the resource.
131
+ */
132
+ interface PaymentRequirements {
133
+ /** Address to send payment to */
134
+ recipient: string;
135
+ /** Amount in USDC minor units (6 decimals). 1000000 = $1.00 */
136
+ amount: bigint;
137
+ /** Currency code (currently only "USDC" is supported) */
138
+ currency: string;
139
+ /** Chain ID (8453 for Base mainnet, 84532 for Base Sepolia) */
140
+ chainId: number;
141
+ /** URL where the payment should be submitted */
142
+ facilitatorUrl: string;
143
+ /** Unique nonce for this payment request */
144
+ nonce: string;
145
+ /** Unix timestamp when this payment request expires */
146
+ expiresAt: number;
147
+ /** Human-readable description of the payment */
148
+ description?: string;
149
+ }
150
+ /**
151
+ * Information about a session key.
152
+ */
153
+ interface SessionKeyInfo {
154
+ /** The session key's address (derived public key) */
155
+ address: string;
156
+ /** Whether the session key is currently valid */
157
+ isValid: boolean;
158
+ /** Spending limits configured for this session key */
159
+ limits: {
160
+ /** Maximum amount per transaction in USD (null = no limit) */
161
+ perTxUsd: number | null;
162
+ /** Maximum amount per day in USD (null = no limit) */
163
+ dailyUsd: number | null;
164
+ /** Maximum total amount in USD (null = no limit) */
165
+ totalUsd: number | null;
166
+ };
167
+ /** Current usage statistics */
168
+ usage: {
169
+ /** Amount spent today in USD */
170
+ todayUsd: number;
171
+ /** Total amount spent in USD */
172
+ totalUsd: number;
173
+ /** Number of transactions made */
174
+ txCount: number;
175
+ };
176
+ /** When the session key expires (null = never) */
177
+ expiresAt: Date | null;
178
+ /** When the session key was created */
179
+ createdAt: Date | null;
180
+ /** Optional name given to this session key */
181
+ name?: string;
182
+ }
183
+ /**
184
+ * Spending statistics for the current session.
185
+ */
186
+ interface SpendingStats {
187
+ /** Total amount spent in USD during this session */
188
+ totalSpentUsd: number;
189
+ /** Number of payment transactions made */
190
+ txCount: number;
191
+ /** Remaining daily limit in USD (null if no limit or unknown) */
192
+ remainingDailyUsd: number | null;
193
+ /** Remaining total limit in USD (null if no limit or unknown) */
194
+ remainingTotalUsd: number | null;
195
+ /** When the session key expires (null if never or unknown) */
196
+ expiresAt: Date | null;
197
+ }
198
+ /**
199
+ * Result of running diagnostics on the wallet.
200
+ */
201
+ interface DiagnosticsResult {
202
+ /** Whether all checks passed */
203
+ healthy: boolean;
204
+ /** List of issues found (empty if healthy) */
205
+ issues: string[];
206
+ /** Individual check results */
207
+ checks: {
208
+ /** Session key format is valid */
209
+ sessionKeyFormat?: boolean;
210
+ /** Can connect to MixrPay API */
211
+ apiConnectivity?: boolean;
212
+ /** Session key is valid and not expired */
213
+ sessionKeyValid?: boolean;
214
+ /** Wallet has USDC balance */
215
+ hasBalance?: boolean;
216
+ };
217
+ /** SDK version */
218
+ sdkVersion: string;
219
+ /** Network name (Base or Base Sepolia) */
220
+ network: string;
221
+ /** Wallet address */
222
+ walletAddress: string;
223
+ }
224
+ /**
225
+ * The X-PAYMENT header payload structure.
226
+ *
227
+ * This is what gets base64-encoded and sent in the X-PAYMENT header.
228
+ */
229
+ interface X402PaymentPayload {
230
+ /** Protocol version (currently 1) */
231
+ x402Version: number;
232
+ /** Payment scheme ('exact' for USDC transfers) */
233
+ scheme: 'exact';
234
+ /** Network identifier */
235
+ network: 'base' | 'base-sepolia';
236
+ /** Payment payload containing signature and authorization */
237
+ payload: {
238
+ /** EIP-712 signature of the transferWithAuthorization */
239
+ signature: string;
240
+ /** TransferWithAuthorization parameters */
241
+ authorization: {
242
+ /** Sender address (smart wallet) */
243
+ from: string;
244
+ /** Recipient address */
245
+ to: string;
246
+ /** Amount in USDC minor units as string */
247
+ value: string;
248
+ /** Unix timestamp after which the authorization is valid */
249
+ validAfter: string;
250
+ /** Unix timestamp before which the authorization is valid */
251
+ validBefore: string;
252
+ /** Unique nonce (32 bytes hex) */
253
+ nonce: string;
254
+ };
255
+ };
256
+ }
257
+ /**
258
+ * EIP-712 domain for USDC transferWithAuthorization.
259
+ */
260
+ interface EIP712Domain {
261
+ /** Contract name ('USD Coin' for USDC) */
262
+ name: string;
263
+ /** Contract version ('2' for USDC) */
264
+ version: string;
265
+ /** Chain ID */
266
+ chainId: number;
267
+ /** USDC contract address */
268
+ verifyingContract: `0x${string}`;
269
+ }
270
+ /**
271
+ * EIP-3009 TransferWithAuthorization message structure.
272
+ */
273
+ interface TransferWithAuthorizationMessage {
274
+ /** Sender address */
275
+ from: `0x${string}`;
276
+ /** Recipient address */
277
+ to: `0x${string}`;
278
+ /** Amount in minor units */
279
+ value: bigint;
280
+ /** Unix timestamp after which the authorization is valid */
281
+ validAfter: bigint;
282
+ /** Unix timestamp before which the authorization is valid */
283
+ validBefore: bigint;
284
+ /** Unique nonce (32 bytes) */
285
+ nonce: `0x${string}`;
286
+ }
287
+ /**
288
+ * Response from the wallet balance endpoint.
289
+ */
290
+ interface WalletBalanceResponse {
291
+ /** Balance in USD */
292
+ balanceUsd: number;
293
+ /** Balance in USDC minor units as string */
294
+ balanceMinor: string;
295
+ /** Currency code */
296
+ currency: string;
297
+ /** Wallet address */
298
+ walletAddress: string;
299
+ }
300
+ /**
301
+ * Response from the session key stats endpoint.
302
+ */
303
+ interface SessionKeyStatsResponse {
304
+ /** Total spent in USD */
305
+ totalSpentUsd: number;
306
+ /** Number of transactions */
307
+ txCount: number;
308
+ /** Remaining daily limit in USD (null if no limit) */
309
+ remainingDailyUsd: number | null;
310
+ /** Remaining total limit in USD (null if no limit) */
311
+ remainingTotalUsd: number | null;
312
+ /** Expiration timestamp ISO string (null if never) */
313
+ expiresAt: string | null;
314
+ }
315
+
316
+ /**
317
+ * MixrPay Agent SDK - AgentWallet
318
+ *
319
+ * Main class for AI agents to make x402 payments. Provides a simple interface
320
+ * for making HTTP requests that automatically handle payments using session keys.
321
+ *
322
+ * @example Quick Start
323
+ * ```typescript
324
+ * import { AgentWallet } from '@mixrpay/agent-sdk';
325
+ *
326
+ * // Initialize with your session key
327
+ * const wallet = new AgentWallet({ sessionKey: 'sk_live_...' });
328
+ *
329
+ * // Make requests - payments handled automatically!
330
+ * const response = await wallet.fetch('https://api.example.com/ai/query', {
331
+ * method: 'POST',
332
+ * body: JSON.stringify({ prompt: 'Hello world' })
333
+ * });
334
+ *
335
+ * console.log(await response.json());
336
+ * ```
337
+ */
338
+
339
+ /** Current SDK version */
340
+ declare const SDK_VERSION = "0.1.0";
341
+ /** Default API base URL - override with baseUrl option or MIXRPAY_BASE_URL env var */
342
+ declare const DEFAULT_BASE_URL: string;
343
+ /** Default x402 facilitator URL */
344
+ declare const DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
345
+ /** Default request timeout in milliseconds */
346
+ declare const DEFAULT_TIMEOUT = 30000;
347
+ /** Supported networks */
348
+ declare const NETWORKS: {
349
+ readonly BASE_MAINNET: {
350
+ readonly chainId: 8453;
351
+ readonly name: "Base";
352
+ readonly isTestnet: false;
353
+ };
354
+ readonly BASE_SEPOLIA: {
355
+ readonly chainId: 84532;
356
+ readonly name: "Base Sepolia";
357
+ readonly isTestnet: true;
358
+ };
359
+ };
360
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';
361
+ /**
362
+ * A wallet wrapper for AI agents that handles x402 payments automatically.
363
+ *
364
+ * The AgentWallet makes it easy for AI agents to access paid APIs. When a server
365
+ * returns a 402 Payment Required response, the SDK automatically handles the payment
366
+ * using a session key and retries the request.
367
+ *
368
+ * ## Features
369
+ * - 🔐 **Secure**: Session keys have built-in spending limits
370
+ * - 🤖 **Agent-Ready**: Works with any AI framework (Vercel AI SDK, LangChain, etc.)
371
+ * - ⚡ **Automatic**: No manual payment handling needed
372
+ * - 📊 **Tracking**: Built-in spending statistics and payment history
373
+ * - 🔄 **Drop-in**: Uses the same interface as native `fetch()`
374
+ *
375
+ * ## Quick Start
376
+ *
377
+ * ```typescript
378
+ * const wallet = new AgentWallet({
379
+ * sessionKey: 'sk_live_...', // Get this from the wallet owner
380
+ * onPayment: (p) => console.log(`Paid $${p.amountUsd}`)
381
+ * });
382
+ *
383
+ * // Just use fetch() - payments are automatic!
384
+ * const response = await wallet.fetch('https://api.example.com/endpoint');
385
+ * ```
386
+ *
387
+ * ## Session Keys
388
+ *
389
+ * Session keys are granted by wallet owners and have spending limits:
390
+ * - **Per-transaction limit**: Maximum amount per single request
391
+ * - **Daily limit**: Maximum total per 24 hours
392
+ * - **Total limit**: Maximum lifetime spend
393
+ * - **Expiration**: When the key becomes invalid
394
+ *
395
+ * Keys are prefixed with `sk_live_` (mainnet) or `sk_test_` (testnet).
396
+ *
397
+ * @see {@link AgentWalletConfig} for configuration options
398
+ * @see {@link PaymentEvent} for payment tracking
399
+ */
400
+ declare class AgentWallet {
401
+ private readonly sessionKey;
402
+ private readonly walletAddress;
403
+ private readonly maxPaymentUsd?;
404
+ private readonly onPayment?;
405
+ private readonly baseUrl;
406
+ private readonly timeout;
407
+ private readonly logger;
408
+ private payments;
409
+ private totalSpentUsd;
410
+ private sessionKeyInfo?;
411
+ private sessionKeyInfoFetchedAt?;
412
+ /**
413
+ * Create a new AgentWallet instance.
414
+ *
415
+ * @param config - Configuration options
416
+ * @throws {InvalidSessionKeyError} If the session key format is invalid
417
+ *
418
+ * @example Basic initialization
419
+ * ```typescript
420
+ * const wallet = new AgentWallet({
421
+ * sessionKey: 'sk_live_abc123...'
422
+ * });
423
+ * ```
424
+ *
425
+ * @example With all options
426
+ * ```typescript
427
+ * const wallet = new AgentWallet({
428
+ * sessionKey: 'sk_live_abc123...',
429
+ * maxPaymentUsd: 5.0, // Client-side safety limit
430
+ * onPayment: (p) => log(p), // Track payments
431
+ * logLevel: 'info', // Enable logging
432
+ * timeout: 60000, // 60s timeout
433
+ * });
434
+ * ```
435
+ */
436
+ constructor(config: AgentWalletConfig);
437
+ /**
438
+ * Validate the configuration before initialization.
439
+ */
440
+ private validateConfig;
441
+ /**
442
+ * Make an HTTP request, automatically handling x402 payment if required.
443
+ *
444
+ * This is a drop-in replacement for the native `fetch()` function.
445
+ * If the server returns 402 Payment Required:
446
+ * 1. Parse payment requirements from response
447
+ * 2. Sign transferWithAuthorization using session key
448
+ * 3. Retry request with X-PAYMENT header
449
+ *
450
+ * @param url - Request URL
451
+ * @param init - Request options (same as native fetch)
452
+ * @returns Response from the server
453
+ *
454
+ * @throws {InsufficientBalanceError} If wallet doesn't have enough USDC
455
+ * @throws {SessionKeyExpiredError} If session key has expired
456
+ * @throws {SpendingLimitExceededError} If payment would exceed limits
457
+ * @throws {PaymentFailedError} If payment transaction failed
458
+ *
459
+ * @example GET request
460
+ * ```typescript
461
+ * const response = await wallet.fetch('https://api.example.com/data');
462
+ * const data = await response.json();
463
+ * ```
464
+ *
465
+ * @example POST request with JSON
466
+ * ```typescript
467
+ * const response = await wallet.fetch('https://api.example.com/generate', {
468
+ * method: 'POST',
469
+ * headers: { 'Content-Type': 'application/json' },
470
+ * body: JSON.stringify({ prompt: 'Hello world' })
471
+ * });
472
+ * ```
473
+ */
474
+ fetch(url: string, init?: RequestInit): Promise<Response>;
475
+ /**
476
+ * Handle a 402 Payment Required response.
477
+ */
478
+ private handlePaymentRequired;
479
+ /**
480
+ * Handle payment-specific errors from the response.
481
+ */
482
+ private handlePaymentError;
483
+ /**
484
+ * Get the wallet address.
485
+ *
486
+ * @returns The Ethereum address of the smart wallet
487
+ */
488
+ getWalletAddress(): `0x${string}`;
489
+ /**
490
+ * Check if using testnet session key.
491
+ *
492
+ * @returns true if using Base Sepolia (testnet), false if using Base Mainnet
493
+ */
494
+ isTestnet(): boolean;
495
+ /**
496
+ * Get the network information.
497
+ *
498
+ * @returns Network details including chain ID and name
499
+ */
500
+ getNetwork(): typeof NETWORKS.BASE_MAINNET | typeof NETWORKS.BASE_SEPOLIA;
501
+ /**
502
+ * Get current USDC balance of the wallet.
503
+ *
504
+ * @returns USDC balance in USD
505
+ *
506
+ * @example
507
+ * ```typescript
508
+ * const balance = await wallet.getBalance();
509
+ * console.log(`Balance: $${balance.toFixed(2)}`);
510
+ * ```
511
+ */
512
+ getBalance(): Promise<number>;
513
+ /**
514
+ * Get information about the session key.
515
+ *
516
+ * @param refresh - Force refresh from server (default: use cache if < 60s old)
517
+ * @returns Session key details including limits and expiration
518
+ *
519
+ * @example
520
+ * ```typescript
521
+ * const info = await wallet.getSessionKeyInfo();
522
+ * console.log(`Daily limit: $${info.limits.dailyUsd}`);
523
+ * console.log(`Expires: ${info.expiresAt}`);
524
+ * ```
525
+ */
526
+ getSessionKeyInfo(refresh?: boolean): Promise<SessionKeyInfo>;
527
+ /**
528
+ * Get spending stats for this session key.
529
+ *
530
+ * @returns Spending statistics
531
+ *
532
+ * @example
533
+ * ```typescript
534
+ * const stats = await wallet.getSpendingStats();
535
+ * console.log(`Spent: $${stats.totalSpentUsd.toFixed(2)}`);
536
+ * console.log(`Remaining daily: $${stats.remainingDailyUsd?.toFixed(2) ?? 'unlimited'}`);
537
+ * ```
538
+ */
539
+ getSpendingStats(): Promise<SpendingStats>;
540
+ /**
541
+ * Get list of payments made in this session.
542
+ *
543
+ * @returns Array of payment events
544
+ */
545
+ getPaymentHistory(): PaymentEvent[];
546
+ /**
547
+ * Get the total amount spent in this session.
548
+ *
549
+ * @returns Total spent in USD
550
+ */
551
+ getTotalSpent(): number;
552
+ /**
553
+ * Run diagnostics to verify the wallet is properly configured.
554
+ *
555
+ * This is useful for debugging integration issues.
556
+ *
557
+ * @returns Diagnostic results with status and any issues found
558
+ *
559
+ * @example
560
+ * ```typescript
561
+ * const diagnostics = await wallet.runDiagnostics();
562
+ * if (diagnostics.healthy) {
563
+ * console.log('✅ Wallet is ready to use');
564
+ * } else {
565
+ * console.log('❌ Issues found:');
566
+ * diagnostics.issues.forEach(issue => console.log(` - ${issue}`));
567
+ * }
568
+ * ```
569
+ */
570
+ runDiagnostics(): Promise<DiagnosticsResult>;
571
+ /**
572
+ * Enable or disable debug logging.
573
+ *
574
+ * @param enable - true to enable debug logging, false to disable
575
+ *
576
+ * @example
577
+ * ```typescript
578
+ * wallet.setDebug(true); // Enable detailed logs
579
+ * await wallet.fetch(...);
580
+ * wallet.setDebug(false); // Disable logs
581
+ * ```
582
+ */
583
+ setDebug(enable: boolean): void;
584
+ /**
585
+ * Set the log level.
586
+ *
587
+ * @param level - 'debug' | 'info' | 'warn' | 'error' | 'none'
588
+ */
589
+ setLogLevel(level: LogLevel): void;
590
+ }
591
+
592
+ /**
593
+ * MixrPay Agent SDK - Custom Errors
594
+ *
595
+ * These errors provide clear, actionable messages for common x402 payment failures.
596
+ * Each error includes:
597
+ * - A clear description of what went wrong
598
+ * - Relevant data for programmatic handling
599
+ * - Suggestions for how to fix the issue
600
+ *
601
+ * @example Handling errors
602
+ * ```typescript
603
+ * try {
604
+ * await wallet.fetch('https://api.example.com/query');
605
+ * } catch (error) {
606
+ * if (error instanceof InsufficientBalanceError) {
607
+ * console.log(`Need $${error.required}, have $${error.available}`);
608
+ * console.log('Top up at:', error.topUpUrl);
609
+ * }
610
+ * }
611
+ * ```
612
+ */
613
+ /**
614
+ * Base error class for all MixrPay SDK errors.
615
+ *
616
+ * All SDK errors extend this class, making it easy to catch all MixrPay-related
617
+ * errors in a single catch block.
618
+ *
619
+ * @example
620
+ * ```typescript
621
+ * try {
622
+ * await wallet.fetch(...);
623
+ * } catch (error) {
624
+ * if (error instanceof MixrPayError) {
625
+ * // Handle any MixrPay error
626
+ * console.log(error.message);
627
+ * }
628
+ * }
629
+ * ```
630
+ */
631
+ declare class MixrPayError extends Error {
632
+ /** Error code for programmatic handling */
633
+ readonly code: string;
634
+ constructor(message: string, code?: string);
635
+ }
636
+ /**
637
+ * Thrown when the wallet doesn't have enough USDC for the payment.
638
+ *
639
+ * This error indicates the smart wallet needs to be topped up with more USDC.
640
+ *
641
+ * ## Resolution
642
+ * 1. Direct the user to top up their wallet
643
+ * 2. Use a smaller transaction (if possible)
644
+ * 3. Wait for pending deposits to confirm
645
+ *
646
+ * @example
647
+ * ```typescript
648
+ * catch (error) {
649
+ * if (error instanceof InsufficientBalanceError) {
650
+ * console.log(`Need $${error.required.toFixed(2)}, have $${error.available.toFixed(2)}`);
651
+ * console.log(`Top up at: ${error.topUpUrl}`);
652
+ * }
653
+ * }
654
+ * ```
655
+ */
656
+ declare class InsufficientBalanceError extends MixrPayError {
657
+ /** Amount required for the payment in USD */
658
+ readonly required: number;
659
+ /** Current available balance in USD */
660
+ readonly available: number;
661
+ /** URL where the user can top up their wallet */
662
+ readonly topUpUrl: string;
663
+ constructor(required: number, available: number);
664
+ }
665
+ /**
666
+ * Thrown when the session key has expired.
667
+ *
668
+ * Session keys have an expiration date set by the wallet owner. Once expired,
669
+ * the key can no longer authorize payments.
670
+ *
671
+ * ## Resolution
672
+ * 1. Request a new session key from the wallet owner
673
+ * 2. Create a new session key (if you have wallet access)
674
+ *
675
+ * @example
676
+ * ```typescript
677
+ * catch (error) {
678
+ * if (error instanceof SessionKeyExpiredError) {
679
+ * console.log(`Session key expired at ${error.expiredAt}`);
680
+ * // Request new key from wallet owner
681
+ * }
682
+ * }
683
+ * ```
684
+ */
685
+ declare class SessionKeyExpiredError extends MixrPayError {
686
+ /** When the session key expired */
687
+ readonly expiredAt: string;
688
+ constructor(expiredAt: string);
689
+ }
690
+ /**
691
+ * Thrown when a payment would exceed session key spending limits.
692
+ *
693
+ * Session keys can have three types of limits:
694
+ * - **per_tx**: Maximum per single transaction
695
+ * - **daily**: Maximum total per 24-hour period
696
+ * - **total**: Maximum lifetime spend
697
+ * - **client_max**: Client-side limit set in AgentWalletConfig
698
+ *
699
+ * ## Resolution
700
+ * - **per_tx**: Use a smaller transaction or request higher limit
701
+ * - **daily**: Wait until tomorrow or request higher limit
702
+ * - **total**: Request a new session key with higher limit
703
+ * - **client_max**: Increase maxPaymentUsd in config or remove it
704
+ *
705
+ * @example
706
+ * ```typescript
707
+ * catch (error) {
708
+ * if (error instanceof SpendingLimitExceededError) {
709
+ * if (error.limitType === 'daily') {
710
+ * console.log('Daily limit reached. Try again tomorrow.');
711
+ * } else if (error.limitType === 'per_tx') {
712
+ * console.log(`Max per transaction is $${error.limit}`);
713
+ * }
714
+ * }
715
+ * }
716
+ * ```
717
+ */
718
+ declare class SpendingLimitExceededError extends MixrPayError {
719
+ /** Type of limit that was exceeded */
720
+ readonly limitType: 'per_tx' | 'daily' | 'total' | 'client_max' | string;
721
+ /** The limit amount in USD */
722
+ readonly limit: number;
723
+ /** The amount that was attempted in USD */
724
+ readonly attempted: number;
725
+ constructor(limitType: string, limit: number, attempted: number);
726
+ }
727
+ /**
728
+ * Thrown when a payment transaction fails.
729
+ *
730
+ * This is a general error for payment failures that don't fit other categories.
731
+ * Check the `reason` property for more details.
732
+ *
733
+ * ## Common Causes
734
+ * - Network issues
735
+ * - Invalid payment parameters
736
+ * - Server-side errors
737
+ * - Blockchain congestion
738
+ *
739
+ * @example
740
+ * ```typescript
741
+ * catch (error) {
742
+ * if (error instanceof PaymentFailedError) {
743
+ * console.log(`Payment failed: ${error.reason}`);
744
+ * if (error.txHash) {
745
+ * console.log(`Check transaction: https://basescan.org/tx/${error.txHash}`);
746
+ * }
747
+ * }
748
+ * }
749
+ * ```
750
+ */
751
+ declare class PaymentFailedError extends MixrPayError {
752
+ /** Detailed reason for the failure */
753
+ readonly reason: string;
754
+ /** Transaction hash if the tx was submitted (for debugging) */
755
+ readonly txHash?: string;
756
+ constructor(reason: string, txHash?: string);
757
+ }
758
+ /**
759
+ * Thrown when the session key format is invalid.
760
+ *
761
+ * Session keys must:
762
+ * - Start with `sk_live_` (mainnet) or `sk_test_` (testnet)
763
+ * - Be followed by exactly 64 hexadecimal characters
764
+ * - Total length: 72 characters
765
+ *
766
+ * ## Common Issues
767
+ * - Incomplete copy/paste
768
+ * - Extra whitespace
769
+ * - Using API key instead of session key
770
+ * - Using public key instead of private key
771
+ *
772
+ * @example
773
+ * ```typescript
774
+ * catch (error) {
775
+ * if (error instanceof InvalidSessionKeyError) {
776
+ * console.log(`Invalid key: ${error.reason}`);
777
+ * console.log('Get a valid session key from your MixrPay server /wallet/sessions');
778
+ * }
779
+ * }
780
+ * ```
781
+ */
782
+ declare class InvalidSessionKeyError extends MixrPayError {
783
+ /** Detailed reason why the key is invalid */
784
+ readonly reason: string;
785
+ constructor(reason?: string);
786
+ }
787
+ /**
788
+ * Thrown when there's an error in x402 protocol handling.
789
+ *
790
+ * This indicates a problem with the payment protocol, usually due to:
791
+ * - Malformed 402 response from server
792
+ * - Missing required payment fields
793
+ * - Invalid payment parameters
794
+ * - Protocol version mismatch
795
+ *
796
+ * ## Resolution
797
+ * This is usually a server-side issue. Contact the API provider if the error persists.
798
+ *
799
+ * @example
800
+ * ```typescript
801
+ * catch (error) {
802
+ * if (error instanceof X402ProtocolError) {
803
+ * console.log(`Protocol error: ${error.reason}`);
804
+ * // Contact API provider or check server configuration
805
+ * }
806
+ * }
807
+ * ```
808
+ */
809
+ declare class X402ProtocolError extends MixrPayError {
810
+ /** Detailed reason for the protocol error */
811
+ readonly reason: string;
812
+ constructor(reason: string);
813
+ }
814
+ /**
815
+ * Check if an error is a MixrPay SDK error.
816
+ *
817
+ * @param error - The error to check
818
+ * @returns true if the error is a MixrPayError or subclass
819
+ *
820
+ * @example
821
+ * ```typescript
822
+ * try {
823
+ * await wallet.fetch(...);
824
+ * } catch (error) {
825
+ * if (isMixrPayError(error)) {
826
+ * console.log('MixrPay error:', error.code, error.message);
827
+ * } else {
828
+ * console.log('Other error:', error);
829
+ * }
830
+ * }
831
+ * ```
832
+ */
833
+ declare function isMixrPayError(error: unknown): error is MixrPayError;
834
+ /**
835
+ * Get a user-friendly error message from any error.
836
+ *
837
+ * @param error - The error to get a message from
838
+ * @returns A user-friendly error message
839
+ *
840
+ * @example
841
+ * ```typescript
842
+ * catch (error) {
843
+ * const message = getErrorMessage(error);
844
+ * showToast(message);
845
+ * }
846
+ * ```
847
+ */
848
+ declare function getErrorMessage(error: unknown): string;
849
+
850
+ /**
851
+ * MixrPay Agent SDK - Session Key Handling
852
+ *
853
+ * Session keys are derived private keys with on-chain spending limits that enable
854
+ * AI agents to sign USDC transferWithAuthorization transactions autonomously.
855
+ */
856
+
857
+ /**
858
+ * Represents a session key for signing x402 payments.
859
+ *
860
+ * The session key format is: sk_live_{64_hex_chars} or sk_test_{64_hex_chars}
861
+ */
862
+ declare class SessionKey {
863
+ private readonly privateKey;
864
+ private readonly account;
865
+ readonly address: `0x${string}`;
866
+ readonly isTest: boolean;
867
+ private constructor();
868
+ /**
869
+ * Parse a session key string into a SessionKey object.
870
+ *
871
+ * @param sessionKey - Session key in format sk_live_... or sk_test_...
872
+ * @returns SessionKey object
873
+ * @throws InvalidSessionKeyError if the format is invalid
874
+ */
875
+ static fromString(sessionKey: string): SessionKey;
876
+ /**
877
+ * Sign EIP-712 typed data for TransferWithAuthorization.
878
+ *
879
+ * @param domain - EIP-712 domain
880
+ * @param message - Transfer authorization message
881
+ * @returns Hex-encoded signature
882
+ */
883
+ signTransferAuthorization(domain: EIP712Domain, message: TransferWithAuthorizationMessage): Promise<Hex>;
884
+ /**
885
+ * Get the chain ID based on whether this is a test key.
886
+ */
887
+ getDefaultChainId(): number;
888
+ }
889
+ /**
890
+ * Build EIP-712 typed data for USDC transferWithAuthorization (EIP-3009).
891
+ *
892
+ * @param params - Parameters for the transfer authorization
893
+ * @returns Domain and message for EIP-712 signing
894
+ */
895
+ declare function buildTransferAuthorizationData(params: {
896
+ fromAddress: `0x${string}`;
897
+ toAddress: `0x${string}`;
898
+ value: bigint;
899
+ validAfter: bigint;
900
+ validBefore: bigint;
901
+ nonce: Hex;
902
+ chainId: number;
903
+ }): {
904
+ domain: EIP712Domain;
905
+ message: TransferWithAuthorizationMessage;
906
+ };
907
+ /**
908
+ * Generate a random 32-byte nonce as hex.
909
+ */
910
+ declare function generateNonce(): Hex;
911
+
912
+ /**
913
+ * MixrPay Agent SDK - x402 Protocol Handling
914
+ *
915
+ * The x402 protocol enables HTTP-native payments. When a server returns a 402 Payment
916
+ * Required response, the client can automatically fulfill the payment and retry.
917
+ */
918
+
919
+ /**
920
+ * Parse payment requirements from a 402 response.
921
+ *
922
+ * The 402 response can include payment requirements in:
923
+ * 1. X-Payment-Required header (JSON)
924
+ * 2. WWW-Authenticate header (per x402 spec)
925
+ * 3. Response body (JSON)
926
+ *
927
+ * @param response - The HTTP response with status 402
928
+ * @returns Parsed payment requirements
929
+ * @throws X402ProtocolError if requirements cannot be parsed
930
+ */
931
+ declare function parse402Response(response: Response): Promise<PaymentRequirements>;
932
+ /**
933
+ * Build the X-PAYMENT header value for a payment request.
934
+ *
935
+ * This creates an EIP-3009 transferWithAuthorization, signs it with the session key,
936
+ * and encodes it for the X-PAYMENT header.
937
+ *
938
+ * @param requirements - Payment requirements from the 402 response
939
+ * @param sessionKey - Session key to sign the payment
940
+ * @param walletAddress - The smart wallet address that holds USDC
941
+ * @returns Base64-encoded JSON string for the X-PAYMENT header
942
+ */
943
+ declare function buildXPaymentHeader(requirements: PaymentRequirements, sessionKey: SessionKey, walletAddress: `0x${string}`): Promise<string>;
944
+ /**
945
+ * Check if payment requirements have expired.
946
+ */
947
+ declare function isPaymentExpired(requirements: PaymentRequirements): boolean;
948
+ /**
949
+ * Get payment amount in USD (USDC has 6 decimals).
950
+ */
951
+ declare function getAmountUsd(requirements: PaymentRequirements): number;
952
+ /**
953
+ * Validate that a payment amount is within acceptable limits.
954
+ *
955
+ * @param amountUsd - Payment amount in USD
956
+ * @param maxPaymentUsd - Optional client-side maximum per payment
957
+ * @throws X402ProtocolError if the amount exceeds limits
958
+ */
959
+ declare function validatePaymentAmount(amountUsd: number, maxPaymentUsd?: number): void;
960
+
961
+ export { AgentWallet, type AgentWalletConfig, DEFAULT_BASE_URL, DEFAULT_FACILITATOR_URL, DEFAULT_TIMEOUT, type DiagnosticsResult, InsufficientBalanceError, InvalidSessionKeyError, MixrPayError, NETWORKS, type PaymentEvent, PaymentFailedError, type PaymentRequirements, SDK_VERSION, SessionKey, SessionKeyExpiredError, type SessionKeyInfo, type SessionKeyStatsResponse, SpendingLimitExceededError, type SpendingStats, type WalletBalanceResponse, type X402PaymentPayload, X402ProtocolError, buildTransferAuthorizationData, buildXPaymentHeader, generateNonce, getAmountUsd, getErrorMessage, isMixrPayError, isPaymentExpired, parse402Response, validatePaymentAmount };