@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.
- package/README.md +508 -0
- package/dist/index.cjs +982 -0
- package/dist/index.d.cts +961 -0
- package/dist/index.d.ts +961 -0
- package/dist/index.js +936 -0
- package/package.json +77 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,936 @@
|
|
|
1
|
+
// src/session-key.ts
|
|
2
|
+
import {
|
|
3
|
+
privateKeyToAccount,
|
|
4
|
+
signTypedData
|
|
5
|
+
} from "viem/accounts";
|
|
6
|
+
|
|
7
|
+
// src/errors.ts
|
|
8
|
+
var MixrPayError = class extends Error {
|
|
9
|
+
/** Error code for programmatic handling */
|
|
10
|
+
code;
|
|
11
|
+
constructor(message, code = "MIXRPAY_ERROR") {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "MixrPayError";
|
|
14
|
+
this.code = code;
|
|
15
|
+
if (Error.captureStackTrace) {
|
|
16
|
+
Error.captureStackTrace(this, this.constructor);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
var InsufficientBalanceError = class extends MixrPayError {
|
|
21
|
+
/** Amount required for the payment in USD */
|
|
22
|
+
required;
|
|
23
|
+
/** Current available balance in USD */
|
|
24
|
+
available;
|
|
25
|
+
/** URL where the user can top up their wallet */
|
|
26
|
+
topUpUrl;
|
|
27
|
+
constructor(required, available) {
|
|
28
|
+
const shortage = required - available;
|
|
29
|
+
super(
|
|
30
|
+
`Insufficient balance: need $${required.toFixed(2)}, have $${available.toFixed(2)} (short $${shortage.toFixed(2)}). Top up your wallet to continue.`,
|
|
31
|
+
"INSUFFICIENT_BALANCE"
|
|
32
|
+
);
|
|
33
|
+
this.name = "InsufficientBalanceError";
|
|
34
|
+
this.required = required;
|
|
35
|
+
this.available = available;
|
|
36
|
+
this.topUpUrl = "/wallet";
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
var SessionKeyExpiredError = class extends MixrPayError {
|
|
40
|
+
/** When the session key expired */
|
|
41
|
+
expiredAt;
|
|
42
|
+
constructor(expiredAt) {
|
|
43
|
+
super(
|
|
44
|
+
`Session key expired at ${expiredAt}. Request a new session key from the wallet owner or create one at your MixrPay server /wallet/sessions`,
|
|
45
|
+
"SESSION_KEY_EXPIRED"
|
|
46
|
+
);
|
|
47
|
+
this.name = "SessionKeyExpiredError";
|
|
48
|
+
this.expiredAt = expiredAt;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
var SpendingLimitExceededError = class extends MixrPayError {
|
|
52
|
+
/** Type of limit that was exceeded */
|
|
53
|
+
limitType;
|
|
54
|
+
/** The limit amount in USD */
|
|
55
|
+
limit;
|
|
56
|
+
/** The amount that was attempted in USD */
|
|
57
|
+
attempted;
|
|
58
|
+
constructor(limitType, limit, attempted) {
|
|
59
|
+
const limitNames = {
|
|
60
|
+
per_tx: "Per-transaction",
|
|
61
|
+
daily: "Daily",
|
|
62
|
+
total: "Total",
|
|
63
|
+
client_max: "Client-side"
|
|
64
|
+
};
|
|
65
|
+
const limitName = limitNames[limitType] || limitType;
|
|
66
|
+
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.";
|
|
67
|
+
super(
|
|
68
|
+
`${limitName} spending limit exceeded: limit is $${limit.toFixed(2)}, attempted $${attempted.toFixed(2)}. ${suggestion}`,
|
|
69
|
+
"SPENDING_LIMIT_EXCEEDED"
|
|
70
|
+
);
|
|
71
|
+
this.name = "SpendingLimitExceededError";
|
|
72
|
+
this.limitType = limitType;
|
|
73
|
+
this.limit = limit;
|
|
74
|
+
this.attempted = attempted;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
var PaymentFailedError = class extends MixrPayError {
|
|
78
|
+
/** Detailed reason for the failure */
|
|
79
|
+
reason;
|
|
80
|
+
/** Transaction hash if the tx was submitted (for debugging) */
|
|
81
|
+
txHash;
|
|
82
|
+
constructor(reason, txHash) {
|
|
83
|
+
let message = `Payment failed: ${reason}`;
|
|
84
|
+
if (txHash) {
|
|
85
|
+
message += ` (tx: ${txHash} - check on basescan.org)`;
|
|
86
|
+
}
|
|
87
|
+
super(message, "PAYMENT_FAILED");
|
|
88
|
+
this.name = "PaymentFailedError";
|
|
89
|
+
this.reason = reason;
|
|
90
|
+
this.txHash = txHash;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
var InvalidSessionKeyError = class extends MixrPayError {
|
|
94
|
+
/** Detailed reason why the key is invalid */
|
|
95
|
+
reason;
|
|
96
|
+
constructor(reason = "Invalid session key format") {
|
|
97
|
+
super(
|
|
98
|
+
`${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`,
|
|
99
|
+
"INVALID_SESSION_KEY"
|
|
100
|
+
);
|
|
101
|
+
this.name = "InvalidSessionKeyError";
|
|
102
|
+
this.reason = reason;
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
var X402ProtocolError = class extends MixrPayError {
|
|
106
|
+
/** Detailed reason for the protocol error */
|
|
107
|
+
reason;
|
|
108
|
+
constructor(reason) {
|
|
109
|
+
super(
|
|
110
|
+
`x402 protocol error: ${reason}. This may indicate a server configuration issue. If the problem persists, contact the API provider.`,
|
|
111
|
+
"X402_PROTOCOL_ERROR"
|
|
112
|
+
);
|
|
113
|
+
this.name = "X402ProtocolError";
|
|
114
|
+
this.reason = reason;
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
function isMixrPayError(error) {
|
|
118
|
+
return error instanceof MixrPayError;
|
|
119
|
+
}
|
|
120
|
+
function getErrorMessage(error) {
|
|
121
|
+
if (error instanceof MixrPayError) {
|
|
122
|
+
return error.message;
|
|
123
|
+
}
|
|
124
|
+
if (error instanceof Error) {
|
|
125
|
+
return error.message;
|
|
126
|
+
}
|
|
127
|
+
return String(error);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// src/session-key.ts
|
|
131
|
+
var USDC_ADDRESSES = {
|
|
132
|
+
8453: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
133
|
+
// Base Mainnet
|
|
134
|
+
84532: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
|
|
135
|
+
// Base Sepolia
|
|
136
|
+
};
|
|
137
|
+
var USDC_EIP712_DOMAIN_BASE = {
|
|
138
|
+
name: "USD Coin",
|
|
139
|
+
version: "2"
|
|
140
|
+
};
|
|
141
|
+
var TRANSFER_WITH_AUTHORIZATION_TYPES = {
|
|
142
|
+
TransferWithAuthorization: [
|
|
143
|
+
{ name: "from", type: "address" },
|
|
144
|
+
{ name: "to", type: "address" },
|
|
145
|
+
{ name: "value", type: "uint256" },
|
|
146
|
+
{ name: "validAfter", type: "uint256" },
|
|
147
|
+
{ name: "validBefore", type: "uint256" },
|
|
148
|
+
{ name: "nonce", type: "bytes32" }
|
|
149
|
+
]
|
|
150
|
+
};
|
|
151
|
+
var SessionKey = class _SessionKey {
|
|
152
|
+
privateKey;
|
|
153
|
+
account;
|
|
154
|
+
address;
|
|
155
|
+
isTest;
|
|
156
|
+
constructor(privateKey, isTest) {
|
|
157
|
+
this.privateKey = privateKey;
|
|
158
|
+
this.account = privateKeyToAccount(privateKey);
|
|
159
|
+
this.address = this.account.address;
|
|
160
|
+
this.isTest = isTest;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Parse a session key string into a SessionKey object.
|
|
164
|
+
*
|
|
165
|
+
* @param sessionKey - Session key in format sk_live_... or sk_test_...
|
|
166
|
+
* @returns SessionKey object
|
|
167
|
+
* @throws InvalidSessionKeyError if the format is invalid
|
|
168
|
+
*/
|
|
169
|
+
static fromString(sessionKey) {
|
|
170
|
+
const pattern = /^sk_(live|test)_([a-fA-F0-9]{64})$/;
|
|
171
|
+
const match = sessionKey.match(pattern);
|
|
172
|
+
if (!match) {
|
|
173
|
+
throw new InvalidSessionKeyError(
|
|
174
|
+
"Session key must be in format sk_live_{64_hex} or sk_test_{64_hex}"
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
const env = match[1];
|
|
178
|
+
const hexKey = match[2];
|
|
179
|
+
try {
|
|
180
|
+
const privateKey = `0x${hexKey}`;
|
|
181
|
+
return new _SessionKey(privateKey, env === "test");
|
|
182
|
+
} catch (e) {
|
|
183
|
+
throw new InvalidSessionKeyError(`Failed to decode session key: ${e}`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Sign EIP-712 typed data for TransferWithAuthorization.
|
|
188
|
+
*
|
|
189
|
+
* @param domain - EIP-712 domain
|
|
190
|
+
* @param message - Transfer authorization message
|
|
191
|
+
* @returns Hex-encoded signature
|
|
192
|
+
*/
|
|
193
|
+
async signTransferAuthorization(domain, message) {
|
|
194
|
+
return signTypedData({
|
|
195
|
+
privateKey: this.privateKey,
|
|
196
|
+
domain,
|
|
197
|
+
types: TRANSFER_WITH_AUTHORIZATION_TYPES,
|
|
198
|
+
primaryType: "TransferWithAuthorization",
|
|
199
|
+
message
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Get the chain ID based on whether this is a test key.
|
|
204
|
+
*/
|
|
205
|
+
getDefaultChainId() {
|
|
206
|
+
return this.isTest ? 84532 : 8453;
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
function buildTransferAuthorizationData(params) {
|
|
210
|
+
const usdcAddress = USDC_ADDRESSES[params.chainId];
|
|
211
|
+
if (!usdcAddress) {
|
|
212
|
+
throw new Error(`USDC not supported on chain ${params.chainId}`);
|
|
213
|
+
}
|
|
214
|
+
const domain = {
|
|
215
|
+
...USDC_EIP712_DOMAIN_BASE,
|
|
216
|
+
chainId: params.chainId,
|
|
217
|
+
verifyingContract: usdcAddress
|
|
218
|
+
};
|
|
219
|
+
const message = {
|
|
220
|
+
from: params.fromAddress,
|
|
221
|
+
to: params.toAddress,
|
|
222
|
+
value: params.value,
|
|
223
|
+
validAfter: params.validAfter,
|
|
224
|
+
validBefore: params.validBefore,
|
|
225
|
+
nonce: params.nonce
|
|
226
|
+
};
|
|
227
|
+
return { domain, message };
|
|
228
|
+
}
|
|
229
|
+
function generateNonce() {
|
|
230
|
+
const bytes = new Uint8Array(32);
|
|
231
|
+
crypto.getRandomValues(bytes);
|
|
232
|
+
return `0x${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// src/x402.ts
|
|
236
|
+
async function parse402Response(response) {
|
|
237
|
+
let paymentData = null;
|
|
238
|
+
const paymentHeader = response.headers.get("X-Payment-Required");
|
|
239
|
+
if (paymentHeader) {
|
|
240
|
+
try {
|
|
241
|
+
paymentData = JSON.parse(paymentHeader);
|
|
242
|
+
} catch {
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
if (!paymentData) {
|
|
246
|
+
const authHeader = response.headers.get("WWW-Authenticate");
|
|
247
|
+
if (authHeader?.startsWith("X-402 ")) {
|
|
248
|
+
try {
|
|
249
|
+
const encoded = authHeader.slice(6);
|
|
250
|
+
paymentData = JSON.parse(atob(encoded));
|
|
251
|
+
} catch {
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (!paymentData) {
|
|
256
|
+
try {
|
|
257
|
+
paymentData = await response.json();
|
|
258
|
+
} catch {
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if (!paymentData) {
|
|
262
|
+
throw new X402ProtocolError("Could not parse payment requirements from 402 response");
|
|
263
|
+
}
|
|
264
|
+
if (!paymentData.recipient) {
|
|
265
|
+
throw new X402ProtocolError("Missing recipient in payment requirements");
|
|
266
|
+
}
|
|
267
|
+
if (!paymentData.amount) {
|
|
268
|
+
throw new X402ProtocolError("Missing amount in payment requirements");
|
|
269
|
+
}
|
|
270
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
271
|
+
return {
|
|
272
|
+
recipient: paymentData.recipient,
|
|
273
|
+
amount: BigInt(paymentData.amount),
|
|
274
|
+
currency: paymentData.currency || "USDC",
|
|
275
|
+
chainId: paymentData.chainId || paymentData.chain_id || 8453,
|
|
276
|
+
facilitatorUrl: paymentData.facilitatorUrl || paymentData.facilitator_url || "https://x402.org/facilitator",
|
|
277
|
+
nonce: paymentData.nonce || generateNonce().slice(2),
|
|
278
|
+
// Remove 0x prefix for storage
|
|
279
|
+
expiresAt: paymentData.expiresAt || paymentData.expires_at || now + 300,
|
|
280
|
+
description: paymentData.description
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
async function buildXPaymentHeader(requirements, sessionKey, walletAddress) {
|
|
284
|
+
const nonceHex = requirements.nonce.length === 64 ? `0x${requirements.nonce}` : generateNonce();
|
|
285
|
+
const now = BigInt(Math.floor(Date.now() / 1e3));
|
|
286
|
+
const validAfter = now - 60n;
|
|
287
|
+
const validBefore = BigInt(requirements.expiresAt);
|
|
288
|
+
const { domain, message } = buildTransferAuthorizationData({
|
|
289
|
+
fromAddress: walletAddress,
|
|
290
|
+
toAddress: requirements.recipient,
|
|
291
|
+
value: requirements.amount,
|
|
292
|
+
validAfter,
|
|
293
|
+
validBefore,
|
|
294
|
+
nonce: nonceHex,
|
|
295
|
+
chainId: requirements.chainId
|
|
296
|
+
});
|
|
297
|
+
const signature = await sessionKey.signTransferAuthorization(domain, message);
|
|
298
|
+
const paymentPayload = {
|
|
299
|
+
x402Version: 1,
|
|
300
|
+
scheme: "exact",
|
|
301
|
+
network: requirements.chainId === 8453 ? "base" : "base-sepolia",
|
|
302
|
+
payload: {
|
|
303
|
+
signature,
|
|
304
|
+
authorization: {
|
|
305
|
+
from: walletAddress,
|
|
306
|
+
to: requirements.recipient,
|
|
307
|
+
value: requirements.amount.toString(),
|
|
308
|
+
validAfter: validAfter.toString(),
|
|
309
|
+
validBefore: validBefore.toString(),
|
|
310
|
+
nonce: nonceHex
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
return btoa(JSON.stringify(paymentPayload));
|
|
315
|
+
}
|
|
316
|
+
function isPaymentExpired(requirements) {
|
|
317
|
+
return Date.now() / 1e3 > requirements.expiresAt;
|
|
318
|
+
}
|
|
319
|
+
function getAmountUsd(requirements) {
|
|
320
|
+
return Number(requirements.amount) / 1e6;
|
|
321
|
+
}
|
|
322
|
+
function validatePaymentAmount(amountUsd, maxPaymentUsd) {
|
|
323
|
+
if (amountUsd <= 0) {
|
|
324
|
+
throw new X402ProtocolError(`Invalid payment amount: $${amountUsd.toFixed(2)}`);
|
|
325
|
+
}
|
|
326
|
+
if (maxPaymentUsd !== void 0 && amountUsd > maxPaymentUsd) {
|
|
327
|
+
throw new X402ProtocolError(
|
|
328
|
+
`Payment amount $${amountUsd.toFixed(2)} exceeds client limit $${maxPaymentUsd.toFixed(2)}`
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// src/agent-wallet.ts
|
|
334
|
+
var SDK_VERSION = "0.1.0";
|
|
335
|
+
var DEFAULT_BASE_URL = process.env.MIXRPAY_BASE_URL || "http://localhost:3000";
|
|
336
|
+
var DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
|
|
337
|
+
var DEFAULT_TIMEOUT = 3e4;
|
|
338
|
+
var NETWORKS = {
|
|
339
|
+
BASE_MAINNET: { chainId: 8453, name: "Base", isTestnet: false },
|
|
340
|
+
BASE_SEPOLIA: { chainId: 84532, name: "Base Sepolia", isTestnet: true }
|
|
341
|
+
};
|
|
342
|
+
var LOG_LEVELS = {
|
|
343
|
+
debug: 0,
|
|
344
|
+
info: 1,
|
|
345
|
+
warn: 2,
|
|
346
|
+
error: 3,
|
|
347
|
+
none: 4
|
|
348
|
+
};
|
|
349
|
+
var Logger = class {
|
|
350
|
+
level;
|
|
351
|
+
prefix;
|
|
352
|
+
constructor(level = "none", prefix = "[MixrPay]") {
|
|
353
|
+
this.level = level;
|
|
354
|
+
this.prefix = prefix;
|
|
355
|
+
}
|
|
356
|
+
setLevel(level) {
|
|
357
|
+
this.level = level;
|
|
358
|
+
}
|
|
359
|
+
shouldLog(level) {
|
|
360
|
+
return LOG_LEVELS[level] >= LOG_LEVELS[this.level];
|
|
361
|
+
}
|
|
362
|
+
debug(...args) {
|
|
363
|
+
if (this.shouldLog("debug")) {
|
|
364
|
+
console.log(`${this.prefix} \u{1F50D}`, ...args);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
info(...args) {
|
|
368
|
+
if (this.shouldLog("info")) {
|
|
369
|
+
console.log(`${this.prefix} \u2139\uFE0F`, ...args);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
warn(...args) {
|
|
373
|
+
if (this.shouldLog("warn")) {
|
|
374
|
+
console.warn(`${this.prefix} \u26A0\uFE0F`, ...args);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
error(...args) {
|
|
378
|
+
if (this.shouldLog("error")) {
|
|
379
|
+
console.error(`${this.prefix} \u274C`, ...args);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
payment(amount, recipient, description) {
|
|
383
|
+
if (this.shouldLog("info")) {
|
|
384
|
+
const desc = description ? ` for "${description}"` : "";
|
|
385
|
+
console.log(`${this.prefix} \u{1F4B8} Paid $${amount.toFixed(4)} to ${recipient.slice(0, 10)}...${desc}`);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
var AgentWallet = class {
|
|
390
|
+
sessionKey;
|
|
391
|
+
walletAddress;
|
|
392
|
+
maxPaymentUsd;
|
|
393
|
+
onPayment;
|
|
394
|
+
baseUrl;
|
|
395
|
+
timeout;
|
|
396
|
+
logger;
|
|
397
|
+
// Payment tracking
|
|
398
|
+
payments = [];
|
|
399
|
+
totalSpentUsd = 0;
|
|
400
|
+
// Session key info cache
|
|
401
|
+
sessionKeyInfo;
|
|
402
|
+
sessionKeyInfoFetchedAt;
|
|
403
|
+
/**
|
|
404
|
+
* Create a new AgentWallet instance.
|
|
405
|
+
*
|
|
406
|
+
* @param config - Configuration options
|
|
407
|
+
* @throws {InvalidSessionKeyError} If the session key format is invalid
|
|
408
|
+
*
|
|
409
|
+
* @example Basic initialization
|
|
410
|
+
* ```typescript
|
|
411
|
+
* const wallet = new AgentWallet({
|
|
412
|
+
* sessionKey: 'sk_live_abc123...'
|
|
413
|
+
* });
|
|
414
|
+
* ```
|
|
415
|
+
*
|
|
416
|
+
* @example With all options
|
|
417
|
+
* ```typescript
|
|
418
|
+
* const wallet = new AgentWallet({
|
|
419
|
+
* sessionKey: 'sk_live_abc123...',
|
|
420
|
+
* maxPaymentUsd: 5.0, // Client-side safety limit
|
|
421
|
+
* onPayment: (p) => log(p), // Track payments
|
|
422
|
+
* logLevel: 'info', // Enable logging
|
|
423
|
+
* timeout: 60000, // 60s timeout
|
|
424
|
+
* });
|
|
425
|
+
* ```
|
|
426
|
+
*/
|
|
427
|
+
constructor(config) {
|
|
428
|
+
this.validateConfig(config);
|
|
429
|
+
this.sessionKey = SessionKey.fromString(config.sessionKey);
|
|
430
|
+
this.walletAddress = config.walletAddress || this.sessionKey.address;
|
|
431
|
+
this.maxPaymentUsd = config.maxPaymentUsd;
|
|
432
|
+
this.onPayment = config.onPayment;
|
|
433
|
+
this.baseUrl = (config.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
434
|
+
this.timeout = config.timeout || DEFAULT_TIMEOUT;
|
|
435
|
+
this.logger = new Logger(config.logLevel || "none");
|
|
436
|
+
this.logger.debug("AgentWallet initialized", {
|
|
437
|
+
walletAddress: this.walletAddress,
|
|
438
|
+
isTestnet: this.isTestnet(),
|
|
439
|
+
maxPaymentUsd: this.maxPaymentUsd
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Validate the configuration before initialization.
|
|
444
|
+
*/
|
|
445
|
+
validateConfig(config) {
|
|
446
|
+
if (!config.sessionKey) {
|
|
447
|
+
throw new InvalidSessionKeyError(
|
|
448
|
+
"Session key is required. Get one from the wallet owner or create one at your MixrPay server /wallet/sessions"
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
const key = config.sessionKey.trim();
|
|
452
|
+
if (!key.startsWith("sk_live_") && !key.startsWith("sk_test_")) {
|
|
453
|
+
throw new InvalidSessionKeyError(
|
|
454
|
+
`Invalid session key prefix. Expected 'sk_live_' (mainnet) or 'sk_test_' (testnet), got '${key.slice(0, 10)}...'`
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
const expectedLength = 8 + 64;
|
|
458
|
+
if (key.length !== expectedLength) {
|
|
459
|
+
throw new InvalidSessionKeyError(
|
|
460
|
+
`Invalid session key length. Expected ${expectedLength} characters, got ${key.length}. Make sure you copied the complete key.`
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
const hexPortion = key.slice(8);
|
|
464
|
+
if (!/^[0-9a-fA-F]+$/.test(hexPortion)) {
|
|
465
|
+
throw new InvalidSessionKeyError(
|
|
466
|
+
"Invalid session key format. The key should contain only hexadecimal characters after the prefix."
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
if (config.maxPaymentUsd !== void 0) {
|
|
470
|
+
if (config.maxPaymentUsd <= 0) {
|
|
471
|
+
throw new MixrPayError("maxPaymentUsd must be a positive number");
|
|
472
|
+
}
|
|
473
|
+
if (config.maxPaymentUsd > 1e4) {
|
|
474
|
+
this.logger?.warn("maxPaymentUsd is very high ($" + config.maxPaymentUsd + "). Consider using a lower limit for safety.");
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
// ===========================================================================
|
|
479
|
+
// Core Methods
|
|
480
|
+
// ===========================================================================
|
|
481
|
+
/**
|
|
482
|
+
* Make an HTTP request, automatically handling x402 payment if required.
|
|
483
|
+
*
|
|
484
|
+
* This is a drop-in replacement for the native `fetch()` function.
|
|
485
|
+
* If the server returns 402 Payment Required:
|
|
486
|
+
* 1. Parse payment requirements from response
|
|
487
|
+
* 2. Sign transferWithAuthorization using session key
|
|
488
|
+
* 3. Retry request with X-PAYMENT header
|
|
489
|
+
*
|
|
490
|
+
* @param url - Request URL
|
|
491
|
+
* @param init - Request options (same as native fetch)
|
|
492
|
+
* @returns Response from the server
|
|
493
|
+
*
|
|
494
|
+
* @throws {InsufficientBalanceError} If wallet doesn't have enough USDC
|
|
495
|
+
* @throws {SessionKeyExpiredError} If session key has expired
|
|
496
|
+
* @throws {SpendingLimitExceededError} If payment would exceed limits
|
|
497
|
+
* @throws {PaymentFailedError} If payment transaction failed
|
|
498
|
+
*
|
|
499
|
+
* @example GET request
|
|
500
|
+
* ```typescript
|
|
501
|
+
* const response = await wallet.fetch('https://api.example.com/data');
|
|
502
|
+
* const data = await response.json();
|
|
503
|
+
* ```
|
|
504
|
+
*
|
|
505
|
+
* @example POST request with JSON
|
|
506
|
+
* ```typescript
|
|
507
|
+
* const response = await wallet.fetch('https://api.example.com/generate', {
|
|
508
|
+
* method: 'POST',
|
|
509
|
+
* headers: { 'Content-Type': 'application/json' },
|
|
510
|
+
* body: JSON.stringify({ prompt: 'Hello world' })
|
|
511
|
+
* });
|
|
512
|
+
* ```
|
|
513
|
+
*/
|
|
514
|
+
async fetch(url, init) {
|
|
515
|
+
this.logger.debug(`Fetching ${init?.method || "GET"} ${url}`);
|
|
516
|
+
const controller = new AbortController();
|
|
517
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
518
|
+
try {
|
|
519
|
+
let response = await fetch(url, {
|
|
520
|
+
...init,
|
|
521
|
+
signal: controller.signal
|
|
522
|
+
});
|
|
523
|
+
this.logger.debug(`Initial response: ${response.status}`);
|
|
524
|
+
if (response.status === 402) {
|
|
525
|
+
this.logger.info(`Payment required for ${url}`);
|
|
526
|
+
response = await this.handlePaymentRequired(url, init, response);
|
|
527
|
+
}
|
|
528
|
+
return response;
|
|
529
|
+
} catch (error) {
|
|
530
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
531
|
+
throw new MixrPayError(`Request timeout after ${this.timeout}ms`);
|
|
532
|
+
}
|
|
533
|
+
throw error;
|
|
534
|
+
} finally {
|
|
535
|
+
clearTimeout(timeoutId);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Handle a 402 Payment Required response.
|
|
540
|
+
*/
|
|
541
|
+
async handlePaymentRequired(url, init, response) {
|
|
542
|
+
let requirements;
|
|
543
|
+
try {
|
|
544
|
+
requirements = await parse402Response(response);
|
|
545
|
+
this.logger.debug("Payment requirements:", {
|
|
546
|
+
amount: `$${getAmountUsd(requirements).toFixed(4)}`,
|
|
547
|
+
recipient: requirements.recipient,
|
|
548
|
+
description: requirements.description
|
|
549
|
+
});
|
|
550
|
+
} catch (e) {
|
|
551
|
+
this.logger.error("Failed to parse payment requirements:", e);
|
|
552
|
+
throw new PaymentFailedError(
|
|
553
|
+
`Failed to parse payment requirements: ${e}. The server may not be properly configured for x402 payments.`
|
|
554
|
+
);
|
|
555
|
+
}
|
|
556
|
+
if (isPaymentExpired(requirements)) {
|
|
557
|
+
throw new PaymentFailedError(
|
|
558
|
+
"Payment requirements have expired. This usually means the request took too long. Try again."
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
const amountUsd = getAmountUsd(requirements);
|
|
562
|
+
if (this.maxPaymentUsd !== void 0 && amountUsd > this.maxPaymentUsd) {
|
|
563
|
+
throw new SpendingLimitExceededError(
|
|
564
|
+
"client_max",
|
|
565
|
+
this.maxPaymentUsd,
|
|
566
|
+
amountUsd
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
let xPayment;
|
|
570
|
+
try {
|
|
571
|
+
this.logger.debug("Signing payment authorization...");
|
|
572
|
+
xPayment = await buildXPaymentHeader(
|
|
573
|
+
requirements,
|
|
574
|
+
this.sessionKey,
|
|
575
|
+
this.walletAddress
|
|
576
|
+
);
|
|
577
|
+
} catch (e) {
|
|
578
|
+
this.logger.error("Failed to sign payment:", e);
|
|
579
|
+
throw new PaymentFailedError(
|
|
580
|
+
`Failed to sign payment: ${e}. This may indicate an issue with the session key.`
|
|
581
|
+
);
|
|
582
|
+
}
|
|
583
|
+
this.logger.debug("Retrying request with payment...");
|
|
584
|
+
const headers = new Headers(init?.headers);
|
|
585
|
+
headers.set("X-PAYMENT", xPayment);
|
|
586
|
+
const retryResponse = await fetch(url, {
|
|
587
|
+
...init,
|
|
588
|
+
headers
|
|
589
|
+
});
|
|
590
|
+
if (retryResponse.status !== 402) {
|
|
591
|
+
const payment = {
|
|
592
|
+
amountUsd,
|
|
593
|
+
recipient: requirements.recipient,
|
|
594
|
+
txHash: retryResponse.headers.get("X-Payment-TxHash"),
|
|
595
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
596
|
+
description: requirements.description,
|
|
597
|
+
url
|
|
598
|
+
};
|
|
599
|
+
this.payments.push(payment);
|
|
600
|
+
this.totalSpentUsd += amountUsd;
|
|
601
|
+
this.logger.payment(amountUsd, requirements.recipient, requirements.description);
|
|
602
|
+
if (this.onPayment) {
|
|
603
|
+
this.onPayment(payment);
|
|
604
|
+
}
|
|
605
|
+
} else {
|
|
606
|
+
await this.handlePaymentError(retryResponse);
|
|
607
|
+
}
|
|
608
|
+
return retryResponse;
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Handle payment-specific errors from the response.
|
|
612
|
+
*/
|
|
613
|
+
async handlePaymentError(response) {
|
|
614
|
+
let errorData = {};
|
|
615
|
+
try {
|
|
616
|
+
errorData = await response.json();
|
|
617
|
+
} catch {
|
|
618
|
+
}
|
|
619
|
+
const errorCode = errorData.error_code || "";
|
|
620
|
+
const errorMessage = errorData.error || errorData.message || "Payment required";
|
|
621
|
+
this.logger.error("Payment failed:", { errorCode, errorMessage, errorData });
|
|
622
|
+
if (errorCode === "insufficient_balance") {
|
|
623
|
+
const required = errorData.required || 0;
|
|
624
|
+
const available = errorData.available || 0;
|
|
625
|
+
throw new InsufficientBalanceError(required, available);
|
|
626
|
+
} else if (errorCode === "session_key_expired") {
|
|
627
|
+
throw new SessionKeyExpiredError(errorData.expired_at || "unknown");
|
|
628
|
+
} else if (errorCode === "spending_limit_exceeded") {
|
|
629
|
+
throw new SpendingLimitExceededError(
|
|
630
|
+
errorData.limit_type || "unknown",
|
|
631
|
+
errorData.limit || 0,
|
|
632
|
+
errorData.attempted || 0
|
|
633
|
+
);
|
|
634
|
+
} else {
|
|
635
|
+
throw new PaymentFailedError(errorMessage);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
// ===========================================================================
|
|
639
|
+
// Wallet Information
|
|
640
|
+
// ===========================================================================
|
|
641
|
+
/**
|
|
642
|
+
* Get the wallet address.
|
|
643
|
+
*
|
|
644
|
+
* @returns The Ethereum address of the smart wallet
|
|
645
|
+
*/
|
|
646
|
+
getWalletAddress() {
|
|
647
|
+
return this.walletAddress;
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Check if using testnet session key.
|
|
651
|
+
*
|
|
652
|
+
* @returns true if using Base Sepolia (testnet), false if using Base Mainnet
|
|
653
|
+
*/
|
|
654
|
+
isTestnet() {
|
|
655
|
+
return this.sessionKey.isTest;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Get the network information.
|
|
659
|
+
*
|
|
660
|
+
* @returns Network details including chain ID and name
|
|
661
|
+
*/
|
|
662
|
+
getNetwork() {
|
|
663
|
+
return this.isTestnet() ? NETWORKS.BASE_SEPOLIA : NETWORKS.BASE_MAINNET;
|
|
664
|
+
}
|
|
665
|
+
/**
|
|
666
|
+
* Get current USDC balance of the wallet.
|
|
667
|
+
*
|
|
668
|
+
* @returns USDC balance in USD
|
|
669
|
+
*
|
|
670
|
+
* @example
|
|
671
|
+
* ```typescript
|
|
672
|
+
* const balance = await wallet.getBalance();
|
|
673
|
+
* console.log(`Balance: $${balance.toFixed(2)}`);
|
|
674
|
+
* ```
|
|
675
|
+
*/
|
|
676
|
+
async getBalance() {
|
|
677
|
+
this.logger.debug("Fetching wallet balance...");
|
|
678
|
+
try {
|
|
679
|
+
const response = await fetch(`${this.baseUrl}/v1/wallet/balance`, {
|
|
680
|
+
headers: {
|
|
681
|
+
"X-Session-Key": this.sessionKey.address
|
|
682
|
+
}
|
|
683
|
+
});
|
|
684
|
+
if (response.ok) {
|
|
685
|
+
const data = await response.json();
|
|
686
|
+
const balance = data.balance_usd || data.balanceUsd || 0;
|
|
687
|
+
this.logger.debug(`Balance: $${balance}`);
|
|
688
|
+
return balance;
|
|
689
|
+
}
|
|
690
|
+
} catch (error) {
|
|
691
|
+
this.logger.warn("Failed to fetch balance:", error);
|
|
692
|
+
}
|
|
693
|
+
this.logger.debug("Using estimated balance based on tracking");
|
|
694
|
+
return Math.max(0, 100 - this.totalSpentUsd);
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* Get information about the session key.
|
|
698
|
+
*
|
|
699
|
+
* @param refresh - Force refresh from server (default: use cache if < 60s old)
|
|
700
|
+
* @returns Session key details including limits and expiration
|
|
701
|
+
*
|
|
702
|
+
* @example
|
|
703
|
+
* ```typescript
|
|
704
|
+
* const info = await wallet.getSessionKeyInfo();
|
|
705
|
+
* console.log(`Daily limit: $${info.limits.dailyUsd}`);
|
|
706
|
+
* console.log(`Expires: ${info.expiresAt}`);
|
|
707
|
+
* ```
|
|
708
|
+
*/
|
|
709
|
+
async getSessionKeyInfo(refresh = false) {
|
|
710
|
+
const cacheAge = this.sessionKeyInfoFetchedAt ? Date.now() - this.sessionKeyInfoFetchedAt : Infinity;
|
|
711
|
+
if (!refresh && this.sessionKeyInfo && cacheAge < 6e4) {
|
|
712
|
+
return this.sessionKeyInfo;
|
|
713
|
+
}
|
|
714
|
+
this.logger.debug("Fetching session key info...");
|
|
715
|
+
try {
|
|
716
|
+
const response = await fetch(`${this.baseUrl}/v1/session-key/info`, {
|
|
717
|
+
headers: {
|
|
718
|
+
"X-Session-Key": this.sessionKey.address
|
|
719
|
+
}
|
|
720
|
+
});
|
|
721
|
+
if (response.ok) {
|
|
722
|
+
const data = await response.json();
|
|
723
|
+
this.sessionKeyInfo = {
|
|
724
|
+
address: this.sessionKey.address,
|
|
725
|
+
isValid: data.is_valid ?? data.isValid ?? true,
|
|
726
|
+
limits: {
|
|
727
|
+
perTxUsd: data.per_tx_limit_usd ?? data.perTxLimitUsd ?? null,
|
|
728
|
+
dailyUsd: data.daily_limit_usd ?? data.dailyLimitUsd ?? null,
|
|
729
|
+
totalUsd: data.total_limit_usd ?? data.totalLimitUsd ?? null
|
|
730
|
+
},
|
|
731
|
+
usage: {
|
|
732
|
+
todayUsd: data.today_spent_usd ?? data.todaySpentUsd ?? 0,
|
|
733
|
+
totalUsd: data.total_spent_usd ?? data.totalSpentUsd ?? 0,
|
|
734
|
+
txCount: data.tx_count ?? data.txCount ?? 0
|
|
735
|
+
},
|
|
736
|
+
expiresAt: data.expires_at ? new Date(data.expires_at) : null,
|
|
737
|
+
createdAt: data.created_at ? new Date(data.created_at) : null,
|
|
738
|
+
name: data.name
|
|
739
|
+
};
|
|
740
|
+
this.sessionKeyInfoFetchedAt = Date.now();
|
|
741
|
+
return this.sessionKeyInfo;
|
|
742
|
+
}
|
|
743
|
+
} catch (error) {
|
|
744
|
+
this.logger.warn("Failed to fetch session key info:", error);
|
|
745
|
+
}
|
|
746
|
+
return {
|
|
747
|
+
address: this.sessionKey.address,
|
|
748
|
+
isValid: true,
|
|
749
|
+
limits: { perTxUsd: null, dailyUsd: null, totalUsd: null },
|
|
750
|
+
usage: { todayUsd: this.totalSpentUsd, totalUsd: this.totalSpentUsd, txCount: this.payments.length },
|
|
751
|
+
expiresAt: null,
|
|
752
|
+
createdAt: null
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* Get spending stats for this session key.
|
|
757
|
+
*
|
|
758
|
+
* @returns Spending statistics
|
|
759
|
+
*
|
|
760
|
+
* @example
|
|
761
|
+
* ```typescript
|
|
762
|
+
* const stats = await wallet.getSpendingStats();
|
|
763
|
+
* console.log(`Spent: $${stats.totalSpentUsd.toFixed(2)}`);
|
|
764
|
+
* console.log(`Remaining daily: $${stats.remainingDailyUsd?.toFixed(2) ?? 'unlimited'}`);
|
|
765
|
+
* ```
|
|
766
|
+
*/
|
|
767
|
+
async getSpendingStats() {
|
|
768
|
+
this.logger.debug("Fetching spending stats...");
|
|
769
|
+
try {
|
|
770
|
+
const response = await fetch(`${this.baseUrl}/v1/session-key/stats`, {
|
|
771
|
+
headers: {
|
|
772
|
+
"X-Session-Key": this.sessionKey.address
|
|
773
|
+
}
|
|
774
|
+
});
|
|
775
|
+
if (response.ok) {
|
|
776
|
+
const data = await response.json();
|
|
777
|
+
return {
|
|
778
|
+
totalSpentUsd: data.total_spent_usd || data.totalSpentUsd || this.totalSpentUsd,
|
|
779
|
+
txCount: data.tx_count || data.txCount || this.payments.length,
|
|
780
|
+
remainingDailyUsd: data.remaining_daily_usd || data.remainingDailyUsd || null,
|
|
781
|
+
remainingTotalUsd: data.remaining_total_usd || data.remainingTotalUsd || null,
|
|
782
|
+
expiresAt: data.expires_at ? new Date(data.expires_at) : null
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
} catch (error) {
|
|
786
|
+
this.logger.warn("Failed to fetch spending stats:", error);
|
|
787
|
+
}
|
|
788
|
+
return {
|
|
789
|
+
totalSpentUsd: this.totalSpentUsd,
|
|
790
|
+
txCount: this.payments.length,
|
|
791
|
+
remainingDailyUsd: null,
|
|
792
|
+
remainingTotalUsd: null,
|
|
793
|
+
expiresAt: null
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* Get list of payments made in this session.
|
|
798
|
+
*
|
|
799
|
+
* @returns Array of payment events
|
|
800
|
+
*/
|
|
801
|
+
getPaymentHistory() {
|
|
802
|
+
return [...this.payments];
|
|
803
|
+
}
|
|
804
|
+
/**
|
|
805
|
+
* Get the total amount spent in this session.
|
|
806
|
+
*
|
|
807
|
+
* @returns Total spent in USD
|
|
808
|
+
*/
|
|
809
|
+
getTotalSpent() {
|
|
810
|
+
return this.totalSpentUsd;
|
|
811
|
+
}
|
|
812
|
+
// ===========================================================================
|
|
813
|
+
// Diagnostics
|
|
814
|
+
// ===========================================================================
|
|
815
|
+
/**
|
|
816
|
+
* Run diagnostics to verify the wallet is properly configured.
|
|
817
|
+
*
|
|
818
|
+
* This is useful for debugging integration issues.
|
|
819
|
+
*
|
|
820
|
+
* @returns Diagnostic results with status and any issues found
|
|
821
|
+
*
|
|
822
|
+
* @example
|
|
823
|
+
* ```typescript
|
|
824
|
+
* const diagnostics = await wallet.runDiagnostics();
|
|
825
|
+
* if (diagnostics.healthy) {
|
|
826
|
+
* console.log('✅ Wallet is ready to use');
|
|
827
|
+
* } else {
|
|
828
|
+
* console.log('❌ Issues found:');
|
|
829
|
+
* diagnostics.issues.forEach(issue => console.log(` - ${issue}`));
|
|
830
|
+
* }
|
|
831
|
+
* ```
|
|
832
|
+
*/
|
|
833
|
+
async runDiagnostics() {
|
|
834
|
+
this.logger.info("Running diagnostics...");
|
|
835
|
+
const issues = [];
|
|
836
|
+
const checks = {};
|
|
837
|
+
checks.sessionKeyFormat = true;
|
|
838
|
+
try {
|
|
839
|
+
const response = await fetch(`${this.baseUrl}/health`, {
|
|
840
|
+
method: "GET",
|
|
841
|
+
signal: AbortSignal.timeout(5e3)
|
|
842
|
+
});
|
|
843
|
+
checks.apiConnectivity = response.ok;
|
|
844
|
+
if (!response.ok) {
|
|
845
|
+
issues.push(`API server returned ${response.status}. Check baseUrl configuration.`);
|
|
846
|
+
}
|
|
847
|
+
} catch {
|
|
848
|
+
checks.apiConnectivity = false;
|
|
849
|
+
issues.push("Cannot connect to MixrPay API. Check your network connection and baseUrl.");
|
|
850
|
+
}
|
|
851
|
+
try {
|
|
852
|
+
const info = await this.getSessionKeyInfo(true);
|
|
853
|
+
checks.sessionKeyValid = info.isValid;
|
|
854
|
+
if (!info.isValid) {
|
|
855
|
+
issues.push("Session key is invalid or has been revoked.");
|
|
856
|
+
}
|
|
857
|
+
if (info.expiresAt && info.expiresAt < /* @__PURE__ */ new Date()) {
|
|
858
|
+
checks.sessionKeyValid = false;
|
|
859
|
+
issues.push(`Session key expired on ${info.expiresAt.toISOString()}`);
|
|
860
|
+
}
|
|
861
|
+
} catch {
|
|
862
|
+
checks.sessionKeyValid = false;
|
|
863
|
+
issues.push("Could not verify session key validity.");
|
|
864
|
+
}
|
|
865
|
+
try {
|
|
866
|
+
const balance = await this.getBalance();
|
|
867
|
+
checks.hasBalance = balance > 0;
|
|
868
|
+
if (balance <= 0) {
|
|
869
|
+
issues.push("Wallet has no USDC balance. Top up at your MixrPay server /wallet");
|
|
870
|
+
} else if (balance < 1) {
|
|
871
|
+
issues.push(`Low balance: $${balance.toFixed(2)}. Consider topping up.`);
|
|
872
|
+
}
|
|
873
|
+
} catch {
|
|
874
|
+
checks.hasBalance = false;
|
|
875
|
+
issues.push("Could not fetch wallet balance.");
|
|
876
|
+
}
|
|
877
|
+
const healthy = issues.length === 0;
|
|
878
|
+
this.logger.info("Diagnostics complete:", { healthy, issues });
|
|
879
|
+
return {
|
|
880
|
+
healthy,
|
|
881
|
+
issues,
|
|
882
|
+
checks,
|
|
883
|
+
sdkVersion: SDK_VERSION,
|
|
884
|
+
network: this.getNetwork().name,
|
|
885
|
+
walletAddress: this.walletAddress
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
/**
|
|
889
|
+
* Enable or disable debug logging.
|
|
890
|
+
*
|
|
891
|
+
* @param enable - true to enable debug logging, false to disable
|
|
892
|
+
*
|
|
893
|
+
* @example
|
|
894
|
+
* ```typescript
|
|
895
|
+
* wallet.setDebug(true); // Enable detailed logs
|
|
896
|
+
* await wallet.fetch(...);
|
|
897
|
+
* wallet.setDebug(false); // Disable logs
|
|
898
|
+
* ```
|
|
899
|
+
*/
|
|
900
|
+
setDebug(enable) {
|
|
901
|
+
this.logger.setLevel(enable ? "debug" : "none");
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Set the log level.
|
|
905
|
+
*
|
|
906
|
+
* @param level - 'debug' | 'info' | 'warn' | 'error' | 'none'
|
|
907
|
+
*/
|
|
908
|
+
setLogLevel(level) {
|
|
909
|
+
this.logger.setLevel(level);
|
|
910
|
+
}
|
|
911
|
+
};
|
|
912
|
+
export {
|
|
913
|
+
AgentWallet,
|
|
914
|
+
DEFAULT_BASE_URL,
|
|
915
|
+
DEFAULT_FACILITATOR_URL,
|
|
916
|
+
DEFAULT_TIMEOUT,
|
|
917
|
+
InsufficientBalanceError,
|
|
918
|
+
InvalidSessionKeyError,
|
|
919
|
+
MixrPayError,
|
|
920
|
+
NETWORKS,
|
|
921
|
+
PaymentFailedError,
|
|
922
|
+
SDK_VERSION,
|
|
923
|
+
SessionKey,
|
|
924
|
+
SessionKeyExpiredError,
|
|
925
|
+
SpendingLimitExceededError,
|
|
926
|
+
X402ProtocolError,
|
|
927
|
+
buildTransferAuthorizationData,
|
|
928
|
+
buildXPaymentHeader,
|
|
929
|
+
generateNonce,
|
|
930
|
+
getAmountUsd,
|
|
931
|
+
getErrorMessage,
|
|
932
|
+
isMixrPayError,
|
|
933
|
+
isPaymentExpired,
|
|
934
|
+
parse402Response,
|
|
935
|
+
validatePaymentAmount
|
|
936
|
+
};
|