@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.
package/dist/index.js ADDED
@@ -0,0 +1,1985 @@
1
+ // src/session-key.ts
2
+ import {
3
+ privateKeyToAccount,
4
+ signTypedData,
5
+ signMessage as viemSignMessage
6
+ } from "viem/accounts";
7
+
8
+ // src/errors.ts
9
+ var MixrPayError = class extends Error {
10
+ /** Error code for programmatic handling */
11
+ code;
12
+ constructor(message, code = "MIXRPAY_ERROR") {
13
+ super(message);
14
+ this.name = "MixrPayError";
15
+ this.code = code;
16
+ if (Error.captureStackTrace) {
17
+ Error.captureStackTrace(this, this.constructor);
18
+ }
19
+ }
20
+ };
21
+ var InsufficientBalanceError = class extends MixrPayError {
22
+ /** Amount required for the payment in USD */
23
+ required;
24
+ /** Current available balance in USD */
25
+ available;
26
+ /** URL where the user can top up their wallet */
27
+ topUpUrl;
28
+ constructor(required, available) {
29
+ const shortage = required - available;
30
+ super(
31
+ `Insufficient balance: need $${required.toFixed(2)}, have $${available.toFixed(2)} (short $${shortage.toFixed(2)}). Top up your wallet to continue.`,
32
+ "INSUFFICIENT_BALANCE"
33
+ );
34
+ this.name = "InsufficientBalanceError";
35
+ this.required = required;
36
+ this.available = available;
37
+ this.topUpUrl = "/wallet";
38
+ }
39
+ };
40
+ var SessionKeyExpiredError = class extends MixrPayError {
41
+ /** When the session key expired */
42
+ expiredAt;
43
+ constructor(expiredAt) {
44
+ super(
45
+ `Session key expired at ${expiredAt}. Request a new session key from the wallet owner or create one at your MixrPay server /wallet/sessions`,
46
+ "SESSION_KEY_EXPIRED"
47
+ );
48
+ this.name = "SessionKeyExpiredError";
49
+ this.expiredAt = expiredAt;
50
+ }
51
+ };
52
+ var SpendingLimitExceededError = class extends MixrPayError {
53
+ /** Type of limit that was exceeded */
54
+ limitType;
55
+ /** The limit amount in USD */
56
+ limit;
57
+ /** The amount that was attempted in USD */
58
+ attempted;
59
+ constructor(limitType, limit, attempted) {
60
+ const limitNames = {
61
+ per_tx: "Per-transaction",
62
+ daily: "Daily",
63
+ total: "Total",
64
+ client_max: "Client-side"
65
+ };
66
+ const limitName = limitNames[limitType] || limitType;
67
+ const suggestion = limitType === "daily" ? "Wait until tomorrow or request a higher limit." : limitType === "client_max" ? "Increase maxPaymentUsd in your AgentWallet configuration." : "Request a new session key with a higher limit.";
68
+ super(
69
+ `${limitName} spending limit exceeded: limit is $${limit.toFixed(2)}, attempted $${attempted.toFixed(2)}. ${suggestion}`,
70
+ "SPENDING_LIMIT_EXCEEDED"
71
+ );
72
+ this.name = "SpendingLimitExceededError";
73
+ this.limitType = limitType;
74
+ this.limit = limit;
75
+ this.attempted = attempted;
76
+ }
77
+ };
78
+ var PaymentFailedError = class extends MixrPayError {
79
+ /** Detailed reason for the failure */
80
+ reason;
81
+ /** Transaction hash if the tx was submitted (for debugging) */
82
+ txHash;
83
+ constructor(reason, txHash) {
84
+ let message = `Payment failed: ${reason}`;
85
+ if (txHash) {
86
+ message += ` (tx: ${txHash} - check on basescan.org)`;
87
+ }
88
+ super(message, "PAYMENT_FAILED");
89
+ this.name = "PaymentFailedError";
90
+ this.reason = reason;
91
+ this.txHash = txHash;
92
+ }
93
+ };
94
+ var InvalidSessionKeyError = class extends MixrPayError {
95
+ /** Detailed reason why the key is invalid */
96
+ reason;
97
+ constructor(reason = "Invalid session key format") {
98
+ super(
99
+ `${reason}. Session keys should be in format: sk_live_<64 hex chars> or sk_test_<64 hex chars>. Get one from your MixrPay server /wallet/sessions`,
100
+ "INVALID_SESSION_KEY"
101
+ );
102
+ this.name = "InvalidSessionKeyError";
103
+ this.reason = reason;
104
+ }
105
+ };
106
+ var X402ProtocolError = class extends MixrPayError {
107
+ /** Detailed reason for the protocol error */
108
+ reason;
109
+ constructor(reason) {
110
+ super(
111
+ `x402 protocol error: ${reason}. This may indicate a server configuration issue. If the problem persists, contact the API provider.`,
112
+ "X402_PROTOCOL_ERROR"
113
+ );
114
+ this.name = "X402ProtocolError";
115
+ this.reason = reason;
116
+ }
117
+ };
118
+ var SessionExpiredError = class extends MixrPayError {
119
+ /** ID of the expired session */
120
+ sessionId;
121
+ /** When the session expired (ISO string or Date) */
122
+ expiredAt;
123
+ constructor(sessionId, expiredAt) {
124
+ super(
125
+ `Session ${sessionId} has expired${expiredAt ? ` at ${expiredAt}` : ""}. A new session will be created automatically on your next request.`,
126
+ "SESSION_EXPIRED"
127
+ );
128
+ this.name = "SessionExpiredError";
129
+ this.sessionId = sessionId;
130
+ this.expiredAt = expiredAt;
131
+ }
132
+ };
133
+ var SessionLimitExceededError = class extends MixrPayError {
134
+ /** ID of the session */
135
+ sessionId;
136
+ /** The session's spending limit in USD */
137
+ limit;
138
+ /** The amount requested in USD */
139
+ requested;
140
+ /** Remaining balance in the session (limit - used) */
141
+ remaining;
142
+ constructor(limit, requested, remaining, sessionId) {
143
+ super(
144
+ `Session spending limit exceeded: limit is $${limit.toFixed(2)}, requested $${requested.toFixed(2)}, remaining $${remaining.toFixed(2)}. Create a new session with a higher limit to continue.`,
145
+ "SESSION_LIMIT_EXCEEDED"
146
+ );
147
+ this.name = "SessionLimitExceededError";
148
+ this.sessionId = sessionId;
149
+ this.limit = limit;
150
+ this.requested = requested;
151
+ this.remaining = remaining;
152
+ }
153
+ };
154
+ var SessionNotFoundError = class extends MixrPayError {
155
+ /** The session ID that was not found */
156
+ sessionId;
157
+ constructor(sessionId) {
158
+ super(
159
+ `Session ${sessionId} not found. It may have been deleted or never existed. Create a new session with getOrCreateSession().`,
160
+ "SESSION_NOT_FOUND"
161
+ );
162
+ this.name = "SessionNotFoundError";
163
+ this.sessionId = sessionId;
164
+ }
165
+ };
166
+ var SessionRevokedError = class extends MixrPayError {
167
+ /** The session ID that was revoked */
168
+ sessionId;
169
+ /** Optional reason for revocation */
170
+ reason;
171
+ constructor(sessionId, reason) {
172
+ super(
173
+ `Session ${sessionId} has been revoked${reason ? `: ${reason}` : ""}. Create a new session with getOrCreateSession().`,
174
+ "SESSION_REVOKED"
175
+ );
176
+ this.name = "SessionRevokedError";
177
+ this.sessionId = sessionId;
178
+ this.reason = reason;
179
+ }
180
+ };
181
+ function isMixrPayError(error) {
182
+ return error instanceof MixrPayError;
183
+ }
184
+
185
+ // src/session-key.ts
186
+ var USDC_ADDRESSES = {
187
+ 8453: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
188
+ // Base Mainnet
189
+ 84532: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
190
+ // Base Sepolia
191
+ };
192
+ var USDC_EIP712_DOMAIN_BASE = {
193
+ name: "USD Coin",
194
+ version: "2"
195
+ };
196
+ var TRANSFER_WITH_AUTHORIZATION_TYPES = {
197
+ TransferWithAuthorization: [
198
+ { name: "from", type: "address" },
199
+ { name: "to", type: "address" },
200
+ { name: "value", type: "uint256" },
201
+ { name: "validAfter", type: "uint256" },
202
+ { name: "validBefore", type: "uint256" },
203
+ { name: "nonce", type: "bytes32" }
204
+ ]
205
+ };
206
+ var SessionKey = class _SessionKey {
207
+ privateKey;
208
+ account;
209
+ address;
210
+ isTest;
211
+ constructor(privateKey, isTest) {
212
+ this.privateKey = privateKey;
213
+ this.account = privateKeyToAccount(privateKey);
214
+ this.address = this.account.address;
215
+ this.isTest = isTest;
216
+ }
217
+ /**
218
+ * Get the private key as hex string (without 0x prefix).
219
+ * Used for API authentication headers.
220
+ */
221
+ get privateKeyHex() {
222
+ return this.privateKey.slice(2);
223
+ }
224
+ /**
225
+ * Parse a session key string into a SessionKey object.
226
+ *
227
+ * @param sessionKey - Session key in format sk_live_... or sk_test_...
228
+ * @returns SessionKey object
229
+ * @throws InvalidSessionKeyError if the format is invalid
230
+ */
231
+ static fromString(sessionKey) {
232
+ const pattern = /^sk_(live|test)_([a-fA-F0-9]{64})$/;
233
+ const match = sessionKey.match(pattern);
234
+ if (!match) {
235
+ throw new InvalidSessionKeyError(
236
+ "Session key must be in format sk_live_{64_hex} or sk_test_{64_hex}"
237
+ );
238
+ }
239
+ const env = match[1];
240
+ const hexKey = match[2];
241
+ try {
242
+ const privateKey = `0x${hexKey}`;
243
+ return new _SessionKey(privateKey, env === "test");
244
+ } catch (e) {
245
+ throw new InvalidSessionKeyError(`Failed to decode session key: ${e}`);
246
+ }
247
+ }
248
+ /**
249
+ * Sign EIP-712 typed data for TransferWithAuthorization.
250
+ *
251
+ * @param domain - EIP-712 domain
252
+ * @param message - Transfer authorization message
253
+ * @returns Hex-encoded signature
254
+ */
255
+ async signTransferAuthorization(domain, message) {
256
+ return signTypedData({
257
+ privateKey: this.privateKey,
258
+ domain,
259
+ types: TRANSFER_WITH_AUTHORIZATION_TYPES,
260
+ primaryType: "TransferWithAuthorization",
261
+ message
262
+ });
263
+ }
264
+ /**
265
+ * Sign a plain message (EIP-191 personal sign).
266
+ *
267
+ * @param message - Message to sign
268
+ * @returns Hex-encoded signature
269
+ */
270
+ async signMessage(message) {
271
+ return viemSignMessage({
272
+ privateKey: this.privateKey,
273
+ message
274
+ });
275
+ }
276
+ /**
277
+ * Get the chain ID based on whether this is a test key.
278
+ */
279
+ getDefaultChainId() {
280
+ return this.isTest ? 84532 : 8453;
281
+ }
282
+ };
283
+ function buildTransferAuthorizationData(params) {
284
+ const usdcAddress = USDC_ADDRESSES[params.chainId];
285
+ if (!usdcAddress) {
286
+ throw new Error(`USDC not supported on chain ${params.chainId}`);
287
+ }
288
+ const domain = {
289
+ ...USDC_EIP712_DOMAIN_BASE,
290
+ chainId: params.chainId,
291
+ verifyingContract: usdcAddress
292
+ };
293
+ const message = {
294
+ from: params.fromAddress,
295
+ to: params.toAddress,
296
+ value: params.value,
297
+ validAfter: params.validAfter,
298
+ validBefore: params.validBefore,
299
+ nonce: params.nonce
300
+ };
301
+ return { domain, message };
302
+ }
303
+ function generateNonce() {
304
+ const bytes = new Uint8Array(32);
305
+ crypto.getRandomValues(bytes);
306
+ return `0x${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
307
+ }
308
+ function buildSessionAuthMessage(timestamp, address) {
309
+ return `MixrPay:${timestamp}:${address.toLowerCase()}`;
310
+ }
311
+ async function createSessionAuthPayload(sessionKey) {
312
+ const timestamp = Date.now();
313
+ const message = buildSessionAuthMessage(timestamp, sessionKey.address);
314
+ const signature = await sessionKey.signMessage(message);
315
+ return {
316
+ address: sessionKey.address,
317
+ timestamp,
318
+ signature
319
+ };
320
+ }
321
+
322
+ // src/x402.ts
323
+ async function parse402Response(response) {
324
+ let paymentData = null;
325
+ const paymentHeader = response.headers.get("X-Payment-Required");
326
+ if (paymentHeader) {
327
+ try {
328
+ paymentData = JSON.parse(paymentHeader);
329
+ } catch {
330
+ }
331
+ }
332
+ if (!paymentData) {
333
+ const authHeader = response.headers.get("WWW-Authenticate");
334
+ if (authHeader?.startsWith("X-402 ")) {
335
+ try {
336
+ const encoded = authHeader.slice(6);
337
+ paymentData = JSON.parse(atob(encoded));
338
+ } catch {
339
+ }
340
+ }
341
+ }
342
+ if (!paymentData) {
343
+ try {
344
+ paymentData = await response.json();
345
+ } catch {
346
+ }
347
+ }
348
+ if (!paymentData) {
349
+ throw new X402ProtocolError("Could not parse payment requirements from 402 response");
350
+ }
351
+ if (!paymentData.recipient) {
352
+ throw new X402ProtocolError("Missing recipient in payment requirements");
353
+ }
354
+ if (!paymentData.amount) {
355
+ throw new X402ProtocolError("Missing amount in payment requirements");
356
+ }
357
+ const now = Math.floor(Date.now() / 1e3);
358
+ return {
359
+ recipient: paymentData.recipient,
360
+ amount: BigInt(paymentData.amount),
361
+ currency: paymentData.currency || "USDC",
362
+ chainId: paymentData.chainId || paymentData.chain_id || 8453,
363
+ facilitatorUrl: paymentData.facilitatorUrl || paymentData.facilitator_url || "https://x402.org/facilitator",
364
+ nonce: paymentData.nonce || generateNonce().slice(2),
365
+ // Remove 0x prefix for storage
366
+ expiresAt: paymentData.expiresAt || paymentData.expires_at || now + 300,
367
+ description: paymentData.description
368
+ };
369
+ }
370
+ async function buildXPaymentHeader(requirements, sessionKey, walletAddress) {
371
+ const nonceHex = requirements.nonce.length === 64 ? `0x${requirements.nonce}` : generateNonce();
372
+ const now = BigInt(Math.floor(Date.now() / 1e3));
373
+ const validAfter = now - 60n;
374
+ const validBefore = BigInt(requirements.expiresAt);
375
+ const { domain, message } = buildTransferAuthorizationData({
376
+ fromAddress: walletAddress,
377
+ toAddress: requirements.recipient,
378
+ value: requirements.amount,
379
+ validAfter,
380
+ validBefore,
381
+ nonce: nonceHex,
382
+ chainId: requirements.chainId
383
+ });
384
+ const signature = await sessionKey.signTransferAuthorization(domain, message);
385
+ const paymentPayload = {
386
+ x402Version: 1,
387
+ scheme: "exact",
388
+ network: requirements.chainId === 8453 ? "base" : "base-sepolia",
389
+ payload: {
390
+ signature,
391
+ authorization: {
392
+ from: walletAddress,
393
+ to: requirements.recipient,
394
+ value: requirements.amount.toString(),
395
+ validAfter: validAfter.toString(),
396
+ validBefore: validBefore.toString(),
397
+ nonce: nonceHex
398
+ }
399
+ }
400
+ };
401
+ return btoa(JSON.stringify(paymentPayload));
402
+ }
403
+ function isPaymentExpired(requirements) {
404
+ return Date.now() / 1e3 > requirements.expiresAt;
405
+ }
406
+ function getAmountUsd(requirements) {
407
+ return Number(requirements.amount) / 1e6;
408
+ }
409
+
410
+ // src/agent-wallet.ts
411
+ var SDK_VERSION = "0.4.1";
412
+ var DEFAULT_BASE_URL = process.env.MIXRPAY_BASE_URL || "https://www.mixrpay.com";
413
+ var DEFAULT_TIMEOUT = 3e4;
414
+ var NETWORKS = {
415
+ BASE_MAINNET: { chainId: 8453, name: "Base", isTestnet: false },
416
+ BASE_SEPOLIA: { chainId: 84532, name: "Base Sepolia", isTestnet: true }
417
+ };
418
+ var LOG_LEVELS = {
419
+ debug: 0,
420
+ info: 1,
421
+ warn: 2,
422
+ error: 3,
423
+ none: 4
424
+ };
425
+ var Logger = class {
426
+ level;
427
+ prefix;
428
+ constructor(level = "none", prefix = "[MixrPay]") {
429
+ this.level = level;
430
+ this.prefix = prefix;
431
+ }
432
+ setLevel(level) {
433
+ this.level = level;
434
+ }
435
+ shouldLog(level) {
436
+ return LOG_LEVELS[level] >= LOG_LEVELS[this.level];
437
+ }
438
+ debug(...args) {
439
+ if (this.shouldLog("debug")) {
440
+ console.log(`${this.prefix} \u{1F50D}`, ...args);
441
+ }
442
+ }
443
+ info(...args) {
444
+ if (this.shouldLog("info")) {
445
+ console.log(`${this.prefix} \u2139\uFE0F`, ...args);
446
+ }
447
+ }
448
+ warn(...args) {
449
+ if (this.shouldLog("warn")) {
450
+ console.warn(`${this.prefix} \u26A0\uFE0F`, ...args);
451
+ }
452
+ }
453
+ error(...args) {
454
+ if (this.shouldLog("error")) {
455
+ console.error(`${this.prefix} \u274C`, ...args);
456
+ }
457
+ }
458
+ payment(amount, recipient, description) {
459
+ if (this.shouldLog("info")) {
460
+ const desc = description ? ` for "${description}"` : "";
461
+ console.log(`${this.prefix} \u{1F4B8} Paid $${amount.toFixed(4)} to ${recipient.slice(0, 10)}...${desc}`);
462
+ }
463
+ }
464
+ };
465
+ var AgentWallet = class {
466
+ sessionKey;
467
+ walletAddress;
468
+ maxPaymentUsd;
469
+ onPayment;
470
+ baseUrl;
471
+ timeout;
472
+ logger;
473
+ // Payment tracking
474
+ payments = [];
475
+ totalSpentUsd = 0;
476
+ // Session key info cache
477
+ sessionKeyInfo;
478
+ sessionKeyInfoFetchedAt;
479
+ /**
480
+ * Create a new AgentWallet instance.
481
+ *
482
+ * @param config - Configuration options
483
+ * @throws {InvalidSessionKeyError} If the session key format is invalid
484
+ *
485
+ * @example Basic initialization
486
+ * ```typescript
487
+ * const wallet = new AgentWallet({
488
+ * sessionKey: 'sk_live_abc123...'
489
+ * });
490
+ * ```
491
+ *
492
+ * @example With all options
493
+ * ```typescript
494
+ * const wallet = new AgentWallet({
495
+ * sessionKey: 'sk_live_abc123...',
496
+ * maxPaymentUsd: 5.0, // Client-side safety limit
497
+ * onPayment: (p) => log(p), // Track payments
498
+ * logLevel: 'info', // Enable logging
499
+ * timeout: 60000, // 60s timeout
500
+ * });
501
+ * ```
502
+ */
503
+ constructor(config) {
504
+ this.validateConfig(config);
505
+ this.sessionKey = SessionKey.fromString(config.sessionKey);
506
+ this.walletAddress = config.walletAddress || this.sessionKey.address;
507
+ this.maxPaymentUsd = config.maxPaymentUsd;
508
+ this.onPayment = config.onPayment;
509
+ this.baseUrl = (config.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
510
+ this.timeout = config.timeout || DEFAULT_TIMEOUT;
511
+ this.logger = new Logger(config.logLevel || "none");
512
+ this.logger.debug("AgentWallet initialized", {
513
+ walletAddress: this.walletAddress,
514
+ isTestnet: this.isTestnet(),
515
+ maxPaymentUsd: this.maxPaymentUsd
516
+ });
517
+ }
518
+ /**
519
+ * Validate the configuration before initialization.
520
+ */
521
+ validateConfig(config) {
522
+ if (!config.sessionKey) {
523
+ throw new InvalidSessionKeyError(
524
+ "Session key is required. Get one from the wallet owner or create one at your MixrPay server /wallet/sessions"
525
+ );
526
+ }
527
+ const key = config.sessionKey.trim();
528
+ if (!key.startsWith("sk_live_") && !key.startsWith("sk_test_")) {
529
+ throw new InvalidSessionKeyError(
530
+ `Invalid session key prefix. Expected 'sk_live_' (mainnet) or 'sk_test_' (testnet), got '${key.slice(0, 10)}...'`
531
+ );
532
+ }
533
+ const expectedLength = 8 + 64;
534
+ if (key.length !== expectedLength) {
535
+ throw new InvalidSessionKeyError(
536
+ `Invalid session key length. Expected ${expectedLength} characters, got ${key.length}. Make sure you copied the complete key.`
537
+ );
538
+ }
539
+ const hexPortion = key.slice(8);
540
+ if (!/^[0-9a-fA-F]+$/.test(hexPortion)) {
541
+ throw new InvalidSessionKeyError(
542
+ "Invalid session key format. The key should contain only hexadecimal characters after the prefix."
543
+ );
544
+ }
545
+ if (config.maxPaymentUsd !== void 0) {
546
+ if (config.maxPaymentUsd <= 0) {
547
+ throw new MixrPayError("maxPaymentUsd must be a positive number");
548
+ }
549
+ if (config.maxPaymentUsd > 1e4) {
550
+ this.logger?.warn("maxPaymentUsd is very high ($" + config.maxPaymentUsd + "). Consider using a lower limit for safety.");
551
+ }
552
+ }
553
+ }
554
+ // ===========================================================================
555
+ // Core Methods
556
+ // ===========================================================================
557
+ /**
558
+ * Make an HTTP request, automatically handling x402 payment if required.
559
+ *
560
+ * This is a drop-in replacement for the native `fetch()` function.
561
+ * If the server returns 402 Payment Required:
562
+ * 1. Parse payment requirements from response
563
+ * 2. Sign transferWithAuthorization using session key
564
+ * 3. Retry request with X-PAYMENT header
565
+ *
566
+ * @param url - Request URL
567
+ * @param init - Request options (same as native fetch)
568
+ * @returns Response from the server
569
+ *
570
+ * @throws {InsufficientBalanceError} If wallet doesn't have enough USDC
571
+ * @throws {SessionKeyExpiredError} If session key has expired
572
+ * @throws {SpendingLimitExceededError} If payment would exceed limits
573
+ * @throws {PaymentFailedError} If payment transaction failed
574
+ *
575
+ * @example GET request
576
+ * ```typescript
577
+ * const response = await wallet.fetch('https://api.example.com/data');
578
+ * const data = await response.json();
579
+ * ```
580
+ *
581
+ * @example POST request with JSON
582
+ * ```typescript
583
+ * const response = await wallet.fetch('https://api.example.com/generate', {
584
+ * method: 'POST',
585
+ * headers: { 'Content-Type': 'application/json' },
586
+ * body: JSON.stringify({ prompt: 'Hello world' })
587
+ * });
588
+ * ```
589
+ */
590
+ async fetch(url, init) {
591
+ this.logger.debug(`Fetching ${init?.method || "GET"} ${url}`);
592
+ const controller = new AbortController();
593
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
594
+ try {
595
+ let response = await fetch(url, {
596
+ ...init,
597
+ signal: controller.signal
598
+ });
599
+ this.logger.debug(`Initial response: ${response.status}`);
600
+ if (response.status === 402) {
601
+ this.logger.info(`Payment required for ${url}`);
602
+ response = await this.handlePaymentRequired(url, init, response);
603
+ }
604
+ return response;
605
+ } catch (error) {
606
+ if (error instanceof Error && error.name === "AbortError") {
607
+ throw new MixrPayError(`Request timeout after ${this.timeout}ms`);
608
+ }
609
+ throw error;
610
+ } finally {
611
+ clearTimeout(timeoutId);
612
+ }
613
+ }
614
+ /**
615
+ * Handle a 402 Payment Required response.
616
+ */
617
+ async handlePaymentRequired(url, init, response) {
618
+ let requirements;
619
+ try {
620
+ requirements = await parse402Response(response);
621
+ this.logger.debug("Payment requirements:", {
622
+ amount: `$${getAmountUsd(requirements).toFixed(4)}`,
623
+ recipient: requirements.recipient,
624
+ description: requirements.description
625
+ });
626
+ } catch (e) {
627
+ this.logger.error("Failed to parse payment requirements:", e);
628
+ throw new PaymentFailedError(
629
+ `Failed to parse payment requirements: ${e}. The server may not be properly configured for x402 payments.`
630
+ );
631
+ }
632
+ if (isPaymentExpired(requirements)) {
633
+ throw new PaymentFailedError(
634
+ "Payment requirements have expired. This usually means the request took too long. Try again."
635
+ );
636
+ }
637
+ const amountUsd = getAmountUsd(requirements);
638
+ if (this.maxPaymentUsd !== void 0 && amountUsd > this.maxPaymentUsd) {
639
+ throw new SpendingLimitExceededError(
640
+ "client_max",
641
+ this.maxPaymentUsd,
642
+ amountUsd
643
+ );
644
+ }
645
+ let xPayment;
646
+ try {
647
+ this.logger.debug("Signing payment authorization...");
648
+ xPayment = await buildXPaymentHeader(
649
+ requirements,
650
+ this.sessionKey,
651
+ this.walletAddress
652
+ );
653
+ } catch (e) {
654
+ this.logger.error("Failed to sign payment:", e);
655
+ throw new PaymentFailedError(
656
+ `Failed to sign payment: ${e}. This may indicate an issue with the session key.`
657
+ );
658
+ }
659
+ this.logger.debug("Retrying request with payment...");
660
+ const headers = new Headers(init?.headers);
661
+ headers.set("X-PAYMENT", xPayment);
662
+ const retryResponse = await fetch(url, {
663
+ ...init,
664
+ headers
665
+ });
666
+ if (retryResponse.status !== 402) {
667
+ const payment = {
668
+ amountUsd,
669
+ recipient: requirements.recipient,
670
+ txHash: retryResponse.headers.get("X-Payment-TxHash"),
671
+ timestamp: /* @__PURE__ */ new Date(),
672
+ description: requirements.description,
673
+ url
674
+ };
675
+ this.payments.push(payment);
676
+ this.totalSpentUsd += amountUsd;
677
+ this.logger.payment(amountUsd, requirements.recipient, requirements.description);
678
+ if (this.onPayment) {
679
+ this.onPayment(payment);
680
+ }
681
+ } else {
682
+ await this.handlePaymentError(retryResponse);
683
+ }
684
+ return retryResponse;
685
+ }
686
+ /**
687
+ * Handle payment-specific errors from the response.
688
+ */
689
+ async handlePaymentError(response) {
690
+ let errorData = {};
691
+ try {
692
+ errorData = await response.json();
693
+ } catch {
694
+ }
695
+ const errorCode = errorData.error_code || "";
696
+ const errorMessage = errorData.error || errorData.message || "Payment required";
697
+ this.logger.error("Payment failed:", { errorCode, errorMessage, errorData });
698
+ if (errorCode === "insufficient_balance") {
699
+ const required = errorData.required || 0;
700
+ const available = errorData.available || 0;
701
+ throw new InsufficientBalanceError(required, available);
702
+ } else if (errorCode === "session_key_expired") {
703
+ throw new SessionKeyExpiredError(errorData.expired_at || "unknown");
704
+ } else if (errorCode === "spending_limit_exceeded") {
705
+ throw new SpendingLimitExceededError(
706
+ errorData.limit_type || "unknown",
707
+ errorData.limit || 0,
708
+ errorData.attempted || 0
709
+ );
710
+ } else {
711
+ throw new PaymentFailedError(errorMessage);
712
+ }
713
+ }
714
+ // ===========================================================================
715
+ // Wallet Information
716
+ // ===========================================================================
717
+ /**
718
+ * Get the wallet address.
719
+ *
720
+ * @returns The Ethereum address of the smart wallet
721
+ */
722
+ getWalletAddress() {
723
+ return this.walletAddress;
724
+ }
725
+ /**
726
+ * Check if using testnet session key.
727
+ *
728
+ * @returns true if using Base Sepolia (testnet), false if using Base Mainnet
729
+ */
730
+ isTestnet() {
731
+ return this.sessionKey.isTest;
732
+ }
733
+ /**
734
+ * Get the network information.
735
+ *
736
+ * @returns Network details including chain ID and name
737
+ */
738
+ getNetwork() {
739
+ return this.isTestnet() ? NETWORKS.BASE_SEPOLIA : NETWORKS.BASE_MAINNET;
740
+ }
741
+ /**
742
+ * Get current USDC balance of the wallet.
743
+ *
744
+ * @returns USDC balance in USD
745
+ *
746
+ * @example
747
+ * ```typescript
748
+ * const balance = await wallet.getBalance();
749
+ * console.log(`Balance: $${balance.toFixed(2)}`);
750
+ * ```
751
+ */
752
+ async getBalance() {
753
+ this.logger.debug("Fetching wallet balance...");
754
+ try {
755
+ const response = await fetch(`${this.baseUrl}/v1/wallet/balance`, {
756
+ headers: {
757
+ "X-Session-Key": this.sessionKey.address
758
+ }
759
+ });
760
+ if (response.ok) {
761
+ const data = await response.json();
762
+ const balance = data.balance_usd || data.balanceUsd || 0;
763
+ this.logger.debug(`Balance: $${balance}`);
764
+ return balance;
765
+ }
766
+ } catch (error) {
767
+ this.logger.warn("Failed to fetch balance:", error);
768
+ }
769
+ this.logger.debug("Using estimated balance based on tracking");
770
+ return Math.max(0, 100 - this.totalSpentUsd);
771
+ }
772
+ /**
773
+ * Get information about the session key.
774
+ *
775
+ * @param refresh - Force refresh from server (default: use cache if < 60s old)
776
+ * @returns Session key details including limits and expiration
777
+ *
778
+ * @example
779
+ * ```typescript
780
+ * const info = await wallet.getSessionKeyInfo();
781
+ * console.log(`Daily limit: $${info.limits.dailyUsd}`);
782
+ * console.log(`Expires: ${info.expiresAt}`);
783
+ * ```
784
+ */
785
+ async getSessionKeyInfo(refresh = false) {
786
+ const cacheAge = this.sessionKeyInfoFetchedAt ? Date.now() - this.sessionKeyInfoFetchedAt : Infinity;
787
+ if (!refresh && this.sessionKeyInfo && cacheAge < 6e4) {
788
+ return this.sessionKeyInfo;
789
+ }
790
+ this.logger.debug("Fetching session key info...");
791
+ try {
792
+ const response = await fetch(`${this.baseUrl}/v1/session-key/info`, {
793
+ headers: {
794
+ "X-Session-Key": this.sessionKey.address
795
+ }
796
+ });
797
+ if (response.ok) {
798
+ const data = await response.json();
799
+ this.sessionKeyInfo = {
800
+ address: this.sessionKey.address,
801
+ isValid: data.is_valid ?? data.isValid ?? true,
802
+ limits: {
803
+ perTxUsd: data.per_tx_limit_usd ?? data.perTxLimitUsd ?? null,
804
+ dailyUsd: data.daily_limit_usd ?? data.dailyLimitUsd ?? null,
805
+ totalUsd: data.total_limit_usd ?? data.totalLimitUsd ?? null
806
+ },
807
+ usage: {
808
+ todayUsd: data.today_spent_usd ?? data.todaySpentUsd ?? 0,
809
+ totalUsd: data.total_spent_usd ?? data.totalSpentUsd ?? 0,
810
+ txCount: data.tx_count ?? data.txCount ?? 0
811
+ },
812
+ expiresAt: data.expires_at ? new Date(data.expires_at) : null,
813
+ createdAt: data.created_at ? new Date(data.created_at) : null,
814
+ name: data.name
815
+ };
816
+ this.sessionKeyInfoFetchedAt = Date.now();
817
+ return this.sessionKeyInfo;
818
+ }
819
+ } catch (error) {
820
+ this.logger.warn("Failed to fetch session key info:", error);
821
+ }
822
+ return {
823
+ address: this.sessionKey.address,
824
+ isValid: true,
825
+ limits: { perTxUsd: null, dailyUsd: null, totalUsd: null },
826
+ usage: { todayUsd: this.totalSpentUsd, totalUsd: this.totalSpentUsd, txCount: this.payments.length },
827
+ expiresAt: null,
828
+ createdAt: null
829
+ };
830
+ }
831
+ /**
832
+ * Get spending stats for this session key.
833
+ *
834
+ * @returns Spending statistics
835
+ *
836
+ * @example
837
+ * ```typescript
838
+ * const stats = await wallet.getSpendingStats();
839
+ * console.log(`Spent: $${stats.totalSpentUsd.toFixed(2)}`);
840
+ * console.log(`Remaining daily: $${stats.remainingDailyUsd?.toFixed(2) ?? 'unlimited'}`);
841
+ * ```
842
+ */
843
+ async getSpendingStats() {
844
+ this.logger.debug("Fetching spending stats...");
845
+ try {
846
+ const response = await fetch(`${this.baseUrl}/v1/session-key/stats`, {
847
+ headers: {
848
+ "X-Session-Key": this.sessionKey.address
849
+ }
850
+ });
851
+ if (response.ok) {
852
+ const data = await response.json();
853
+ return {
854
+ totalSpentUsd: data.total_spent_usd || data.totalSpentUsd || this.totalSpentUsd,
855
+ txCount: data.tx_count || data.txCount || this.payments.length,
856
+ remainingDailyUsd: data.remaining_daily_usd || data.remainingDailyUsd || null,
857
+ remainingTotalUsd: data.remaining_total_usd || data.remainingTotalUsd || null,
858
+ expiresAt: data.expires_at ? new Date(data.expires_at) : null
859
+ };
860
+ }
861
+ } catch (error) {
862
+ this.logger.warn("Failed to fetch spending stats:", error);
863
+ }
864
+ return {
865
+ totalSpentUsd: this.totalSpentUsd,
866
+ txCount: this.payments.length,
867
+ remainingDailyUsd: null,
868
+ remainingTotalUsd: null,
869
+ expiresAt: null
870
+ };
871
+ }
872
+ /**
873
+ * Get list of payments made in this session.
874
+ *
875
+ * @returns Array of payment events
876
+ */
877
+ getPaymentHistory() {
878
+ return [...this.payments];
879
+ }
880
+ /**
881
+ * Get the total amount spent in this session.
882
+ *
883
+ * @returns Total spent in USD
884
+ */
885
+ getTotalSpent() {
886
+ return this.totalSpentUsd;
887
+ }
888
+ // ===========================================================================
889
+ // Diagnostics
890
+ // ===========================================================================
891
+ /**
892
+ * Run diagnostics to verify the wallet is properly configured.
893
+ *
894
+ * This is useful for debugging integration issues.
895
+ *
896
+ * @returns Diagnostic results with status and any issues found
897
+ *
898
+ * @example
899
+ * ```typescript
900
+ * const diagnostics = await wallet.runDiagnostics();
901
+ * if (diagnostics.healthy) {
902
+ * console.log('✅ Wallet is ready to use');
903
+ * } else {
904
+ * console.log('❌ Issues found:');
905
+ * diagnostics.issues.forEach(issue => console.log(` - ${issue}`));
906
+ * }
907
+ * ```
908
+ */
909
+ async runDiagnostics() {
910
+ this.logger.info("Running diagnostics...");
911
+ const issues = [];
912
+ const checks = {};
913
+ checks.sessionKeyFormat = true;
914
+ try {
915
+ const response = await fetch(`${this.baseUrl}/health`, {
916
+ method: "GET",
917
+ signal: AbortSignal.timeout(5e3)
918
+ });
919
+ checks.apiConnectivity = response.ok;
920
+ if (!response.ok) {
921
+ issues.push(`API server returned ${response.status}. Check baseUrl configuration.`);
922
+ }
923
+ } catch {
924
+ checks.apiConnectivity = false;
925
+ issues.push("Cannot connect to MixrPay API. Check your network connection and baseUrl.");
926
+ }
927
+ try {
928
+ const info = await this.getSessionKeyInfo(true);
929
+ checks.sessionKeyValid = info.isValid;
930
+ if (!info.isValid) {
931
+ issues.push("Session key is invalid or has been revoked.");
932
+ }
933
+ if (info.expiresAt && info.expiresAt < /* @__PURE__ */ new Date()) {
934
+ checks.sessionKeyValid = false;
935
+ issues.push(`Session key expired on ${info.expiresAt.toISOString()}`);
936
+ }
937
+ } catch {
938
+ checks.sessionKeyValid = false;
939
+ issues.push("Could not verify session key validity.");
940
+ }
941
+ try {
942
+ const balance = await this.getBalance();
943
+ checks.hasBalance = balance > 0;
944
+ if (balance <= 0) {
945
+ issues.push("Wallet has no USDC balance. Top up at your MixrPay server /wallet");
946
+ } else if (balance < 1) {
947
+ issues.push(`Low balance: $${balance.toFixed(2)}. Consider topping up.`);
948
+ }
949
+ } catch {
950
+ checks.hasBalance = false;
951
+ issues.push("Could not fetch wallet balance.");
952
+ }
953
+ const healthy = issues.length === 0;
954
+ this.logger.info("Diagnostics complete:", { healthy, issues });
955
+ return {
956
+ healthy,
957
+ issues,
958
+ checks,
959
+ sdkVersion: SDK_VERSION,
960
+ network: this.getNetwork().name,
961
+ walletAddress: this.walletAddress
962
+ };
963
+ }
964
+ /**
965
+ * Enable or disable debug logging.
966
+ *
967
+ * @param enable - true to enable debug logging, false to disable
968
+ *
969
+ * @example
970
+ * ```typescript
971
+ * wallet.setDebug(true); // Enable detailed logs
972
+ * await wallet.fetch(...);
973
+ * wallet.setDebug(false); // Disable logs
974
+ * ```
975
+ */
976
+ setDebug(enable) {
977
+ this.logger.setLevel(enable ? "debug" : "none");
978
+ }
979
+ /**
980
+ * Set the log level.
981
+ *
982
+ * @param level - 'debug' | 'info' | 'warn' | 'error' | 'none'
983
+ */
984
+ setLogLevel(level) {
985
+ this.logger.setLevel(level);
986
+ }
987
+ // ===========================================================================
988
+ // Session Authorization Methods (for MixrPay Merchants)
989
+ // ===========================================================================
990
+ /**
991
+ * Create the X-Session-Auth header for secure API authentication.
992
+ * Uses signature-based authentication - private key is NEVER transmitted.
993
+ *
994
+ * @returns Headers object with X-Session-Auth
995
+ */
996
+ async getSessionAuthHeaders() {
997
+ const payload = await createSessionAuthPayload(this.sessionKey);
998
+ return {
999
+ "X-Session-Auth": JSON.stringify(payload)
1000
+ };
1001
+ }
1002
+ /**
1003
+ * Get an existing session or create a new one with a MixrPay merchant.
1004
+ *
1005
+ * This is the recommended way to interact with MixrPay-enabled APIs.
1006
+ * If an active session exists, it will be returned. Otherwise, a new
1007
+ * session authorization request will be created and confirmed.
1008
+ *
1009
+ * @param options - Session creation options
1010
+ * @returns Active session authorization
1011
+ *
1012
+ * @throws {MixrPayError} If merchant is not found or session creation fails
1013
+ *
1014
+ * @example
1015
+ * ```typescript
1016
+ * const session = await wallet.getOrCreateSession({
1017
+ * merchantPublicKey: 'pk_live_abc123...',
1018
+ * spendingLimitUsd: 25.00,
1019
+ * durationDays: 7,
1020
+ * });
1021
+ *
1022
+ * console.log(`Session active: $${session.remainingLimitUsd} remaining`);
1023
+ * ```
1024
+ */
1025
+ async getOrCreateSession(options) {
1026
+ this.logger.debug("getOrCreateSession called", options);
1027
+ const { merchantPublicKey, spendingLimitUsd = 25, durationDays = 7 } = options;
1028
+ try {
1029
+ const existingSession = await this.getSessionByMerchant(merchantPublicKey);
1030
+ if (existingSession && existingSession.status === "active") {
1031
+ this.logger.debug("Found existing active session", existingSession.id);
1032
+ return existingSession;
1033
+ }
1034
+ } catch {
1035
+ }
1036
+ this.logger.info(`Creating new session with merchant ${merchantPublicKey.slice(0, 20)}...`);
1037
+ const authHeaders = await this.getSessionAuthHeaders();
1038
+ const authorizeResponse = await fetch(`${this.baseUrl}/api/v2/session/authorize`, {
1039
+ method: "POST",
1040
+ headers: {
1041
+ "Content-Type": "application/json",
1042
+ ...authHeaders
1043
+ },
1044
+ body: JSON.stringify({
1045
+ merchant_public_key: merchantPublicKey,
1046
+ spending_limit_usd: spendingLimitUsd,
1047
+ duration_days: durationDays
1048
+ })
1049
+ });
1050
+ if (!authorizeResponse.ok) {
1051
+ const error = await authorizeResponse.json().catch(() => ({}));
1052
+ throw new MixrPayError(
1053
+ error.message || error.error || `Failed to create session: ${authorizeResponse.status}`
1054
+ );
1055
+ }
1056
+ const authorizeData = await authorizeResponse.json();
1057
+ const sessionId = authorizeData.session_id;
1058
+ const messageToSign = authorizeData.message_to_sign;
1059
+ if (!sessionId || !messageToSign) {
1060
+ throw new MixrPayError("Invalid authorize response: missing session_id or message_to_sign");
1061
+ }
1062
+ this.logger.debug("Signing session authorization message...");
1063
+ const signature = await this.sessionKey.signMessage(messageToSign);
1064
+ const confirmResponse = await fetch(`${this.baseUrl}/api/v2/session/confirm`, {
1065
+ method: "POST",
1066
+ headers: {
1067
+ "Content-Type": "application/json"
1068
+ },
1069
+ body: JSON.stringify({
1070
+ session_id: sessionId,
1071
+ signature,
1072
+ wallet_address: this.walletAddress
1073
+ })
1074
+ });
1075
+ if (!confirmResponse.ok) {
1076
+ const error = await confirmResponse.json().catch(() => ({}));
1077
+ throw new MixrPayError(
1078
+ error.message || `Failed to confirm session: ${confirmResponse.status}`
1079
+ );
1080
+ }
1081
+ const confirmData = await confirmResponse.json();
1082
+ this.logger.info(`Session created: ${confirmData.session?.id || sessionId}`);
1083
+ return this.parseSessionResponse(confirmData.session || confirmData);
1084
+ }
1085
+ /**
1086
+ * Get session status for a specific merchant.
1087
+ *
1088
+ * @param merchantPublicKey - The merchant's public key
1089
+ * @returns Session authorization or null if not found
1090
+ */
1091
+ async getSessionByMerchant(merchantPublicKey) {
1092
+ this.logger.debug("getSessionByMerchant", merchantPublicKey);
1093
+ const authHeaders = await this.getSessionAuthHeaders();
1094
+ const response = await fetch(`${this.baseUrl}/api/v2/session/status?merchant_public_key=${encodeURIComponent(merchantPublicKey)}`, {
1095
+ headers: authHeaders
1096
+ });
1097
+ if (response.status === 404) {
1098
+ return null;
1099
+ }
1100
+ if (!response.ok) {
1101
+ const error = await response.json().catch(() => ({}));
1102
+ throw new MixrPayError(error.message || `Failed to get session: ${response.status}`);
1103
+ }
1104
+ const data = await response.json();
1105
+ return data.session ? this.parseSessionResponse(data.session) : null;
1106
+ }
1107
+ /**
1108
+ * List all session authorizations for this wallet.
1109
+ *
1110
+ * @returns Array of session authorizations
1111
+ *
1112
+ * @example
1113
+ * ```typescript
1114
+ * const sessions = await wallet.listSessions();
1115
+ * for (const session of sessions) {
1116
+ * console.log(`${session.merchantName}: $${session.remainingLimitUsd} remaining`);
1117
+ * }
1118
+ * ```
1119
+ */
1120
+ async listSessions() {
1121
+ this.logger.debug("listSessions");
1122
+ const authHeaders = await this.getSessionAuthHeaders();
1123
+ const response = await fetch(`${this.baseUrl}/api/v2/session/list`, {
1124
+ headers: authHeaders
1125
+ });
1126
+ if (!response.ok) {
1127
+ const error = await response.json().catch(() => ({}));
1128
+ throw new MixrPayError(error.message || `Failed to list sessions: ${response.status}`);
1129
+ }
1130
+ const data = await response.json();
1131
+ return (data.sessions || []).map((s) => this.parseSessionResponse(s));
1132
+ }
1133
+ /**
1134
+ * Revoke a session authorization.
1135
+ *
1136
+ * After revocation, no further charges can be made against this session.
1137
+ *
1138
+ * @param sessionId - The session ID to revoke
1139
+ * @returns true if revoked successfully
1140
+ *
1141
+ * @example
1142
+ * ```typescript
1143
+ * const revoked = await wallet.revokeSession('sess_abc123');
1144
+ * if (revoked) {
1145
+ * console.log('Session revoked successfully');
1146
+ * }
1147
+ * ```
1148
+ */
1149
+ async revokeSession(sessionId) {
1150
+ this.logger.debug("revokeSession", sessionId);
1151
+ const authHeaders = await this.getSessionAuthHeaders();
1152
+ const response = await fetch(`${this.baseUrl}/api/v2/session/revoke`, {
1153
+ method: "POST",
1154
+ headers: {
1155
+ "Content-Type": "application/json",
1156
+ ...authHeaders
1157
+ },
1158
+ body: JSON.stringify({ session_id: sessionId })
1159
+ });
1160
+ if (!response.ok) {
1161
+ const error = await response.json().catch(() => ({}));
1162
+ this.logger.error("Failed to revoke session:", error);
1163
+ return false;
1164
+ }
1165
+ this.logger.info(`Session ${sessionId} revoked`);
1166
+ return true;
1167
+ }
1168
+ /**
1169
+ * Get statistics about all session authorizations.
1170
+ *
1171
+ * This provides an overview of active, expired, and revoked sessions,
1172
+ * along with aggregate spending information.
1173
+ *
1174
+ * @returns Session statistics
1175
+ *
1176
+ * @example
1177
+ * ```typescript
1178
+ * const stats = await wallet.getSessionStats();
1179
+ * console.log(`Active sessions: ${stats.activeCount}`);
1180
+ * console.log(`Total authorized: $${stats.totalAuthorizedUsd.toFixed(2)}`);
1181
+ * console.log(`Total remaining: $${stats.totalRemainingUsd.toFixed(2)}`);
1182
+ *
1183
+ * for (const session of stats.activeSessions) {
1184
+ * console.log(`${session.merchantName}: $${session.remainingUsd} remaining`);
1185
+ * }
1186
+ * ```
1187
+ */
1188
+ async getSessionStats() {
1189
+ this.logger.debug("getSessionStats");
1190
+ const sessions = await this.listSessions();
1191
+ const now = /* @__PURE__ */ new Date();
1192
+ const active = [];
1193
+ const expired = [];
1194
+ const revoked = [];
1195
+ for (const session of sessions) {
1196
+ if (session.status === "revoked") {
1197
+ revoked.push(session);
1198
+ } else if (session.status === "expired" || session.expiresAt && session.expiresAt < now) {
1199
+ expired.push(session);
1200
+ } else if (session.status === "active") {
1201
+ active.push(session);
1202
+ }
1203
+ }
1204
+ const totalAuthorizedUsd = active.reduce((sum, s) => sum + s.spendingLimitUsd, 0);
1205
+ const totalSpentUsd = sessions.reduce((sum, s) => sum + s.amountUsedUsd, 0);
1206
+ const totalRemainingUsd = active.reduce((sum, s) => sum + s.remainingLimitUsd, 0);
1207
+ return {
1208
+ activeCount: active.length,
1209
+ expiredCount: expired.length,
1210
+ revokedCount: revoked.length,
1211
+ totalAuthorizedUsd,
1212
+ totalSpentUsd,
1213
+ totalRemainingUsd,
1214
+ activeSessions: active.map((s) => ({
1215
+ id: s.id,
1216
+ merchantName: s.merchantName,
1217
+ merchantPublicKey: s.merchantId,
1218
+ // merchantId is the public key in this context
1219
+ spendingLimitUsd: s.spendingLimitUsd,
1220
+ remainingUsd: s.remainingLimitUsd,
1221
+ expiresAt: s.expiresAt
1222
+ }))
1223
+ };
1224
+ }
1225
+ /**
1226
+ * Charge against an active session authorization.
1227
+ *
1228
+ * This is useful when you need to manually charge a session outside of
1229
+ * the `callMerchantApi()` flow.
1230
+ *
1231
+ * @param sessionId - The session ID to charge
1232
+ * @param amountUsd - Amount to charge in USD
1233
+ * @param options - Additional charge options
1234
+ * @returns Charge result
1235
+ *
1236
+ * @example
1237
+ * ```typescript
1238
+ * const result = await wallet.chargeSession('sess_abc123', 0.05, {
1239
+ * feature: 'ai-generation',
1240
+ * idempotencyKey: 'unique-key-123',
1241
+ * });
1242
+ *
1243
+ * console.log(`Charged $${result.amountUsd}, remaining: $${result.remainingSessionBalanceUsd}`);
1244
+ * ```
1245
+ */
1246
+ async chargeSession(sessionId, amountUsd, options = {}) {
1247
+ this.logger.debug("chargeSession", { sessionId, amountUsd, options });
1248
+ const authHeaders = await this.getSessionAuthHeaders();
1249
+ const response = await fetch(`${this.baseUrl}/api/v2/charge`, {
1250
+ method: "POST",
1251
+ headers: {
1252
+ "Content-Type": "application/json",
1253
+ ...authHeaders
1254
+ },
1255
+ body: JSON.stringify({
1256
+ session_id: sessionId,
1257
+ price_usd: amountUsd,
1258
+ feature: options.feature,
1259
+ idempotency_key: options.idempotencyKey,
1260
+ metadata: options.metadata
1261
+ })
1262
+ });
1263
+ if (!response.ok) {
1264
+ const error = await response.json().catch(() => ({}));
1265
+ const errorCode = error.error || error.error_code || "";
1266
+ if (response.status === 402) {
1267
+ if (errorCode === "session_limit_exceeded") {
1268
+ const limit = error.sessionLimitUsd || error.session_limit_usd || 0;
1269
+ const remaining = error.remainingUsd || error.remaining_usd || 0;
1270
+ throw new SessionLimitExceededError(limit, amountUsd, remaining, sessionId);
1271
+ }
1272
+ if (errorCode === "insufficient_balance") {
1273
+ throw new InsufficientBalanceError(
1274
+ amountUsd,
1275
+ error.availableUsd || error.available_usd || 0
1276
+ );
1277
+ }
1278
+ }
1279
+ if (response.status === 404 || errorCode === "session_not_found") {
1280
+ throw new SessionNotFoundError(sessionId);
1281
+ }
1282
+ if (errorCode === "session_expired") {
1283
+ throw new SessionExpiredError(sessionId, error.expiredAt || error.expires_at);
1284
+ }
1285
+ if (errorCode === "session_revoked") {
1286
+ throw new SessionRevokedError(sessionId, error.reason);
1287
+ }
1288
+ throw new MixrPayError(error.message || `Charge failed: ${response.status}`);
1289
+ }
1290
+ const data = await response.json();
1291
+ this.logger.payment(amountUsd, sessionId, options.feature);
1292
+ return {
1293
+ success: true,
1294
+ chargeId: data.chargeId || data.charge_id,
1295
+ amountUsd: data.amountUsd || data.amount_usd || amountUsd,
1296
+ txHash: data.txHash || data.tx_hash,
1297
+ remainingSessionBalanceUsd: data.remainingSessionBalanceUsd || data.remaining_session_balance_usd || 0
1298
+ };
1299
+ }
1300
+ /**
1301
+ * Call a MixrPay merchant's API with automatic session management.
1302
+ *
1303
+ * This is the recommended way to interact with MixrPay-enabled APIs.
1304
+ * It automatically:
1305
+ * 1. Gets or creates a session authorization
1306
+ * 2. Adds the `X-Mixr-Session` header to the request
1307
+ * 3. Handles payment errors and session expiration
1308
+ *
1309
+ * @param options - API call options
1310
+ * @returns Response from the merchant API
1311
+ *
1312
+ * @example
1313
+ * ```typescript
1314
+ * const response = await wallet.callMerchantApi({
1315
+ * url: 'https://api.merchant.com/generate',
1316
+ * merchantPublicKey: 'pk_live_abc123...',
1317
+ * method: 'POST',
1318
+ * body: { prompt: 'Hello world' },
1319
+ * priceUsd: 0.05,
1320
+ * });
1321
+ *
1322
+ * const data = await response.json();
1323
+ * ```
1324
+ */
1325
+ async callMerchantApi(options) {
1326
+ const {
1327
+ url,
1328
+ method = "POST",
1329
+ body,
1330
+ headers: customHeaders = {},
1331
+ merchantPublicKey,
1332
+ priceUsd,
1333
+ feature
1334
+ } = options;
1335
+ this.logger.debug("callMerchantApi", { url, method, merchantPublicKey, priceUsd });
1336
+ if (priceUsd !== void 0 && this.maxPaymentUsd !== void 0 && priceUsd > this.maxPaymentUsd) {
1337
+ throw new SpendingLimitExceededError("client_max", this.maxPaymentUsd, priceUsd);
1338
+ }
1339
+ const session = await this.getOrCreateSession({
1340
+ merchantPublicKey,
1341
+ spendingLimitUsd: 25,
1342
+ // Default limit
1343
+ durationDays: 7
1344
+ });
1345
+ const headers = {
1346
+ "Content-Type": "application/json",
1347
+ "X-Mixr-Session": session.id,
1348
+ ...customHeaders
1349
+ };
1350
+ if (feature) {
1351
+ headers["X-Mixr-Feature"] = feature;
1352
+ }
1353
+ const requestBody = body !== void 0 ? typeof body === "string" ? body : JSON.stringify(body) : void 0;
1354
+ const response = await fetch(url, {
1355
+ method,
1356
+ headers,
1357
+ body: requestBody,
1358
+ signal: AbortSignal.timeout(this.timeout)
1359
+ });
1360
+ const chargedAmount = response.headers.get("X-Mixr-Charged");
1361
+ if (chargedAmount) {
1362
+ const amountUsd = parseFloat(chargedAmount);
1363
+ if (!isNaN(amountUsd)) {
1364
+ const payment = {
1365
+ amountUsd,
1366
+ recipient: merchantPublicKey,
1367
+ txHash: response.headers.get("X-Payment-TxHash"),
1368
+ timestamp: /* @__PURE__ */ new Date(),
1369
+ description: feature || "API call",
1370
+ url
1371
+ };
1372
+ this.payments.push(payment);
1373
+ this.totalSpentUsd += amountUsd;
1374
+ this.logger.payment(amountUsd, merchantPublicKey, feature);
1375
+ if (this.onPayment) {
1376
+ this.onPayment(payment);
1377
+ }
1378
+ }
1379
+ }
1380
+ if (response.status === 402) {
1381
+ const errorData = await response.json().catch(() => ({}));
1382
+ const errorCode = errorData.error || errorData.error_code || "";
1383
+ if (errorCode === "session_expired") {
1384
+ this.logger.info("Session expired, creating new one...");
1385
+ const newSession = await this.getOrCreateSession({
1386
+ merchantPublicKey,
1387
+ spendingLimitUsd: 25,
1388
+ durationDays: 7
1389
+ });
1390
+ headers["X-Mixr-Session"] = newSession.id;
1391
+ return fetch(url, {
1392
+ method,
1393
+ headers,
1394
+ body: requestBody,
1395
+ signal: AbortSignal.timeout(this.timeout)
1396
+ });
1397
+ }
1398
+ if (errorCode === "session_limit_exceeded") {
1399
+ const limit = errorData.sessionLimitUsd || errorData.session_limit_usd || 0;
1400
+ const remaining = errorData.remainingUsd || errorData.remaining_usd || 0;
1401
+ throw new SessionLimitExceededError(limit, priceUsd || 0, remaining, session.id);
1402
+ }
1403
+ if (errorCode === "session_revoked") {
1404
+ throw new SessionRevokedError(session.id, errorData.reason);
1405
+ }
1406
+ if (errorCode === "session_not_found") {
1407
+ throw new SessionNotFoundError(session.id);
1408
+ }
1409
+ if (errorCode === "insufficient_balance") {
1410
+ throw new InsufficientBalanceError(
1411
+ priceUsd || 0,
1412
+ errorData.availableUsd || errorData.available_usd || 0
1413
+ );
1414
+ }
1415
+ }
1416
+ return response;
1417
+ }
1418
+ /**
1419
+ * Parse session response data into SessionAuthorization object.
1420
+ */
1421
+ parseSessionResponse(data) {
1422
+ return {
1423
+ id: data.id || data.session_id || data.sessionId,
1424
+ merchantId: data.merchantId || data.merchant_id,
1425
+ merchantName: data.merchantName || data.merchant_name || "Unknown",
1426
+ status: data.status || "active",
1427
+ spendingLimitUsd: Number(data.spendingLimitUsd || data.spending_limit_usd || data.spendingLimit || 0),
1428
+ amountUsedUsd: Number(data.amountUsedUsd || data.amount_used_usd || data.amountUsed || 0),
1429
+ remainingLimitUsd: Number(
1430
+ data.remainingLimitUsd || data.remaining_limit_usd || data.remainingLimit || Number(data.spendingLimitUsd || data.spending_limit_usd || 0) - Number(data.amountUsedUsd || data.amount_used_usd || 0)
1431
+ ),
1432
+ expiresAt: new Date(data.expiresAt || data.expires_at),
1433
+ createdAt: new Date(data.createdAt || data.created_at)
1434
+ };
1435
+ }
1436
+ // ===========================================================================
1437
+ // MCP (Model Context Protocol) Methods
1438
+ // ===========================================================================
1439
+ /**
1440
+ * Get authentication headers for MCP wallet-based authentication.
1441
+ *
1442
+ * These headers prove wallet ownership without transmitting the private key.
1443
+ * Use for direct pay-per-call mode (no session needed).
1444
+ *
1445
+ * @returns Headers object with X-Mixr-Wallet, X-Mixr-Signature, X-Mixr-Timestamp
1446
+ *
1447
+ * @example
1448
+ * ```typescript
1449
+ * const headers = await wallet.getMCPAuthHeaders();
1450
+ * const response = await fetch('https://mixrpay.com/api/mcp', {
1451
+ * method: 'POST',
1452
+ * headers: {
1453
+ * 'Content-Type': 'application/json',
1454
+ * ...headers,
1455
+ * },
1456
+ * body: JSON.stringify({
1457
+ * jsonrpc: '2.0',
1458
+ * method: 'tools/list',
1459
+ * id: 1,
1460
+ * }),
1461
+ * });
1462
+ * ```
1463
+ */
1464
+ async getMCPAuthHeaders() {
1465
+ const timestamp = Date.now().toString();
1466
+ const message = `MixrPay MCP Auth
1467
+ Wallet: ${this.walletAddress}
1468
+ Timestamp: ${timestamp}`;
1469
+ const signature = await this.sessionKey.signMessage(message);
1470
+ return {
1471
+ "X-Mixr-Wallet": this.walletAddress,
1472
+ "X-Mixr-Signature": signature,
1473
+ "X-Mixr-Timestamp": timestamp
1474
+ };
1475
+ }
1476
+ /**
1477
+ * List available MCP tools from the MixrPay gateway.
1478
+ *
1479
+ * Returns all tools exposed by MCP providers on the MixrPay marketplace.
1480
+ * Each tool includes pricing information.
1481
+ *
1482
+ * @returns Array of MCP tools with pricing and metadata
1483
+ *
1484
+ * @example
1485
+ * ```typescript
1486
+ * const tools = await wallet.listMCPTools();
1487
+ * for (const tool of tools) {
1488
+ * console.log(`${tool.name}: $${tool.priceUsd} - ${tool.description}`);
1489
+ * }
1490
+ * ```
1491
+ */
1492
+ async listMCPTools() {
1493
+ this.logger.debug("listMCPTools");
1494
+ const response = await fetch(`${this.baseUrl}/api/mcp`, {
1495
+ method: "POST",
1496
+ headers: { "Content-Type": "application/json" },
1497
+ body: JSON.stringify({
1498
+ jsonrpc: "2.0",
1499
+ method: "tools/list",
1500
+ id: Date.now()
1501
+ })
1502
+ });
1503
+ if (!response.ok) {
1504
+ throw new MixrPayError(`Failed to list MCP tools: ${response.status}`);
1505
+ }
1506
+ const result = await response.json();
1507
+ if (result.error) {
1508
+ throw new MixrPayError(result.error.message || "Failed to list MCP tools");
1509
+ }
1510
+ return (result.result?.tools || []).map((tool) => ({
1511
+ name: tool.name,
1512
+ description: tool.description,
1513
+ inputSchema: tool.inputSchema,
1514
+ priceUsd: tool["x-mixrpay"]?.priceUsd || 0,
1515
+ merchantName: tool["x-mixrpay"]?.merchantName,
1516
+ merchantSlug: tool["x-mixrpay"]?.merchantSlug,
1517
+ verified: tool["x-mixrpay"]?.verified || false
1518
+ }));
1519
+ }
1520
+ /**
1521
+ * Call an MCP tool with wallet authentication (direct pay per call).
1522
+ *
1523
+ * This method signs a fresh auth message for each call, charging
1524
+ * directly from your wallet balance without needing a session.
1525
+ *
1526
+ * @param toolName - The tool name in format "merchant/tool"
1527
+ * @param args - Arguments to pass to the tool
1528
+ * @returns Tool execution result
1529
+ *
1530
+ * @example
1531
+ * ```typescript
1532
+ * const result = await wallet.callMCPTool('firecrawl/scrape', {
1533
+ * url: 'https://example.com',
1534
+ * });
1535
+ * console.log(result.data);
1536
+ * console.log(`Charged: $${result.chargedUsd}`);
1537
+ * ```
1538
+ */
1539
+ async callMCPTool(toolName, args = {}) {
1540
+ this.logger.debug("callMCPTool", { toolName, args });
1541
+ const authHeaders = await this.getMCPAuthHeaders();
1542
+ const response = await fetch(`${this.baseUrl}/api/mcp`, {
1543
+ method: "POST",
1544
+ headers: {
1545
+ "Content-Type": "application/json",
1546
+ ...authHeaders
1547
+ },
1548
+ body: JSON.stringify({
1549
+ jsonrpc: "2.0",
1550
+ method: "tools/call",
1551
+ params: { name: toolName, arguments: args },
1552
+ id: Date.now()
1553
+ })
1554
+ });
1555
+ const result = await response.json();
1556
+ if (result.error) {
1557
+ throw new MixrPayError(result.error.message || "MCP tool call failed");
1558
+ }
1559
+ const content = result.result?.content?.[0];
1560
+ const data = content?.text ? JSON.parse(content.text) : null;
1561
+ const mixrpay = result.result?._mixrpay || {};
1562
+ if (mixrpay.chargedUsd) {
1563
+ const payment = {
1564
+ amountUsd: mixrpay.chargedUsd,
1565
+ recipient: toolName.split("/")[0] || toolName,
1566
+ txHash: mixrpay.txHash,
1567
+ timestamp: /* @__PURE__ */ new Date(),
1568
+ description: `MCP: ${toolName}`,
1569
+ url: `${this.baseUrl}/api/mcp`
1570
+ };
1571
+ this.payments.push(payment);
1572
+ this.totalSpentUsd += mixrpay.chargedUsd;
1573
+ this.logger.payment(mixrpay.chargedUsd, toolName, "MCP call");
1574
+ if (this.onPayment) {
1575
+ this.onPayment(payment);
1576
+ }
1577
+ }
1578
+ return {
1579
+ data,
1580
+ chargedUsd: mixrpay.chargedUsd || 0,
1581
+ txHash: mixrpay.txHash,
1582
+ latencyMs: mixrpay.latencyMs
1583
+ };
1584
+ }
1585
+ // ===========================================================================
1586
+ // Agent Runtime API
1587
+ // ===========================================================================
1588
+ /**
1589
+ * Run an AI agent with LLM and tool execution.
1590
+ *
1591
+ * This method orchestrates a full agentic loop:
1592
+ * - Multi-turn reasoning with LLM
1593
+ * - Automatic tool execution
1594
+ * - Bundled billing (single charge at end)
1595
+ * - Optional streaming via SSE
1596
+ *
1597
+ * @param options - Agent run options
1598
+ * @returns Agent run result with response and cost breakdown
1599
+ *
1600
+ * @example Basic usage
1601
+ * ```typescript
1602
+ * const result = await wallet.runAgent({
1603
+ * sessionId: 'sess_abc123',
1604
+ * messages: [{ role: 'user', content: 'Find AI startups in SF' }],
1605
+ * });
1606
+ *
1607
+ * console.log(result.response);
1608
+ * console.log(`Cost: $${result.cost.totalUsd.toFixed(4)}`);
1609
+ * ```
1610
+ *
1611
+ * @example With custom config
1612
+ * ```typescript
1613
+ * const result = await wallet.runAgent({
1614
+ * sessionId: 'sess_abc123',
1615
+ * messages: [{ role: 'user', content: 'Research quantum computing' }],
1616
+ * config: {
1617
+ * model: 'gpt-4o',
1618
+ * maxIterations: 15,
1619
+ * tools: ['platform/exa-search', 'platform/firecrawl-scrape'],
1620
+ * systemPrompt: 'You are a research assistant.',
1621
+ * },
1622
+ * });
1623
+ * ```
1624
+ *
1625
+ * @example With streaming
1626
+ * ```typescript
1627
+ * await wallet.runAgent({
1628
+ * sessionId: 'sess_abc123',
1629
+ * messages: [{ role: 'user', content: 'Analyze this company' }],
1630
+ * stream: true,
1631
+ * onEvent: (event) => {
1632
+ * if (event.type === 'llm_chunk') {
1633
+ * process.stdout.write(event.delta);
1634
+ * } else if (event.type === 'tool_call') {
1635
+ * console.log(`Calling tool: ${event.tool}`);
1636
+ * }
1637
+ * },
1638
+ * });
1639
+ * ```
1640
+ */
1641
+ async runAgent(options) {
1642
+ const {
1643
+ sessionId,
1644
+ messages,
1645
+ config = {},
1646
+ stream = false,
1647
+ idempotencyKey,
1648
+ onEvent
1649
+ } = options;
1650
+ this.logger.debug("runAgent", { sessionId, messageCount: messages.length, config, stream });
1651
+ const body = {
1652
+ session_id: sessionId,
1653
+ messages: messages.map((m) => ({ role: m.role, content: m.content })),
1654
+ config: {
1655
+ model: config.model,
1656
+ max_iterations: config.maxIterations,
1657
+ tools: config.tools,
1658
+ system_prompt: config.systemPrompt
1659
+ },
1660
+ stream,
1661
+ idempotency_key: idempotencyKey
1662
+ };
1663
+ const AGENT_RUN_TIMEOUT = 18e4;
1664
+ if (!stream) {
1665
+ const response = await fetch(`${this.baseUrl}/api/v2/agent/run`, {
1666
+ method: "POST",
1667
+ headers: {
1668
+ "Content-Type": "application/json",
1669
+ "X-Mixr-Session": sessionId
1670
+ },
1671
+ body: JSON.stringify(body),
1672
+ signal: AbortSignal.timeout(AGENT_RUN_TIMEOUT)
1673
+ });
1674
+ if (!response.ok) {
1675
+ const error = await response.json().catch(() => ({}));
1676
+ throw new MixrPayError(error.error || `Agent run failed: ${response.status}`);
1677
+ }
1678
+ const data = await response.json();
1679
+ if (data.cost?.total_usd > 0) {
1680
+ const payment = {
1681
+ amountUsd: data.cost.total_usd,
1682
+ recipient: "mixrpay-agent-run",
1683
+ txHash: data.tx_hash,
1684
+ timestamp: /* @__PURE__ */ new Date(),
1685
+ description: `Agent run: ${data.run_id}`,
1686
+ url: `${this.baseUrl}/api/v2/agent/run`
1687
+ };
1688
+ this.payments.push(payment);
1689
+ this.totalSpentUsd += data.cost.total_usd;
1690
+ this.logger.payment(data.cost.total_usd, "agent-run", data.run_id);
1691
+ if (this.onPayment) {
1692
+ this.onPayment(payment);
1693
+ }
1694
+ }
1695
+ return {
1696
+ runId: data.run_id,
1697
+ status: data.status,
1698
+ response: data.response,
1699
+ iterations: data.iterations,
1700
+ toolsUsed: data.tools_used,
1701
+ cost: {
1702
+ llmUsd: data.cost.llm_usd,
1703
+ toolsUsd: data.cost.tools_usd,
1704
+ totalUsd: data.cost.total_usd
1705
+ },
1706
+ tokens: data.tokens,
1707
+ sessionRemainingUsd: data.session_remaining_usd,
1708
+ txHash: data.tx_hash
1709
+ };
1710
+ }
1711
+ return this.runAgentStreaming(sessionId, body, onEvent);
1712
+ }
1713
+ /**
1714
+ * Internal: Handle streaming agent run via SSE
1715
+ */
1716
+ async runAgentStreaming(sessionId, body, onEvent) {
1717
+ const STREAMING_TIMEOUT = 3e5;
1718
+ const response = await fetch(`${this.baseUrl}/api/v2/agent/run`, {
1719
+ method: "POST",
1720
+ headers: {
1721
+ "Content-Type": "application/json",
1722
+ "X-Mixr-Session": sessionId
1723
+ },
1724
+ body: JSON.stringify(body),
1725
+ signal: AbortSignal.timeout(STREAMING_TIMEOUT)
1726
+ });
1727
+ if (!response.ok) {
1728
+ const error = await response.json().catch(() => ({}));
1729
+ throw new MixrPayError(error.error || `Agent run failed: ${response.status}`);
1730
+ }
1731
+ const reader = response.body?.getReader();
1732
+ if (!reader) {
1733
+ throw new MixrPayError("No response body for streaming");
1734
+ }
1735
+ const decoder = new TextDecoder();
1736
+ let buffer = "";
1737
+ let result = null;
1738
+ while (true) {
1739
+ const { done, value } = await reader.read();
1740
+ if (done) break;
1741
+ buffer += decoder.decode(value, { stream: true });
1742
+ const lines = buffer.split("\n");
1743
+ buffer = lines.pop() || "";
1744
+ let currentEvent = "";
1745
+ for (const line of lines) {
1746
+ if (line.startsWith("event: ")) {
1747
+ currentEvent = line.slice(7).trim();
1748
+ } else if (line.startsWith("data: ") && currentEvent) {
1749
+ try {
1750
+ const data = JSON.parse(line.slice(6));
1751
+ const event = this.parseSSEEvent(currentEvent, data);
1752
+ if (event) {
1753
+ onEvent?.(event);
1754
+ if (currentEvent === "complete") {
1755
+ result = {
1756
+ runId: data.run_id,
1757
+ status: "completed",
1758
+ response: data.response,
1759
+ iterations: data.iterations,
1760
+ toolsUsed: data.tools_used,
1761
+ cost: {
1762
+ llmUsd: 0,
1763
+ // Not provided in streaming complete
1764
+ toolsUsd: 0,
1765
+ totalUsd: data.total_cost_usd
1766
+ },
1767
+ tokens: { prompt: 0, completion: 0 },
1768
+ sessionRemainingUsd: 0,
1769
+ txHash: data.tx_hash
1770
+ };
1771
+ if (data.total_cost_usd > 0) {
1772
+ const payment = {
1773
+ amountUsd: data.total_cost_usd,
1774
+ recipient: "mixrpay-agent-run",
1775
+ txHash: data.tx_hash,
1776
+ timestamp: /* @__PURE__ */ new Date(),
1777
+ description: `Agent run: ${data.run_id}`,
1778
+ url: `${this.baseUrl}/api/v2/agent/run`
1779
+ };
1780
+ this.payments.push(payment);
1781
+ this.totalSpentUsd += data.total_cost_usd;
1782
+ if (this.onPayment) {
1783
+ this.onPayment(payment);
1784
+ }
1785
+ }
1786
+ }
1787
+ if (currentEvent === "error") {
1788
+ throw new MixrPayError(data.error || "Agent run failed");
1789
+ }
1790
+ }
1791
+ } catch (e) {
1792
+ if (e instanceof MixrPayError) throw e;
1793
+ this.logger.warn("Failed to parse SSE event:", e);
1794
+ }
1795
+ currentEvent = "";
1796
+ }
1797
+ }
1798
+ }
1799
+ if (!result) {
1800
+ throw new MixrPayError("Agent run completed without final result");
1801
+ }
1802
+ return result;
1803
+ }
1804
+ /**
1805
+ * Internal: Parse SSE event into typed event object
1806
+ */
1807
+ parseSSEEvent(eventType, data) {
1808
+ switch (eventType) {
1809
+ case "run_start":
1810
+ return { type: "run_start", runId: data.run_id };
1811
+ case "iteration_start":
1812
+ return { type: "iteration_start", iteration: data.iteration };
1813
+ case "llm_chunk":
1814
+ return { type: "llm_chunk", delta: data.delta };
1815
+ case "tool_call":
1816
+ return { type: "tool_call", tool: data.tool, arguments: data.arguments };
1817
+ case "tool_result":
1818
+ return {
1819
+ type: "tool_result",
1820
+ tool: data.tool,
1821
+ success: data.success,
1822
+ costUsd: data.cost_usd,
1823
+ error: data.error
1824
+ };
1825
+ case "iteration_complete":
1826
+ return {
1827
+ type: "iteration_complete",
1828
+ iteration: data.iteration,
1829
+ tokens: data.tokens,
1830
+ costUsd: data.cost_usd
1831
+ };
1832
+ case "complete":
1833
+ return {
1834
+ type: "complete",
1835
+ runId: data.run_id,
1836
+ response: data.response,
1837
+ totalCostUsd: data.total_cost_usd,
1838
+ txHash: data.tx_hash,
1839
+ iterations: data.iterations,
1840
+ toolsUsed: data.tools_used
1841
+ };
1842
+ case "error":
1843
+ return {
1844
+ type: "error",
1845
+ error: data.error,
1846
+ partialCostUsd: data.partial_cost_usd
1847
+ };
1848
+ default:
1849
+ return null;
1850
+ }
1851
+ }
1852
+ /**
1853
+ * Get the status of an agent run by ID.
1854
+ *
1855
+ * @param runId - The agent run ID
1856
+ * @param sessionId - The session ID (for authentication)
1857
+ * @returns Agent run status and results
1858
+ *
1859
+ * @example
1860
+ * ```typescript
1861
+ * const status = await wallet.getAgentRunStatus('run_abc123', 'sess_xyz789');
1862
+ * console.log(`Status: ${status.status}`);
1863
+ * if (status.status === 'completed') {
1864
+ * console.log(status.response);
1865
+ * }
1866
+ * ```
1867
+ */
1868
+ async getAgentRunStatus(runId, sessionId) {
1869
+ this.logger.debug("getAgentRunStatus", { runId, sessionId });
1870
+ const response = await fetch(`${this.baseUrl}/api/v2/agent/run/${runId}`, {
1871
+ headers: {
1872
+ "X-Mixr-Session": sessionId
1873
+ }
1874
+ });
1875
+ if (!response.ok) {
1876
+ const error = await response.json().catch(() => ({}));
1877
+ throw new MixrPayError(error.error || `Failed to get run status: ${response.status}`);
1878
+ }
1879
+ const data = await response.json();
1880
+ return {
1881
+ runId: data.run_id,
1882
+ status: data.status,
1883
+ response: data.response,
1884
+ iterations: data.iterations,
1885
+ toolsUsed: data.tools_used,
1886
+ cost: {
1887
+ llmUsd: data.cost.llm_usd,
1888
+ toolsUsd: data.cost.tools_usd,
1889
+ totalUsd: data.cost.total_usd
1890
+ },
1891
+ tokens: data.tokens,
1892
+ txHash: data.tx_hash,
1893
+ error: data.error,
1894
+ startedAt: new Date(data.started_at),
1895
+ completedAt: data.completed_at ? new Date(data.completed_at) : void 0
1896
+ };
1897
+ }
1898
+ /**
1899
+ * Call an MCP tool using session authorization (pre-authorized spending limit).
1900
+ *
1901
+ * Use this when you've already created a session with the tool provider
1902
+ * and want to use that spending limit instead of direct wallet charges.
1903
+ *
1904
+ * @param sessionId - The session ID for the tool provider
1905
+ * @param toolName - The tool name in format "merchant/tool"
1906
+ * @param args - Arguments to pass to the tool
1907
+ * @returns Tool execution result
1908
+ *
1909
+ * @example
1910
+ * ```typescript
1911
+ * // Create session with provider first
1912
+ * const session = await wallet.getOrCreateSession({
1913
+ * merchantPublicKey: 'pk_live_firecrawl_...',
1914
+ * spendingLimitUsd: 50,
1915
+ * });
1916
+ *
1917
+ * // Use session for multiple calls
1918
+ * const result = await wallet.callMCPToolWithSession(
1919
+ * session.id,
1920
+ * 'firecrawl/scrape',
1921
+ * { url: 'https://example.com' }
1922
+ * );
1923
+ * ```
1924
+ */
1925
+ async callMCPToolWithSession(sessionId, toolName, args = {}) {
1926
+ this.logger.debug("callMCPToolWithSession", { sessionId, toolName, args });
1927
+ const response = await fetch(`${this.baseUrl}/api/mcp`, {
1928
+ method: "POST",
1929
+ headers: {
1930
+ "Content-Type": "application/json",
1931
+ "X-Mixr-Session": sessionId
1932
+ },
1933
+ body: JSON.stringify({
1934
+ jsonrpc: "2.0",
1935
+ method: "tools/call",
1936
+ params: { name: toolName, arguments: args },
1937
+ id: Date.now()
1938
+ })
1939
+ });
1940
+ const result = await response.json();
1941
+ if (result.error) {
1942
+ throw new MixrPayError(result.error.message || "MCP tool call failed");
1943
+ }
1944
+ const content = result.result?.content?.[0];
1945
+ const data = content?.text ? JSON.parse(content.text) : null;
1946
+ const mixrpay = result.result?._mixrpay || {};
1947
+ if (mixrpay.chargedUsd) {
1948
+ const payment = {
1949
+ amountUsd: mixrpay.chargedUsd,
1950
+ recipient: toolName.split("/")[0] || toolName,
1951
+ txHash: mixrpay.txHash,
1952
+ timestamp: /* @__PURE__ */ new Date(),
1953
+ description: `MCP: ${toolName}`,
1954
+ url: `${this.baseUrl}/api/mcp`
1955
+ };
1956
+ this.payments.push(payment);
1957
+ this.totalSpentUsd += mixrpay.chargedUsd;
1958
+ this.logger.payment(mixrpay.chargedUsd, toolName, "MCP call (session)");
1959
+ if (this.onPayment) {
1960
+ this.onPayment(payment);
1961
+ }
1962
+ }
1963
+ return {
1964
+ data,
1965
+ chargedUsd: mixrpay.chargedUsd || 0,
1966
+ txHash: mixrpay.txHash,
1967
+ latencyMs: mixrpay.latencyMs
1968
+ };
1969
+ }
1970
+ };
1971
+ export {
1972
+ AgentWallet,
1973
+ InsufficientBalanceError,
1974
+ InvalidSessionKeyError,
1975
+ MixrPayError,
1976
+ PaymentFailedError,
1977
+ SDK_VERSION,
1978
+ SessionExpiredError,
1979
+ SessionKeyExpiredError,
1980
+ SessionLimitExceededError,
1981
+ SessionNotFoundError,
1982
+ SessionRevokedError,
1983
+ SpendingLimitExceededError,
1984
+ isMixrPayError
1985
+ };