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