@voyage_ai/v402-web-ts 0.1.0 → 0.1.2

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 CHANGED
@@ -56,7 +56,7 @@ module.exports = __toCommonJS(index_exports);
56
56
  var import_types3 = require("x402/types");
57
57
 
58
58
  // src/types/common.ts
59
- var PROD_BACK_URL = "https://v402.onvoyage.ai/api";
59
+ var PROD_BACK_URL = "https://v402.onvoyage.ai/api/pay";
60
60
 
61
61
  // src/types/svm.ts
62
62
  var import_zod = require("zod");
@@ -134,166 +134,63 @@ function getChainId(network) {
134
134
  // src/services/svm/payment-header.ts
135
135
  var import_web3 = require("@solana/web3.js");
136
136
  var import_spl_token = require("@solana/spl-token");
137
- async function createSvmPaymentHeader(params) {
138
- const { wallet, paymentRequirements, x402Version, rpcUrl } = params;
139
- const connection = new import_web3.Connection(rpcUrl, "confirmed");
140
- const feePayer = paymentRequirements?.extra?.feePayer;
141
- if (typeof feePayer !== "string" || !feePayer) {
142
- throw new Error("Missing facilitator feePayer in payment requirements (extra.feePayer).");
143
- }
144
- const feePayerPubkey = new import_web3.PublicKey(feePayer);
145
- const walletAddress = wallet?.publicKey?.toString() || wallet?.address;
146
- if (!walletAddress) {
147
- throw new Error("Missing connected Solana wallet address or publicKey");
148
- }
149
- const userPubkey = new import_web3.PublicKey(walletAddress);
150
- if (!paymentRequirements?.payTo) {
151
- throw new Error("Missing payTo in payment requirements");
152
- }
153
- const destination = new import_web3.PublicKey(paymentRequirements.payTo);
154
- const instructions = [];
155
- instructions.push(
156
- import_web3.ComputeBudgetProgram.setComputeUnitLimit({
157
- units: 7e3
158
- // Sufficient for SPL token transfer
159
- })
160
- );
161
- instructions.push(
162
- import_web3.ComputeBudgetProgram.setComputeUnitPrice({
163
- microLamports: 1
164
- // Minimal price
165
- })
166
- );
167
- if (!paymentRequirements.asset) {
168
- throw new Error("Missing token mint for SPL transfer");
137
+
138
+ // src/utils/wallet.ts
139
+ function isWalletInstalled(networkType) {
140
+ if (typeof window === "undefined") {
141
+ return false;
169
142
  }
170
- const mintPubkey = new import_web3.PublicKey(paymentRequirements.asset);
171
- const mintInfo = await connection.getAccountInfo(mintPubkey, "confirmed");
172
- const programId = mintInfo?.owner?.toBase58() === import_spl_token.TOKEN_2022_PROGRAM_ID.toBase58() ? import_spl_token.TOKEN_2022_PROGRAM_ID : import_spl_token.TOKEN_PROGRAM_ID;
173
- const mint = await (0, import_spl_token.getMint)(connection, mintPubkey, void 0, programId);
174
- const sourceAta = await (0, import_spl_token.getAssociatedTokenAddress)(
175
- mintPubkey,
176
- userPubkey,
177
- false,
178
- programId
179
- );
180
- const destinationAta = await (0, import_spl_token.getAssociatedTokenAddress)(
181
- mintPubkey,
182
- destination,
183
- false,
184
- programId
185
- );
186
- const sourceAtaInfo = await connection.getAccountInfo(sourceAta, "confirmed");
187
- if (!sourceAtaInfo) {
188
- throw new Error(
189
- `User does not have an Associated Token Account for ${paymentRequirements.asset}. Please create one first or ensure you have the required token.`
190
- );
143
+ switch (networkType) {
144
+ case "evm" /* EVM */:
145
+ return !!window.ethereum;
146
+ case "solana" /* SOLANA */:
147
+ case "svm" /* SVM */:
148
+ return !!window.solana || !!window.phantom;
149
+ default:
150
+ return false;
191
151
  }
192
- const destAtaInfo = await connection.getAccountInfo(destinationAta, "confirmed");
193
- if (!destAtaInfo) {
194
- throw new Error(
195
- `Destination does not have an Associated Token Account for ${paymentRequirements.asset}. The receiver must create their token account before receiving payments.`
196
- );
152
+ }
153
+ function getWalletProvider(networkType) {
154
+ if (typeof window === "undefined") {
155
+ return null;
197
156
  }
198
- const amount = BigInt(paymentRequirements.maxAmountRequired);
199
- instructions.push(
200
- (0, import_spl_token.createTransferCheckedInstruction)(
201
- sourceAta,
202
- mintPubkey,
203
- destinationAta,
204
- userPubkey,
205
- amount,
206
- mint.decimals,
207
- [],
208
- programId
209
- )
210
- );
211
- const { blockhash } = await connection.getLatestBlockhash("confirmed");
212
- const message = new import_web3.TransactionMessage({
213
- payerKey: feePayerPubkey,
214
- recentBlockhash: blockhash,
215
- instructions
216
- }).compileToV0Message();
217
- const transaction = new import_web3.VersionedTransaction(message);
218
- if (typeof wallet?.signTransaction !== "function") {
219
- throw new Error("Connected wallet does not support signTransaction");
157
+ switch (networkType) {
158
+ case "evm" /* EVM */:
159
+ return window.ethereum;
160
+ case "solana" /* SOLANA */:
161
+ case "svm" /* SVM */:
162
+ return window.solana || window.phantom;
163
+ default:
164
+ return null;
220
165
  }
221
- const userSignedTx = await wallet.signTransaction(transaction);
222
- const serializedTransaction = Buffer.from(userSignedTx.serialize()).toString("base64");
223
- const paymentPayload = {
224
- x402Version,
225
- scheme: paymentRequirements.scheme,
226
- network: paymentRequirements.network,
227
- payload: {
228
- transaction: serializedTransaction
229
- }
230
- };
231
- const paymentHeader = Buffer.from(JSON.stringify(paymentPayload)).toString("base64");
232
- return paymentHeader;
233
166
  }
234
- function getDefaultSolanaRpcUrl(network) {
235
- const normalized = network.toLowerCase();
236
- if (normalized === "solana" || normalized === "solana-mainnet") {
237
- return "https://api.mainnet-beta.solana.com";
238
- } else if (normalized === "solana-devnet") {
239
- return "https://api.devnet.solana.com";
167
+ function formatAddress(address) {
168
+ if (!address || address.length < 10) {
169
+ return address;
240
170
  }
241
- throw new Error(`Unsupported Solana network: ${network}`);
171
+ return `${address.slice(0, 6)}...${address.slice(-4)}`;
242
172
  }
243
-
244
- // src/services/svm/payment-handler.ts
245
- async function handleSvmPayment(endpoint, config, requestInit) {
246
- const { wallet, network, rpcUrl, maxPaymentAmount } = config;
247
- const initialResponse = await fetch(endpoint, {
248
- ...requestInit,
249
- method: requestInit?.method || "POST"
250
- });
251
- if (initialResponse.status !== 402) {
252
- return initialResponse;
253
- }
254
- const rawResponse = await initialResponse.json();
255
- const x402Version = rawResponse.x402Version;
256
- const parsedPaymentRequirements = rawResponse.accepts || [];
257
- const selectedRequirements = parsedPaymentRequirements.find(
258
- (req) => req.scheme === "exact" && SolanaNetworkSchema.safeParse(req.network.toLowerCase()).success
259
- );
260
- if (!selectedRequirements) {
261
- console.error(
262
- "\u274C No suitable Solana payment requirements found. Available networks:",
263
- parsedPaymentRequirements.map((req) => req.network)
264
- );
265
- throw new Error("No suitable Solana payment requirements found");
266
- }
267
- if (maxPaymentAmount && maxPaymentAmount > BigInt(0)) {
268
- if (BigInt(selectedRequirements.maxAmountRequired) > maxPaymentAmount) {
269
- throw new Error(
270
- `Payment amount ${selectedRequirements.maxAmountRequired} exceeds maximum allowed ${maxPaymentAmount}`
271
- );
272
- }
173
+ function getWalletInstallUrl(networkType) {
174
+ switch (networkType) {
175
+ case "evm" /* EVM */:
176
+ return "https://metamask.io/download/";
177
+ case "solana" /* SOLANA */:
178
+ case "svm" /* SVM */:
179
+ return "https://phantom.app/download";
180
+ default:
181
+ return "#";
273
182
  }
274
- const effectiveRpcUrl = rpcUrl || getDefaultSolanaRpcUrl(network);
275
- const paymentHeader = await createSvmPaymentHeader({
276
- wallet,
277
- paymentRequirements: selectedRequirements,
278
- x402Version,
279
- rpcUrl: effectiveRpcUrl
280
- });
281
- const newInit = {
282
- ...requestInit,
283
- method: requestInit?.method || "POST",
284
- headers: {
285
- ...requestInit?.headers || {},
286
- "X-PAYMENT": paymentHeader,
287
- "Access-Control-Expose-Headers": "X-PAYMENT-RESPONSE"
288
- }
289
- };
290
- return await fetch(endpoint, newInit);
291
183
  }
292
- function createSvmPaymentFetch(config) {
293
- return async (input, init) => {
294
- const endpoint = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
295
- return handleSvmPayment(endpoint, config, init);
296
- };
184
+ function getWalletDisplayName(networkType) {
185
+ switch (networkType) {
186
+ case "evm" /* EVM */:
187
+ return "MetaMask";
188
+ case "solana" /* SOLANA */:
189
+ case "svm" /* SVM */:
190
+ return "Phantom";
191
+ default:
192
+ return "Unknown Wallet";
193
+ }
297
194
  }
298
195
 
299
196
  // src/services/evm/payment-header.ts
@@ -306,6 +203,34 @@ async function createEvmPaymentHeader(params) {
306
203
  if (!paymentRequirements?.asset) {
307
204
  throw new Error("Missing asset (token contract) in payment requirements");
308
205
  }
206
+ if (wallet.getChainId) {
207
+ try {
208
+ const currentChainIdHex = await wallet.getChainId();
209
+ const currentChainId = parseInt(currentChainIdHex, 16);
210
+ if (currentChainId !== chainId) {
211
+ const networkNames = {
212
+ 1: "Ethereum Mainnet",
213
+ 11155111: "Sepolia Testnet",
214
+ 8453: "Base Mainnet",
215
+ 84532: "Base Sepolia Testnet",
216
+ 137: "Polygon Mainnet",
217
+ 42161: "Arbitrum One",
218
+ 10: "Optimism Mainnet"
219
+ };
220
+ const currentNetworkName = networkNames[currentChainId] || `Chain ${currentChainId}`;
221
+ const targetNetworkName = networkNames[chainId] || `Chain ${chainId}`;
222
+ throw new Error(
223
+ `Network mismatch: Your wallet is connected to ${currentNetworkName}, but payment requires ${targetNetworkName}. Please switch your wallet to the correct network.`
224
+ );
225
+ }
226
+ console.log(`\u2705 Chain ID verified: ${chainId}`);
227
+ } catch (error) {
228
+ if (error.message.includes("Network mismatch")) {
229
+ throw wrapPaymentError(error);
230
+ }
231
+ console.warn("Could not verify chainId:", error);
232
+ }
233
+ }
309
234
  const now = Math.floor(Date.now() / 1e3);
310
235
  const nonceBytes = import_ethers.ethers.randomBytes(32);
311
236
  const nonceBytes32 = import_ethers.ethers.hexlify(nonceBytes);
@@ -334,7 +259,14 @@ async function createEvmPaymentHeader(params) {
334
259
  validBefore: String(now + (paymentRequirements.maxTimeoutSeconds || 3600)),
335
260
  nonce: nonceBytes32
336
261
  };
337
- const signature = await wallet.signTypedData(domain, types, authorization);
262
+ let signature;
263
+ try {
264
+ signature = await wallet.signTypedData(domain, types, authorization);
265
+ console.log("\u2705 Signature created successfully");
266
+ } catch (error) {
267
+ console.error("\u274C Failed to create signature:", error);
268
+ throw wrapPaymentError(error);
269
+ }
338
270
  const headerPayload = {
339
271
  x402_version: x402Version,
340
272
  x402Version,
@@ -385,6 +317,26 @@ async function handleEvmPayment(endpoint, config, requestInit) {
385
317
  return initialResponse;
386
318
  }
387
319
  const rawResponse = await initialResponse.json();
320
+ const IGNORED_ERRORS = [
321
+ "X-PAYMENT header is required",
322
+ "missing X-PAYMENT header",
323
+ "payment_required"
324
+ ];
325
+ if (rawResponse.error && !IGNORED_ERRORS.includes(rawResponse.error)) {
326
+ console.error(`\u274C Payment verification failed: ${rawResponse.error}`);
327
+ const ERROR_MESSAGES = {
328
+ "insufficient_funds": "Insufficient balance to complete this payment",
329
+ "invalid_signature": "Invalid payment signature",
330
+ "expired": "Payment authorization has expired",
331
+ "already_used": "This payment has already been used",
332
+ "network_mismatch": "Payment network does not match",
333
+ "invalid_payment": "Invalid payment data",
334
+ "verification_failed": "Payment verification failed"
335
+ };
336
+ const errorMessage = ERROR_MESSAGES[rawResponse.error] || `Payment failed: ${rawResponse.error}`;
337
+ const error = new Error(errorMessage);
338
+ throw wrapPaymentError(error);
339
+ }
388
340
  const x402Version = rawResponse.x402Version;
389
341
  const parsedPaymentRequirements = rawResponse.accepts || [];
390
342
  const selectedRequirements = parsedPaymentRequirements.find(
@@ -405,19 +357,81 @@ async function handleEvmPayment(endpoint, config, requestInit) {
405
357
  }
406
358
  }
407
359
  const targetChainId = getChainIdFromNetwork(selectedRequirements.network);
408
- if (wallet.switchChain) {
360
+ let currentChainId;
361
+ if (wallet.getChainId) {
362
+ try {
363
+ const chainIdHex = await wallet.getChainId();
364
+ currentChainId = parseInt(chainIdHex, 16);
365
+ console.log(`\u{1F4CD} Current wallet chain: ${currentChainId}`);
366
+ } catch (error) {
367
+ console.warn("\u26A0\uFE0F Failed to get current chainId:", error);
368
+ }
369
+ }
370
+ const networkNames = {
371
+ 1: "Ethereum Mainnet",
372
+ 11155111: "Sepolia Testnet",
373
+ 8453: "Base Mainnet",
374
+ 84532: "Base Sepolia Testnet",
375
+ 137: "Polygon Mainnet",
376
+ 42161: "Arbitrum One",
377
+ 10: "Optimism Mainnet"
378
+ };
379
+ if (currentChainId && currentChainId !== targetChainId) {
380
+ if (!wallet.switchChain) {
381
+ const currentNetworkName = networkNames[currentChainId] || `Chain ${currentChainId}`;
382
+ const targetNetworkName = networkNames[targetChainId] || selectedRequirements.network;
383
+ const error = new Error(
384
+ `Network mismatch: Your wallet is connected to ${currentNetworkName}, but payment requires ${targetNetworkName}. Please switch to ${targetNetworkName} manually in your wallet.`
385
+ );
386
+ throw wrapPaymentError(error);
387
+ }
388
+ try {
389
+ console.log(`\u{1F504} Switching to chain ${targetChainId}...`);
390
+ await wallet.switchChain(`0x${targetChainId.toString(16)}`);
391
+ console.log(`\u2705 Successfully switched to chain ${targetChainId}`);
392
+ } catch (error) {
393
+ console.error("\u274C Failed to switch chain:", error);
394
+ const targetNetworkName = networkNames[targetChainId] || selectedRequirements.network;
395
+ const wrappedError = wrapPaymentError(error);
396
+ let finalError;
397
+ if (wrappedError.code === "USER_REJECTED" /* USER_REJECTED */) {
398
+ finalError = new PaymentOperationError({
399
+ code: wrappedError.code,
400
+ message: wrappedError.message,
401
+ userMessage: `You rejected the network switch request. Please switch to ${targetNetworkName} manually.`,
402
+ originalError: wrappedError.originalError
403
+ });
404
+ } else {
405
+ finalError = new PaymentOperationError({
406
+ code: "NETWORK_SWITCH_FAILED" /* NETWORK_SWITCH_FAILED */,
407
+ message: wrappedError.message,
408
+ userMessage: `Failed to switch to ${targetNetworkName}. Please switch manually in your wallet.`,
409
+ originalError: wrappedError.originalError
410
+ });
411
+ }
412
+ throw finalError;
413
+ }
414
+ } else if (wallet.switchChain && !currentChainId) {
409
415
  try {
416
+ console.log(`\u{1F504} Attempting to switch to chain ${targetChainId}...`);
410
417
  await wallet.switchChain(`0x${targetChainId.toString(16)}`);
418
+ console.log(`\u2705 Switch attempted successfully`);
411
419
  } catch (error) {
412
- console.warn("Failed to switch chain:", error);
420
+ console.warn("\u26A0\uFE0F Failed to switch chain (best effort):", error);
413
421
  }
414
422
  }
415
- const paymentHeader = await createEvmPaymentHeader({
416
- wallet,
417
- paymentRequirements: selectedRequirements,
418
- x402Version,
419
- chainId: targetChainId
420
- });
423
+ let paymentHeader;
424
+ try {
425
+ paymentHeader = await createEvmPaymentHeader({
426
+ wallet,
427
+ paymentRequirements: selectedRequirements,
428
+ x402Version,
429
+ chainId: targetChainId
430
+ });
431
+ } catch (error) {
432
+ console.error("\u274C Failed to create payment header:", error);
433
+ throw wrapPaymentError(error);
434
+ }
421
435
  const newInit = {
422
436
  ...requestInit,
423
437
  method: requestInit?.method || "POST",
@@ -427,7 +441,38 @@ async function handleEvmPayment(endpoint, config, requestInit) {
427
441
  "Access-Control-Expose-Headers": "X-PAYMENT-RESPONSE"
428
442
  }
429
443
  };
430
- return await fetch(endpoint, newInit);
444
+ const retryResponse = await fetch(endpoint, newInit);
445
+ if (retryResponse.status === 402) {
446
+ try {
447
+ const retryData = await retryResponse.json();
448
+ const IGNORED_ERRORS2 = [
449
+ "X-PAYMENT header is required",
450
+ "missing X-PAYMENT header",
451
+ "payment_required"
452
+ ];
453
+ if (retryData.error && !IGNORED_ERRORS2.includes(retryData.error)) {
454
+ console.error(`\u274C Payment verification failed: ${retryData.error}`);
455
+ const ERROR_MESSAGES = {
456
+ "insufficient_funds": "Insufficient balance to complete this payment",
457
+ "invalid_signature": "Invalid payment signature",
458
+ "expired": "Payment authorization has expired",
459
+ "already_used": "This payment has already been used",
460
+ "network_mismatch": "Payment network does not match",
461
+ "invalid_payment": "Invalid payment data",
462
+ "verification_failed": "Payment verification failed"
463
+ };
464
+ const errorMessage = ERROR_MESSAGES[retryData.error] || `Payment failed: ${retryData.error}`;
465
+ const error = new Error(errorMessage);
466
+ throw wrapPaymentError(error);
467
+ }
468
+ } catch (error) {
469
+ if (error instanceof PaymentOperationError) {
470
+ throw error;
471
+ }
472
+ console.warn("\u26A0\uFE0F Could not parse retry 402 response:", error);
473
+ }
474
+ }
475
+ return retryResponse;
431
476
  }
432
477
  function createEvmPaymentFetch(config) {
433
478
  return async (input, init) => {
@@ -436,69 +481,17 @@ function createEvmPaymentFetch(config) {
436
481
  };
437
482
  }
438
483
 
439
- // src/utils/wallet.ts
440
- function isWalletInstalled(networkType) {
441
- if (typeof window === "undefined") {
442
- return false;
443
- }
444
- switch (networkType) {
445
- case "evm" /* EVM */:
446
- return !!window.ethereum;
447
- case "solana" /* SOLANA */:
448
- case "svm" /* SVM */:
449
- return !!window.solana || !!window.phantom;
450
- default:
451
- return false;
452
- }
453
- }
454
- function getWalletProvider(networkType) {
455
- if (typeof window === "undefined") {
456
- return null;
457
- }
458
- switch (networkType) {
459
- case "evm" /* EVM */:
460
- return window.ethereum;
461
- case "solana" /* SOLANA */:
462
- case "svm" /* SVM */:
463
- return window.solana || window.phantom;
464
- default:
465
- return null;
466
- }
467
- }
468
- function formatAddress(address) {
469
- if (!address || address.length < 10) {
470
- return address;
471
- }
472
- return `${address.slice(0, 6)}...${address.slice(-4)}`;
473
- }
474
- function getWalletInstallUrl(networkType) {
475
- switch (networkType) {
476
- case "evm" /* EVM */:
477
- return "https://metamask.io/download/";
478
- case "solana" /* SOLANA */:
479
- case "svm" /* SVM */:
480
- return "https://phantom.app/download";
481
- default:
482
- return "#";
483
- }
484
- }
485
- function getWalletDisplayName(networkType) {
486
- switch (networkType) {
487
- case "evm" /* EVM */:
488
- return "MetaMask";
489
- case "solana" /* SOLANA */:
490
- case "svm" /* SVM */:
491
- return "Phantom";
492
- default:
493
- return "Unknown Wallet";
494
- }
495
- }
496
-
497
484
  // src/utils/payment-helpers.ts
498
485
  var import_ethers2 = require("ethers");
499
- async function makePayment(networkType, merchantId, endpoint = PROD_BACK_URL) {
500
- endpoint = `${endpoint}/${merchantId}`;
486
+ async function makePayment(networkType, merchantId, endpoint = PROD_BACK_URL, additionalParams) {
487
+ const fullEndpoint = `${endpoint}/${merchantId}`;
501
488
  let response;
489
+ const requestInit = additionalParams && Object.keys(additionalParams).length > 0 ? {
490
+ body: JSON.stringify(additionalParams),
491
+ headers: {
492
+ "Content-Type": "application/json"
493
+ }
494
+ } : {};
502
495
  if (networkType === "solana" /* SOLANA */ || networkType === "svm" /* SVM */) {
503
496
  const solana = window.solana;
504
497
  if (!solana) {
@@ -507,10 +500,11 @@ async function makePayment(networkType, merchantId, endpoint = PROD_BACK_URL) {
507
500
  if (!solana.isConnected) {
508
501
  await solana.connect();
509
502
  }
510
- response = await handleSvmPayment(endpoint, {
503
+ response = await handleSvmPayment(fullEndpoint, {
511
504
  wallet: solana,
512
- network: "solana-devnet"
513
- });
505
+ network: "solana"
506
+ // Will use backend's network configuration
507
+ }, requestInit);
514
508
  } else if (networkType === "evm" /* EVM */) {
515
509
  if (!window.ethereum) {
516
510
  throw new Error("\u8BF7\u5B89\u88C5 MetaMask \u94B1\u5305");
@@ -521,13 +515,25 @@ async function makePayment(networkType, merchantId, endpoint = PROD_BACK_URL) {
521
515
  address: await signer.getAddress(),
522
516
  signTypedData: async (domain, types, message) => {
523
517
  return await signer.signTypedData(domain, types, message);
518
+ },
519
+ // Get current chain ID from wallet
520
+ getChainId: async () => {
521
+ const network = await provider.getNetwork();
522
+ return `0x${network.chainId.toString(16)}`;
523
+ },
524
+ // Switch to a different chain
525
+ switchChain: async (chainId) => {
526
+ await window.ethereum.request({
527
+ method: "wallet_switchEthereumChain",
528
+ params: [{ chainId }]
529
+ });
524
530
  }
525
531
  };
526
- const network = endpoint.includes("sepolia") ? "base-sepolia" : "base";
527
- response = await handleEvmPayment(endpoint, {
532
+ response = await handleEvmPayment(fullEndpoint, {
528
533
  wallet,
529
- network
530
- });
534
+ network: "base"
535
+ // Will use backend's network configuration
536
+ }, requestInit);
531
537
  } else {
532
538
  throw new Error(`\u4E0D\u652F\u6301\u7684\u7F51\u7EDC\u7C7B\u578B: ${networkType}`);
533
539
  }
@@ -577,6 +583,7 @@ function isEvmAddress(address) {
577
583
  }
578
584
  function getNetworkDisplayName(network) {
579
585
  const displayNames = {
586
+ "evm": "EVM",
580
587
  "ethereum": "Ethereum",
581
588
  "sepolia": "Sepolia Testnet",
582
589
  "base": "Base",
@@ -601,6 +608,370 @@ function fromAtomicUnits(atomicUnits, decimals) {
601
608
  function is402Response(response) {
602
609
  return response && typeof response === "object" && "x402Version" in response && "accepts" in response && Array.isArray(response.accepts);
603
610
  }
611
+
612
+ // src/utils/payment-error-handler.ts
613
+ function parsePaymentError(error) {
614
+ if (!error) {
615
+ return {
616
+ code: "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
617
+ message: "Unknown error occurred",
618
+ userMessage: "An unknown error occurred. Please try again.",
619
+ originalError: error
620
+ };
621
+ }
622
+ const errorMessage = error.message || error.toString();
623
+ const errorCode = error.code;
624
+ if (errorCode === 4001 || errorCode === "ACTION_REJECTED" || errorMessage.includes("User rejected") || errorMessage.includes("user rejected") || errorMessage.includes("User denied") || errorMessage.includes("user denied") || errorMessage.includes("ethers-user-denied")) {
625
+ return {
626
+ code: "USER_REJECTED" /* USER_REJECTED */,
627
+ message: "User rejected the transaction",
628
+ userMessage: "You rejected the signature request. Please try again if you want to proceed.",
629
+ originalError: error
630
+ };
631
+ }
632
+ if (errorMessage.includes("chainId") && (errorMessage.includes("must match") || errorMessage.includes("does not match"))) {
633
+ const match = errorMessage.match(/chainId.*?"(\d+)".*?active.*?"(\d+)"/i) || errorMessage.match(/chain (\d+).*?chain (\d+)/i);
634
+ if (match) {
635
+ const [, requestedChain, activeChain] = match;
636
+ return {
637
+ code: "CHAIN_ID_MISMATCH" /* CHAIN_ID_MISMATCH */,
638
+ message: `Network mismatch (wallet is on different chain): Requested ${requestedChain}, but wallet is on ${activeChain}`,
639
+ userMessage: `Your wallet is on the wrong network. Please switch to the correct network and try again.`,
640
+ originalError: error
641
+ };
642
+ }
643
+ return {
644
+ code: "CHAIN_ID_MISMATCH" /* CHAIN_ID_MISMATCH */,
645
+ message: "Network mismatch (wallet selected network does not match)",
646
+ userMessage: "Your wallet is on the wrong network. Please switch to the correct network.",
647
+ originalError: error
648
+ };
649
+ }
650
+ if (errorMessage.includes("Network mismatch") || errorMessage.includes("Wrong network") || errorMessage.includes("Incorrect network")) {
651
+ return {
652
+ code: "NETWORK_MISMATCH" /* NETWORK_MISMATCH */,
653
+ message: errorMessage,
654
+ userMessage: "Please switch your wallet to the correct network.",
655
+ originalError: error
656
+ };
657
+ }
658
+ if (errorMessage.includes("locked") || errorMessage.includes("Wallet is locked")) {
659
+ return {
660
+ code: "WALLET_LOCKED" /* WALLET_LOCKED */,
661
+ message: "Wallet is locked",
662
+ userMessage: "Please unlock your wallet and try again.",
663
+ originalError: error
664
+ };
665
+ }
666
+ if (errorMessage.includes("insufficient") && (errorMessage.includes("balance") || errorMessage.includes("funds"))) {
667
+ return {
668
+ code: "INSUFFICIENT_BALANCE" /* INSUFFICIENT_BALANCE */,
669
+ message: "Insufficient balance",
670
+ userMessage: "You don't have enough balance to complete this payment.",
671
+ originalError: error
672
+ };
673
+ }
674
+ if (errorMessage.includes("Failed to switch") || errorMessage.includes("switch chain")) {
675
+ return {
676
+ code: "NETWORK_SWITCH_FAILED" /* NETWORK_SWITCH_FAILED */,
677
+ message: errorMessage,
678
+ userMessage: "Failed to switch network. Please switch manually in your wallet.",
679
+ originalError: error
680
+ };
681
+ }
682
+ if (errorMessage.includes("not connected") || errorMessage.includes("No wallet") || errorMessage.includes("Connect wallet")) {
683
+ return {
684
+ code: "WALLET_NOT_CONNECTED" /* WALLET_NOT_CONNECTED */,
685
+ message: "Wallet not connected",
686
+ userMessage: "Please connect your wallet first.",
687
+ originalError: error
688
+ };
689
+ }
690
+ if (errorMessage.includes("No suitable") || errorMessage.includes("payment requirements") || errorMessage.includes("Missing payTo") || errorMessage.includes("Missing asset")) {
691
+ return {
692
+ code: "INVALID_PAYMENT_REQUIREMENTS" /* INVALID_PAYMENT_REQUIREMENTS */,
693
+ message: errorMessage,
694
+ userMessage: "Invalid payment configuration. Please contact support.",
695
+ originalError: error
696
+ };
697
+ }
698
+ if (errorMessage.includes("exceeds maximum")) {
699
+ return {
700
+ code: "AMOUNT_EXCEEDED" /* AMOUNT_EXCEEDED */,
701
+ message: errorMessage,
702
+ userMessage: "Payment amount exceeds the maximum allowed.",
703
+ originalError: error
704
+ };
705
+ }
706
+ if (errorMessage.includes("signature") || errorMessage.includes("sign") || errorCode === "UNKNOWN_ERROR") {
707
+ return {
708
+ code: "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
709
+ message: errorMessage,
710
+ userMessage: "Failed to sign the transaction. Please try again.",
711
+ originalError: error
712
+ };
713
+ }
714
+ return {
715
+ code: "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
716
+ message: errorMessage,
717
+ userMessage: "An unexpected error occurred. Please try again or contact support.",
718
+ originalError: error
719
+ };
720
+ }
721
+ var PaymentOperationError = class _PaymentOperationError extends Error {
722
+ constructor(paymentError) {
723
+ super(paymentError.message);
724
+ this.name = "PaymentOperationError";
725
+ this.code = paymentError.code;
726
+ this.userMessage = paymentError.userMessage;
727
+ this.originalError = paymentError.originalError;
728
+ if (Error.captureStackTrace) {
729
+ Error.captureStackTrace(this, _PaymentOperationError);
730
+ }
731
+ }
732
+ /**
733
+ * Get a formatted error message for logging
734
+ */
735
+ toLogString() {
736
+ return `[${this.code}] ${this.message} | User Message: ${this.userMessage}`;
737
+ }
738
+ };
739
+ function wrapPaymentError(error) {
740
+ const parsedError = parsePaymentError(error);
741
+ return new PaymentOperationError(parsedError);
742
+ }
743
+
744
+ // src/services/svm/payment-header.ts
745
+ async function createSvmPaymentHeader(params) {
746
+ const { wallet, paymentRequirements, x402Version, rpcUrl } = params;
747
+ const connection = new import_web3.Connection(rpcUrl, "confirmed");
748
+ const feePayer = paymentRequirements?.extra?.feePayer;
749
+ if (typeof feePayer !== "string" || !feePayer) {
750
+ throw new Error("Missing facilitator feePayer in payment requirements (extra.feePayer).");
751
+ }
752
+ const feePayerPubkey = new import_web3.PublicKey(feePayer);
753
+ const walletAddress = wallet?.publicKey?.toString() || wallet?.address;
754
+ if (!walletAddress) {
755
+ throw new Error("Missing connected Solana wallet address or publicKey");
756
+ }
757
+ const userPubkey = new import_web3.PublicKey(walletAddress);
758
+ if (!paymentRequirements?.payTo) {
759
+ throw new Error("Missing payTo in payment requirements");
760
+ }
761
+ const destination = new import_web3.PublicKey(paymentRequirements.payTo);
762
+ const instructions = [];
763
+ instructions.push(
764
+ import_web3.ComputeBudgetProgram.setComputeUnitLimit({
765
+ units: 7e3
766
+ // Sufficient for SPL token transfer
767
+ })
768
+ );
769
+ instructions.push(
770
+ import_web3.ComputeBudgetProgram.setComputeUnitPrice({
771
+ microLamports: 1
772
+ // Minimal price
773
+ })
774
+ );
775
+ if (!paymentRequirements.asset) {
776
+ throw new Error("Missing token mint for SPL transfer");
777
+ }
778
+ const mintPubkey = new import_web3.PublicKey(paymentRequirements.asset);
779
+ const mintInfo = await connection.getAccountInfo(mintPubkey, "confirmed");
780
+ const programId = mintInfo?.owner?.toBase58() === import_spl_token.TOKEN_2022_PROGRAM_ID.toBase58() ? import_spl_token.TOKEN_2022_PROGRAM_ID : import_spl_token.TOKEN_PROGRAM_ID;
781
+ const mint = await (0, import_spl_token.getMint)(connection, mintPubkey, void 0, programId);
782
+ const sourceAta = await (0, import_spl_token.getAssociatedTokenAddress)(
783
+ mintPubkey,
784
+ userPubkey,
785
+ false,
786
+ programId
787
+ );
788
+ const destinationAta = await (0, import_spl_token.getAssociatedTokenAddress)(
789
+ mintPubkey,
790
+ destination,
791
+ false,
792
+ programId
793
+ );
794
+ const sourceAtaInfo = await connection.getAccountInfo(sourceAta, "confirmed");
795
+ if (!sourceAtaInfo) {
796
+ throw new Error(
797
+ `User does not have an Associated Token Account for ${paymentRequirements.asset}. Please create one first or ensure you have the required token.`
798
+ );
799
+ }
800
+ const destAtaInfo = await connection.getAccountInfo(destinationAta, "confirmed");
801
+ if (!destAtaInfo) {
802
+ throw new Error(
803
+ `Destination does not have an Associated Token Account for ${paymentRequirements.asset}. The receiver must create their token account before receiving payments.`
804
+ );
805
+ }
806
+ const amount = BigInt(paymentRequirements.maxAmountRequired);
807
+ instructions.push(
808
+ (0, import_spl_token.createTransferCheckedInstruction)(
809
+ sourceAta,
810
+ mintPubkey,
811
+ destinationAta,
812
+ userPubkey,
813
+ amount,
814
+ mint.decimals,
815
+ [],
816
+ programId
817
+ )
818
+ );
819
+ const { blockhash } = await connection.getLatestBlockhash("confirmed");
820
+ const message = new import_web3.TransactionMessage({
821
+ payerKey: feePayerPubkey,
822
+ recentBlockhash: blockhash,
823
+ instructions
824
+ }).compileToV0Message();
825
+ const transaction = new import_web3.VersionedTransaction(message);
826
+ if (typeof wallet?.signTransaction !== "function") {
827
+ throw new Error("Connected wallet does not support signTransaction");
828
+ }
829
+ let userSignedTx;
830
+ try {
831
+ userSignedTx = await wallet.signTransaction(transaction);
832
+ console.log("\u2705 Transaction signed successfully");
833
+ } catch (error) {
834
+ console.error("\u274C Failed to sign transaction:", error);
835
+ throw wrapPaymentError(error);
836
+ }
837
+ const serializedTransaction = Buffer.from(userSignedTx.serialize()).toString("base64");
838
+ const paymentPayload = {
839
+ x402Version,
840
+ scheme: paymentRequirements.scheme,
841
+ network: paymentRequirements.network,
842
+ payload: {
843
+ transaction: serializedTransaction
844
+ }
845
+ };
846
+ const paymentHeader = Buffer.from(JSON.stringify(paymentPayload)).toString("base64");
847
+ return paymentHeader;
848
+ }
849
+ function getDefaultSolanaRpcUrl(network) {
850
+ const normalized = network.toLowerCase();
851
+ if (normalized === "solana" || normalized === "solana-mainnet") {
852
+ return "https://cathee-fu8ezd-fast-mainnet.helius-rpc.com";
853
+ } else if (normalized === "solana-devnet") {
854
+ return "https://api.devnet.solana.com";
855
+ }
856
+ throw new Error(`Unsupported Solana network: ${network}`);
857
+ }
858
+
859
+ // src/services/svm/payment-handler.ts
860
+ async function handleSvmPayment(endpoint, config, requestInit) {
861
+ const { wallet, network, rpcUrl, maxPaymentAmount } = config;
862
+ const initialResponse = await fetch(endpoint, {
863
+ ...requestInit,
864
+ method: requestInit?.method || "POST"
865
+ });
866
+ if (initialResponse.status !== 402) {
867
+ return initialResponse;
868
+ }
869
+ const rawResponse = await initialResponse.json();
870
+ const IGNORED_ERRORS = [
871
+ "X-PAYMENT header is required",
872
+ "missing X-PAYMENT header",
873
+ "payment_required"
874
+ ];
875
+ if (rawResponse.error && !IGNORED_ERRORS.includes(rawResponse.error)) {
876
+ console.error(`\u274C Payment verification failed: ${rawResponse.error}`);
877
+ const ERROR_MESSAGES = {
878
+ "insufficient_funds": "Insufficient balance to complete this payment",
879
+ "invalid_signature": "Invalid payment signature",
880
+ "expired": "Payment authorization has expired",
881
+ "already_used": "This payment has already been used",
882
+ "network_mismatch": "Payment network does not match",
883
+ "invalid_payment": "Invalid payment data",
884
+ "verification_failed": "Payment verification failed",
885
+ "invalid_exact_svm_payload_transaction_simulation_failed": "Transaction simulation failed due to insufficient balance. Please check your wallet balance carefully and ensure you have enough funds to cover the payment and transaction fees."
886
+ };
887
+ const errorMessage = ERROR_MESSAGES[rawResponse.error] || `Payment failed: ${rawResponse.error}`;
888
+ const error = new Error(errorMessage);
889
+ throw wrapPaymentError(error);
890
+ }
891
+ const x402Version = rawResponse.x402Version;
892
+ const parsedPaymentRequirements = rawResponse.accepts || [];
893
+ const selectedRequirements = parsedPaymentRequirements.find(
894
+ (req) => req.scheme === "exact" && SolanaNetworkSchema.safeParse(req.network.toLowerCase()).success
895
+ );
896
+ if (!selectedRequirements) {
897
+ console.error(
898
+ "\u274C No suitable Solana payment requirements found. Available networks:",
899
+ parsedPaymentRequirements.map((req) => req.network)
900
+ );
901
+ throw new Error("No suitable Solana payment requirements found");
902
+ }
903
+ if (maxPaymentAmount && maxPaymentAmount > BigInt(0)) {
904
+ if (BigInt(selectedRequirements.maxAmountRequired) > maxPaymentAmount) {
905
+ throw new Error(
906
+ `Payment amount ${selectedRequirements.maxAmountRequired} exceeds maximum allowed ${maxPaymentAmount}`
907
+ );
908
+ }
909
+ }
910
+ const effectiveRpcUrl = rpcUrl || getDefaultSolanaRpcUrl(selectedRequirements.network);
911
+ console.log(`\u{1F4CD} Using Solana RPC: ${effectiveRpcUrl.substring(0, 40)}...`);
912
+ console.log(`\u{1F4CD} Network from backend: ${selectedRequirements.network}`);
913
+ let paymentHeader;
914
+ try {
915
+ paymentHeader = await createSvmPaymentHeader({
916
+ wallet,
917
+ paymentRequirements: selectedRequirements,
918
+ x402Version,
919
+ rpcUrl: effectiveRpcUrl
920
+ });
921
+ console.log("\u2705 Payment header created successfully");
922
+ } catch (error) {
923
+ console.error("\u274C Failed to create payment header:", error);
924
+ throw wrapPaymentError(error);
925
+ }
926
+ const newInit = {
927
+ ...requestInit,
928
+ method: requestInit?.method || "POST",
929
+ headers: {
930
+ ...requestInit?.headers || {},
931
+ "X-PAYMENT": paymentHeader,
932
+ "Access-Control-Expose-Headers": "X-PAYMENT-RESPONSE"
933
+ }
934
+ };
935
+ const retryResponse = await fetch(endpoint, newInit);
936
+ if (retryResponse.status === 402) {
937
+ try {
938
+ const retryData = await retryResponse.json();
939
+ const IGNORED_ERRORS2 = [
940
+ "X-PAYMENT header is required",
941
+ "missing X-PAYMENT header",
942
+ "payment_required"
943
+ ];
944
+ if (retryData.error && !IGNORED_ERRORS2.includes(retryData.error)) {
945
+ console.error(`\u274C Payment verification failed: ${retryData.error}`);
946
+ const ERROR_MESSAGES = {
947
+ "insufficient_funds": "Insufficient balance to complete this payment",
948
+ "invalid_signature": "Invalid payment signature",
949
+ "expired": "Payment authorization has expired",
950
+ "already_used": "This payment has already been used",
951
+ "network_mismatch": "Payment network does not match",
952
+ "invalid_payment": "Invalid payment data",
953
+ "verification_failed": "Payment verification failed",
954
+ "invalid_exact_svm_payload_transaction_simulation_failed": "Transaction simulation failed due to insufficient balance. Please check your wallet balance carefully and ensure you have enough funds to cover the payment and transaction fees."
955
+ };
956
+ const errorMessage = ERROR_MESSAGES[retryData.error] || `Payment failed: ${retryData.error}`;
957
+ const error = new Error(errorMessage);
958
+ throw wrapPaymentError(error);
959
+ }
960
+ } catch (error) {
961
+ if (error instanceof PaymentOperationError) {
962
+ throw error;
963
+ }
964
+ console.warn("\u26A0\uFE0F Could not parse retry 402 response:", error);
965
+ }
966
+ }
967
+ return retryResponse;
968
+ }
969
+ function createSvmPaymentFetch(config) {
970
+ return async (input, init) => {
971
+ const endpoint = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
972
+ return handleSvmPayment(endpoint, config, init);
973
+ };
974
+ }
604
975
  // Annotate the CommonJS export names for ESM import in node:
605
976
  0 && (module.exports = {
606
977
  EVM_NETWORK_CONFIGS,