@atxp/client 0.8.3 → 0.9.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.
Files changed (42) hide show
  1. package/dist/atxpClient.d.ts.map +1 -1
  2. package/dist/atxpClient.js +2 -1
  3. package/dist/atxpClient.js.map +1 -1
  4. package/dist/atxpFetcher.d.ts +13 -5
  5. package/dist/atxpFetcher.d.ts.map +1 -1
  6. package/dist/atxpFetcher.js +67 -18
  7. package/dist/atxpFetcher.js.map +1 -1
  8. package/dist/errors.d.ts +117 -0
  9. package/dist/errors.d.ts.map +1 -0
  10. package/dist/errors.js +152 -0
  11. package/dist/errors.js.map +1 -0
  12. package/dist/index.cjs +213 -386
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.ts +144 -96
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +205 -378
  17. package/dist/index.js.map +1 -1
  18. package/dist/types.d.ts +25 -13
  19. package/dist/types.d.ts.map +1 -1
  20. package/package.json +3 -11
  21. package/dist/baseAccount.d.ts +0 -20
  22. package/dist/baseAccount.d.ts.map +0 -1
  23. package/dist/baseAccount.js +0 -46
  24. package/dist/baseAccount.js.map +0 -1
  25. package/dist/baseConstants.d.ts +0 -10
  26. package/dist/baseConstants.d.ts.map +0 -1
  27. package/dist/baseConstants.js +0 -21
  28. package/dist/baseConstants.js.map +0 -1
  29. package/dist/basePaymentMaker.d.ts +0 -23
  30. package/dist/basePaymentMaker.d.ts.map +0 -1
  31. package/dist/basePaymentMaker.js +0 -169
  32. package/dist/basePaymentMaker.js.map +0 -1
  33. package/dist/solanaAccount.d.ts +0 -13
  34. package/dist/solanaAccount.d.ts.map +0 -1
  35. package/dist/solanaAccount.js +0 -34
  36. package/dist/solanaAccount.js.map +0 -1
  37. package/dist/solanaPaymentMaker.d.ts +0 -25
  38. package/dist/solanaPaymentMaker.d.ts.map +0 -1
  39. package/dist/solanaPaymentMaker.js +0 -108
  40. package/dist/solanaPaymentMaker.js.map +0 -1
  41. package/dist/types.js +0 -24
  42. package/dist/types.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -2,15 +2,7 @@
2
2
 
3
3
  var common = require('@atxp/common');
4
4
  var oauth = require('oauth4webapi');
5
- var BigNumber = require('bignumber.js');
6
- var web3_js = require('@solana/web3.js');
7
- var pay = require('@solana/pay');
8
- var splToken = require('@solana/spl-token');
9
- var bs58 = require('bs58');
10
- var jose = require('jose');
11
- var viem = require('viem');
12
- var chains = require('viem/chains');
13
- var accounts = require('viem/accounts');
5
+ var bignumber_js = require('bignumber.js');
14
6
 
15
7
  function _interopNamespaceDefault(e) {
16
8
  var n = Object.create(null);
@@ -303,25 +295,153 @@ class OAuthClient extends common.OAuthResourceClient {
303
295
  }
304
296
  }
305
297
 
306
- class InsufficientFundsError extends Error {
298
+ /**
299
+ * Base class for all ATXP payment errors with structured error codes and actionable guidance
300
+ */
301
+ class ATXPPaymentError extends Error {
302
+ constructor(message, context) {
303
+ super(message);
304
+ this.context = context;
305
+ this.name = this.constructor.name;
306
+ }
307
+ }
308
+ /**
309
+ * Thrown when the user's wallet has insufficient funds for a payment
310
+ */
311
+ class InsufficientFundsError extends ATXPPaymentError {
307
312
  constructor(currency, required, available, network) {
313
+ const shortfall = available ? required.minus(available).toString() : required.toString();
308
314
  const availableText = available ? `, Available: ${available}` : '';
309
315
  const networkText = network ? ` on ${network}` : '';
310
316
  super(`Payment failed due to insufficient ${currency} funds${networkText}. ` +
311
317
  `Required: ${required}${availableText}. ` +
312
- `Please ensure your account has adequate balance before retrying.`);
318
+ `Please ensure your account has adequate balance before retrying.`, { currency, required: required.toString(), available: available?.toString(), network, shortfall });
313
319
  this.currency = currency;
314
320
  this.required = required;
315
321
  this.available = available;
316
322
  this.network = network;
317
- this.name = 'InsufficientFundsError';
323
+ this.code = 'INSUFFICIENT_FUNDS';
324
+ this.retryable = true;
325
+ this.actionableMessage = available
326
+ ? `Add at least ${shortfall} ${currency} to your ${network} wallet and try again.`
327
+ : `Ensure your ${network} wallet has at least ${required} ${currency} and try again.`;
318
328
  }
319
329
  }
320
- class PaymentNetworkError extends Error {
321
- constructor(message, originalError) {
322
- super(`Payment failed due to network error: ${message}`);
330
+ /**
331
+ * Thrown when a blockchain transaction is reverted
332
+ */
333
+ class TransactionRevertedError extends ATXPPaymentError {
334
+ constructor(transactionHash, network, revertReason) {
335
+ super(`Transaction ${transactionHash} reverted on ${network}${revertReason ? `: ${revertReason}` : ''}`, { transactionHash, network, revertReason });
336
+ this.transactionHash = transactionHash;
337
+ this.network = network;
338
+ this.revertReason = revertReason;
339
+ this.code = 'TRANSACTION_REVERTED';
340
+ this.retryable = false;
341
+ // Provide specific guidance based on revert reason
342
+ if (revertReason?.toLowerCase().includes('allowance')) {
343
+ this.actionableMessage = 'Approve token spending before making the payment. You may need to increase the token allowance.';
344
+ }
345
+ else if (revertReason?.toLowerCase().includes('balance')) {
346
+ this.actionableMessage = 'Ensure your wallet has sufficient token balance and native token for gas fees.';
347
+ }
348
+ else {
349
+ this.actionableMessage = 'The transaction was rejected by the blockchain. Check the transaction details on a block explorer and verify your wallet settings.';
350
+ }
351
+ }
352
+ }
353
+ /**
354
+ * Thrown when an unsupported currency is requested
355
+ */
356
+ class UnsupportedCurrencyError extends ATXPPaymentError {
357
+ constructor(currency, network, supportedCurrencies) {
358
+ super(`Currency ${currency} is not supported on ${network}`, { currency, network, supportedCurrencies });
359
+ this.currency = currency;
360
+ this.network = network;
361
+ this.supportedCurrencies = supportedCurrencies;
362
+ this.code = 'UNSUPPORTED_CURRENCY';
363
+ this.retryable = false;
364
+ this.actionableMessage = `Please use one of the supported currencies: ${supportedCurrencies.join(', ')}`;
365
+ }
366
+ }
367
+ /**
368
+ * Thrown when gas estimation fails for a transaction
369
+ */
370
+ class GasEstimationError extends ATXPPaymentError {
371
+ constructor(network, reason) {
372
+ super(`Failed to estimate gas on ${network}${reason ? `: ${reason}` : ''}`, { network, reason });
373
+ this.network = network;
374
+ this.reason = reason;
375
+ this.code = 'GAS_ESTIMATION_FAILED';
376
+ this.retryable = true;
377
+ this.actionableMessage = 'Unable to estimate gas for this transaction. Ensure you have sufficient funds for both the payment amount and gas fees, then try again.';
378
+ }
379
+ }
380
+ /**
381
+ * Thrown when RPC/network connectivity fails
382
+ */
383
+ class RpcError extends ATXPPaymentError {
384
+ constructor(network, rpcUrl, originalError) {
385
+ super(`RPC call failed on ${network}${rpcUrl ? ` (${rpcUrl})` : ''}`, { network, rpcUrl, originalError: originalError?.message });
386
+ this.network = network;
387
+ this.rpcUrl = rpcUrl;
323
388
  this.originalError = originalError;
324
- this.name = 'PaymentNetworkError';
389
+ this.code = 'RPC_ERROR';
390
+ this.retryable = true;
391
+ this.actionableMessage = 'Unable to connect to the blockchain network. Please check your internet connection and try again.';
392
+ }
393
+ }
394
+ /**
395
+ * Thrown when the user rejects a transaction in their wallet
396
+ */
397
+ class UserRejectedError extends ATXPPaymentError {
398
+ constructor(network) {
399
+ super(`User rejected transaction on ${network}`, { network });
400
+ this.network = network;
401
+ this.code = 'USER_REJECTED';
402
+ this.retryable = true;
403
+ this.actionableMessage = 'You cancelled the transaction. To complete the payment, please approve the transaction in your wallet.';
404
+ }
405
+ }
406
+ /**
407
+ * Thrown when the payment server returns an error
408
+ */
409
+ class PaymentServerError extends ATXPPaymentError {
410
+ constructor(statusCode, endpoint, serverMessage, errorCode, details) {
411
+ super(`Payment server returned ${statusCode} from ${endpoint}${serverMessage ? `: ${serverMessage}` : ''}`, { statusCode, endpoint, serverMessage, errorCode, details });
412
+ this.statusCode = statusCode;
413
+ this.endpoint = endpoint;
414
+ this.serverMessage = serverMessage;
415
+ this.details = details;
416
+ this.retryable = true;
417
+ this.actionableMessage = 'The payment server encountered an error. Please try again in a few moments.';
418
+ this.code = errorCode || 'PAYMENT_SERVER_ERROR';
419
+ }
420
+ }
421
+ /**
422
+ * Thrown when a payment request has expired
423
+ */
424
+ class PaymentExpiredError extends ATXPPaymentError {
425
+ constructor(paymentRequestId, expiresAt) {
426
+ super(`Payment request ${paymentRequestId} has expired`, { paymentRequestId, expiresAt: expiresAt?.toISOString() });
427
+ this.paymentRequestId = paymentRequestId;
428
+ this.expiresAt = expiresAt;
429
+ this.code = 'PAYMENT_EXPIRED';
430
+ this.retryable = false;
431
+ this.actionableMessage = 'This payment request has expired. Please make a new request to the service.';
432
+ }
433
+ }
434
+ /**
435
+ * Generic network error for backward compatibility and uncategorized errors
436
+ */
437
+ class PaymentNetworkError extends ATXPPaymentError {
438
+ constructor(network, message, originalError) {
439
+ super(`Payment failed on ${network} network: ${message}`, { network, originalError: originalError?.message });
440
+ this.network = network;
441
+ this.originalError = originalError;
442
+ this.code = 'NETWORK_ERROR';
443
+ this.retryable = true;
444
+ this.actionableMessage = 'A network error occurred during payment processing. Please try again.';
325
445
  }
326
446
  }
327
447
 
@@ -346,27 +466,41 @@ function atxpFetch(config) {
346
466
  onAuthorize: config.onAuthorize,
347
467
  onAuthorizeFailure: config.onAuthorizeFailure,
348
468
  onPayment: config.onPayment,
349
- onPaymentFailure: config.onPaymentFailure
469
+ onPaymentFailure: config.onPaymentFailure,
470
+ onPaymentAttemptFailed: config.onPaymentAttemptFailed
350
471
  });
351
472
  return fetcher.fetch;
352
473
  }
353
474
  class ATXPFetcher {
354
475
  constructor(config) {
355
- this.defaultPaymentFailureHandler = async ({ payment, error }) => {
476
+ this.defaultPaymentFailureHandler = async (context) => {
477
+ const { payment, error, attemptedNetworks, retryable } = context;
478
+ const recoveryHint = common.getErrorRecoveryHint(error);
479
+ this.logger.info(`PAYMENT FAILED: ${recoveryHint.title}`);
480
+ this.logger.info(`Description: ${recoveryHint.description}`);
481
+ if (attemptedNetworks.length > 0) {
482
+ this.logger.info(`Attempted networks: ${attemptedNetworks.join(', ')}`);
483
+ }
484
+ this.logger.info(`Account: ${payment.accountId}`);
485
+ // Log actionable guidance
486
+ if (recoveryHint.actions.length > 0) {
487
+ this.logger.info(`What to do:`);
488
+ recoveryHint.actions.forEach((action, index) => {
489
+ this.logger.info(` ${index + 1}. ${action}`);
490
+ });
491
+ }
492
+ if (retryable) {
493
+ this.logger.info(`This payment can be retried.`);
494
+ }
495
+ // Log additional context for specific error types
356
496
  if (error instanceof InsufficientFundsError) {
357
- const networkText = error.network ? ` on ${error.network}` : '';
358
- this.logger.info(`PAYMENT FAILED: Insufficient ${error.currency} funds${networkText}`);
359
497
  this.logger.info(`Required: ${error.required} ${error.currency}`);
360
498
  if (error.available) {
361
499
  this.logger.info(`Available: ${error.available} ${error.currency}`);
362
500
  }
363
- this.logger.info(`Account: ${payment.accountId}`);
364
501
  }
365
- else if (error instanceof PaymentNetworkError) {
366
- this.logger.info(`PAYMENT FAILED: Network error: ${error.message}`);
367
- }
368
- else {
369
- this.logger.info(`PAYMENT FAILED: ${error.message}`);
502
+ else if (error instanceof ATXPPaymentError && error.context) {
503
+ this.logger.debug(`Error context: ${JSON.stringify(error.context)}`);
370
504
  }
371
505
  };
372
506
  this.handleMultiDestinationPayment = async (paymentRequest, paymentRequestUrl, paymentRequestId) => {
@@ -411,9 +545,11 @@ class ATXPFetcher {
411
545
  this.logger.info(`ATXP: payment request denied by callback function`);
412
546
  return false;
413
547
  }
414
- // Try each payment maker in order
548
+ // Try each payment maker in order, tracking attempts
415
549
  let lastPaymentError = null;
416
550
  let paymentAttempted = false;
551
+ const attemptedNetworks = [];
552
+ const failureReasons = new Map();
417
553
  for (const paymentMaker of this.account.paymentMakers) {
418
554
  try {
419
555
  // Pass all destinations to payment maker - it will filter and pick the one it can handle
@@ -425,7 +561,11 @@ class ATXPFetcher {
425
561
  paymentAttempted = true;
426
562
  // Payment was successful
427
563
  this.logger.info(`ATXP: made payment of ${firstDest.amount.toString()} ${firstDest.currency} on ${result.chain}: ${result.transactionId}`);
428
- await this.onPayment({ payment: prospectivePayment });
564
+ await this.onPayment({
565
+ payment: prospectivePayment,
566
+ transactionHash: result.transactionId,
567
+ network: result.chain
568
+ });
429
569
  // Submit payment to the server
430
570
  const jwt = await paymentMaker.generateJWT({ paymentRequestId, codeChallenge: '', accountId: this.account.accountId });
431
571
  const response = await this.sideChannelFetch(paymentRequestUrl.toString(), {
@@ -453,13 +593,41 @@ class ATXPFetcher {
453
593
  const typedError = error;
454
594
  paymentAttempted = true;
455
595
  lastPaymentError = typedError;
456
- this.logger.warn(`ATXP: payment maker failed: ${typedError.message}`);
457
- await this.onPaymentFailure({ payment: prospectivePayment, error: typedError });
596
+ // Extract network from error context if available
597
+ let network = 'unknown';
598
+ if (typedError instanceof ATXPPaymentError && typedError.context?.network) {
599
+ network = typeof typedError.context.network === 'string' ? typedError.context.network : 'unknown';
600
+ }
601
+ attemptedNetworks.push(network);
602
+ failureReasons.set(network, typedError);
603
+ this.logger.warn(`ATXP: payment maker failed on ${network}: ${typedError.message}`);
604
+ // Call optional per-attempt failure callback
605
+ if (this.onPaymentAttemptFailed) {
606
+ const remainingMakers = this.account.paymentMakers.length - (attemptedNetworks.length);
607
+ const remainingNetworks = remainingMakers > 0 ? ['next available'] : [];
608
+ await this.onPaymentAttemptFailed({
609
+ network,
610
+ error: typedError,
611
+ remainingNetworks
612
+ });
613
+ }
458
614
  // Continue to next payment maker
459
615
  }
460
616
  }
461
- // If payment was attempted but all failed, rethrow the last error
617
+ // If payment was attempted but all failed, create full context and call onPaymentFailure
462
618
  if (paymentAttempted && lastPaymentError) {
619
+ const isRetryable = lastPaymentError instanceof ATXPPaymentError
620
+ ? lastPaymentError.retryable
621
+ : true; // Default to retryable for unknown errors
622
+ const failureContext = {
623
+ payment: prospectivePayment,
624
+ error: lastPaymentError,
625
+ attemptedNetworks,
626
+ failureReasons,
627
+ retryable: isRetryable,
628
+ timestamp: new Date()
629
+ };
630
+ await this.onPaymentFailure(failureContext);
463
631
  throw lastPaymentError;
464
632
  }
465
633
  this.logger.info(`ATXP: no payment maker could handle these destinations`);
@@ -502,7 +670,7 @@ class ATXPFetcher {
502
670
  if (paymentRequest.options) {
503
671
  for (const option of paymentRequest.options) {
504
672
  if (typeof option.amount === 'string' || typeof option.amount === 'number') {
505
- option.amount = new BigNumber.BigNumber(option.amount);
673
+ option.amount = new bignumber_js.BigNumber(option.amount);
506
674
  }
507
675
  }
508
676
  }
@@ -707,7 +875,7 @@ class ATXPFetcher {
707
875
  throw error;
708
876
  }
709
877
  };
710
- const { account, db, destinationMakers, fetchFn = fetch, sideChannelFetch = fetchFn, strict = true, allowInsecureRequests = process.env.NODE_ENV === 'development', allowedAuthorizationServers = [common.DEFAULT_AUTHORIZATION_SERVER], approvePayment = async () => true, logger = new common.ConsoleLogger(), onAuthorize = async () => { }, onAuthorizeFailure = async () => { }, onPayment = async () => { }, onPaymentFailure = async () => { } } = config;
878
+ const { account, db, destinationMakers, fetchFn = fetch, sideChannelFetch = fetchFn, strict = true, allowInsecureRequests = process.env.NODE_ENV === 'development', allowedAuthorizationServers = [common.DEFAULT_AUTHORIZATION_SERVER], approvePayment = async () => true, logger = new common.ConsoleLogger(), onAuthorize = async () => { }, onAuthorizeFailure = async () => { }, onPayment = async () => { }, onPaymentFailure, onPaymentAttemptFailed } = config;
711
879
  // Use React Native safe fetch if in React Native environment
712
880
  const safeFetchFn = common.getIsReactNative() ? common.createReactNativeSafeFetch(fetchFn) : fetchFn;
713
881
  const safeSideChannelFetch = common.getIsReactNative() ? common.createReactNativeSafeFetch(sideChannelFetch) : sideChannelFetch;
@@ -736,6 +904,7 @@ class ATXPFetcher {
736
904
  this.onAuthorizeFailure = onAuthorizeFailure;
737
905
  this.onPayment = onPayment;
738
906
  this.onPaymentFailure = onPaymentFailure || this.defaultPaymentFailureHandler;
907
+ this.onPaymentAttemptFailed = onPaymentAttemptFailed;
739
908
  }
740
909
  }
741
910
 
@@ -15862,7 +16031,7 @@ function parseDestinationsResponse(data) {
15862
16031
  throw new Error(`Invalid destination at index ${index}: currency "${dest.currency}" is not a valid currency. Valid currencies are: ${validCurrencies}`);
15863
16032
  }
15864
16033
  // Validate amount is a valid number
15865
- const amount = new BigNumber.BigNumber(dest.amount);
16034
+ const amount = new bignumber_js.BigNumber(dest.amount);
15866
16035
  if (amount.isNaN()) {
15867
16036
  throw new Error(`Invalid destination at index ${index}: amount "${dest.amount}" is not a valid number`);
15868
16037
  }
@@ -16032,7 +16201,8 @@ const DEFAULT_CLIENT_CONFIG = {
16032
16201
  onAuthorize: async () => { },
16033
16202
  onAuthorizeFailure: async () => { },
16034
16203
  onPayment: async () => { },
16035
- onPaymentFailure: async () => { }
16204
+ onPaymentFailure: async () => { },
16205
+ onPaymentAttemptFailed: async () => { }
16036
16206
  };
16037
16207
  function buildClientConfig(args) {
16038
16208
  // Use fetchFn for oAuthChannelFetch if the latter isn't explicitly set
@@ -16078,310 +16248,6 @@ async function atxpClient(args) {
16078
16248
  return client;
16079
16249
  }
16080
16250
 
16081
- // this is a global public key for USDC on the solana mainnet
16082
- const USDC_MINT = new web3_js.PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
16083
- const ValidateTransferError = pay.ValidateTransferError;
16084
- class SolanaPaymentMaker {
16085
- constructor(solanaEndpoint, sourceSecretKey, logger) {
16086
- this.generateJWT = async ({ paymentRequestId, codeChallenge, accountId }) => {
16087
- // Solana/Web3.js secretKey is 64 bytes:
16088
- // first 32 bytes are the private scalar, last 32 are the public key.
16089
- // JWK expects only the 32-byte private scalar for 'd'
16090
- const jwk = {
16091
- kty: 'OKP',
16092
- crv: 'Ed25519',
16093
- d: Buffer.from(this.source.secretKey.slice(0, 32)).toString('base64url'),
16094
- x: Buffer.from(this.source.publicKey.toBytes()).toString('base64url'),
16095
- };
16096
- const privateKey = await jose.importJWK(jwk, 'EdDSA');
16097
- if (!(privateKey instanceof CryptoKey)) {
16098
- throw new Error('Expected CryptoKey from importJWK');
16099
- }
16100
- return common.generateJWT(this.source.publicKey.toBase58(), privateKey, paymentRequestId || '', codeChallenge || '', accountId);
16101
- };
16102
- this.makePayment = async (destinations, memo, _paymentRequestId) => {
16103
- // Filter to solana chain destinations
16104
- const solanaDestinations = destinations.filter(d => d.chain === 'solana');
16105
- if (solanaDestinations.length === 0) {
16106
- this.logger.debug('SolanaPaymentMaker: No solana destinations found, cannot handle payment');
16107
- return null; // Cannot handle these destinations
16108
- }
16109
- // Pick first solana destination
16110
- const dest = solanaDestinations[0];
16111
- const amount = dest.amount;
16112
- const currency = dest.currency;
16113
- const receiver = dest.address;
16114
- if (currency.toUpperCase() !== 'USDC') {
16115
- throw new PaymentNetworkError('Only USDC currency is supported; received ' + currency);
16116
- }
16117
- const receiverKey = new web3_js.PublicKey(receiver);
16118
- this.logger.info(`Making payment of ${amount} ${currency} to ${receiver} on Solana from ${this.source.publicKey.toBase58()}`);
16119
- try {
16120
- // Check balance before attempting payment
16121
- const tokenAccountAddress = await splToken.getAssociatedTokenAddress(USDC_MINT, this.source.publicKey);
16122
- const tokenAccount = await splToken.getAccount(this.connection, tokenAccountAddress);
16123
- const balance = new BigNumber(tokenAccount.amount.toString()).dividedBy(10 ** 6); // USDC has 6 decimals
16124
- if (balance.lt(amount)) {
16125
- this.logger.warn(`Insufficient ${currency} balance for payment. Required: ${amount}, Available: ${balance}`);
16126
- throw new InsufficientFundsError(currency, amount, balance, 'solana');
16127
- }
16128
- // Get the destination token account address (this will be the transactionId)
16129
- const destinationTokenAccount = await splToken.getAssociatedTokenAddress(USDC_MINT, receiverKey);
16130
- // Increase compute units to handle both memo and token transfer
16131
- // Memo uses ~6000 CUs, token transfer needs ~6500 CUs
16132
- const modifyComputeUnits = web3_js.ComputeBudgetProgram.setComputeUnitLimit({
16133
- units: 50000,
16134
- });
16135
- const addPriorityFee = web3_js.ComputeBudgetProgram.setComputeUnitPrice({
16136
- microLamports: 20000,
16137
- });
16138
- const transaction = await pay.createTransfer(this.connection, this.source.publicKey, {
16139
- amount: amount,
16140
- recipient: receiverKey,
16141
- splToken: USDC_MINT,
16142
- memo,
16143
- });
16144
- transaction.add(modifyComputeUnits);
16145
- transaction.add(addPriorityFee);
16146
- const transactionSignature = await web3_js.sendAndConfirmTransaction(this.connection, transaction, [this.source]);
16147
- // Return transaction signature as transactionId and token account address as transactionSubId
16148
- return {
16149
- transactionId: transactionSignature,
16150
- transactionSubId: destinationTokenAccount.toBase58(),
16151
- chain: 'solana',
16152
- currency: 'USDC'
16153
- };
16154
- }
16155
- catch (error) {
16156
- if (error instanceof InsufficientFundsError || error instanceof PaymentNetworkError) {
16157
- throw error;
16158
- }
16159
- // Wrap other errors in PaymentNetworkError
16160
- throw new PaymentNetworkError(`Payment failed on Solana network: ${error.message}`, error);
16161
- }
16162
- };
16163
- if (!solanaEndpoint) {
16164
- throw new Error('Solana endpoint is required');
16165
- }
16166
- if (!sourceSecretKey) {
16167
- throw new Error('Source secret key is required');
16168
- }
16169
- this.connection = new web3_js.Connection(solanaEndpoint, { commitment: 'confirmed' });
16170
- this.source = web3_js.Keypair.fromSecretKey(bs58.decode(sourceSecretKey));
16171
- this.logger = logger ?? new common.ConsoleLogger();
16172
- }
16173
- getSourceAddress(_params) {
16174
- return this.source.publicKey.toBase58();
16175
- }
16176
- }
16177
-
16178
- const USDC_CONTRACT_ADDRESS_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; // USDC on Base mainnet
16179
- const USDC_CONTRACT_ADDRESS_BASE_SEPOLIA = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; // USDC on Base Sepolia testnet
16180
- /**
16181
- * Get USDC contract address for Base chain by chain ID
16182
- * @param chainId - Chain ID (8453 for mainnet, 84532 for sepolia)
16183
- * @returns USDC contract address
16184
- * @throws Error if chain ID is not supported
16185
- */
16186
- const getBaseUSDCAddress = (chainId) => {
16187
- switch (chainId) {
16188
- case 8453: // Base mainnet
16189
- return USDC_CONTRACT_ADDRESS_BASE;
16190
- case 84532: // Base Sepolia
16191
- return USDC_CONTRACT_ADDRESS_BASE_SEPOLIA;
16192
- default:
16193
- throw new Error(`Unsupported Base Chain ID: ${chainId}. Supported chains: 8453 (mainnet), 84532 (sepolia)`);
16194
- }
16195
- };
16196
-
16197
- // Helper function to convert to base64url that works in both Node.js and browsers
16198
- function toBase64Url(data) {
16199
- // Convert string to base64
16200
- const base64 = typeof Buffer !== 'undefined'
16201
- ? Buffer.from(data).toString('base64')
16202
- : btoa(data);
16203
- // Convert base64 to base64url
16204
- return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
16205
- }
16206
- const USDC_DECIMALS = 6;
16207
- const ERC20_ABI = [
16208
- {
16209
- constant: false,
16210
- inputs: [
16211
- { name: "_to", type: "address" },
16212
- { name: "_value", type: "uint256" },
16213
- ],
16214
- name: "transfer",
16215
- outputs: [{ name: "", type: "bool" }],
16216
- type: "function",
16217
- },
16218
- {
16219
- "constant": true,
16220
- "inputs": [
16221
- {
16222
- "name": "_owner",
16223
- "type": "address"
16224
- }
16225
- ],
16226
- "name": "balanceOf",
16227
- "outputs": [
16228
- {
16229
- "name": "balance",
16230
- "type": "uint256"
16231
- }
16232
- ],
16233
- "payable": false,
16234
- "stateMutability": "view",
16235
- "type": "function"
16236
- }
16237
- ];
16238
- class BasePaymentMaker {
16239
- constructor(baseRPCUrl, walletClient, logger) {
16240
- if (!baseRPCUrl) {
16241
- throw new Error('baseRPCUrl was empty');
16242
- }
16243
- if (!walletClient) {
16244
- throw new Error('walletClient was empty');
16245
- }
16246
- if (!walletClient.account) {
16247
- throw new Error('walletClient.account was empty');
16248
- }
16249
- this.signingClient = walletClient.extend(viem.publicActions);
16250
- this.logger = logger ?? new common.ConsoleLogger();
16251
- }
16252
- getSourceAddress(_params) {
16253
- return this.signingClient.account.address;
16254
- }
16255
- async generateJWT({ paymentRequestId, codeChallenge, accountId }) {
16256
- const headerObj = { alg: 'ES256K' };
16257
- const payloadObj = {
16258
- sub: this.signingClient.account.address,
16259
- iss: 'accounts.atxp.ai',
16260
- aud: 'https://auth.atxp.ai',
16261
- iat: Math.floor(Date.now() / 1000),
16262
- exp: Math.floor(Date.now() / 1000) + 60 * 60,
16263
- ...(codeChallenge ? { code_challenge: codeChallenge } : {}),
16264
- ...(paymentRequestId ? { payment_request_id: paymentRequestId } : {}),
16265
- ...(accountId ? { account_id: accountId } : {}),
16266
- };
16267
- const header = toBase64Url(JSON.stringify(headerObj));
16268
- const payload = toBase64Url(JSON.stringify(payloadObj));
16269
- const message = `${header}.${payload}`;
16270
- const messageBytes = typeof Buffer !== 'undefined'
16271
- ? Buffer.from(message, 'utf8')
16272
- : new TextEncoder().encode(message);
16273
- const signResult = await this.signingClient.signMessage({
16274
- account: this.signingClient.account,
16275
- message: { raw: messageBytes },
16276
- });
16277
- // For ES256K, signature is typically 65 bytes (r,s,v)
16278
- // Server expects the hex signature string (with 0x prefix) to be base64url encoded
16279
- // This creates: base64url("0x6eb2565...") not base64url(rawBytes)
16280
- // Pass the hex string directly to toBase64Url which will UTF-8 encode and base64url it
16281
- const signature = toBase64Url(signResult);
16282
- const jwt = `${header}.${payload}.${signature}`;
16283
- this.logger.info(`Generated ES256K JWT: ${jwt}`);
16284
- return jwt;
16285
- }
16286
- async makePayment(destinations, _memo, _paymentRequestId) {
16287
- // Filter to base chain destinations
16288
- const baseDestinations = destinations.filter(d => d.chain === 'base');
16289
- if (baseDestinations.length === 0) {
16290
- this.logger.debug('BasePaymentMaker: No base destinations found, cannot handle payment');
16291
- return null; // Cannot handle these destinations
16292
- }
16293
- // Pick first base destination
16294
- const dest = baseDestinations[0];
16295
- const amount = dest.amount;
16296
- const currency = dest.currency;
16297
- const receiver = dest.address;
16298
- if (currency.toUpperCase() !== 'USDC') {
16299
- throw new PaymentNetworkError('Only USDC currency is supported; received ' + currency);
16300
- }
16301
- this.logger.info(`Making payment of ${amount} ${currency} to ${receiver} on Base from ${this.signingClient.account.address}`);
16302
- try {
16303
- // Check balance before attempting payment
16304
- const balanceRaw = await this.signingClient.readContract({
16305
- address: USDC_CONTRACT_ADDRESS_BASE,
16306
- abi: ERC20_ABI,
16307
- functionName: 'balanceOf',
16308
- args: [this.signingClient.account.address],
16309
- });
16310
- const balance = new BigNumber.BigNumber(balanceRaw.toString()).dividedBy(10 ** USDC_DECIMALS);
16311
- if (balance.lt(amount)) {
16312
- this.logger.warn(`Insufficient ${currency} balance for payment. Required: ${amount}, Available: ${balance}`);
16313
- throw new InsufficientFundsError(currency, amount, balance, 'base');
16314
- }
16315
- // Convert amount to USDC units (6 decimals) as BigInt
16316
- const amountInUSDCUnits = BigInt(amount.multipliedBy(10 ** USDC_DECIMALS).toFixed(0));
16317
- const data = viem.encodeFunctionData({
16318
- abi: ERC20_ABI,
16319
- functionName: "transfer",
16320
- args: [receiver, amountInUSDCUnits],
16321
- });
16322
- const hash = await this.signingClient.sendTransaction({
16323
- chain: chains.base,
16324
- account: this.signingClient.account,
16325
- to: USDC_CONTRACT_ADDRESS_BASE,
16326
- data: data,
16327
- value: viem.parseEther('0'),
16328
- maxPriorityFeePerGas: viem.parseEther('0.000000001')
16329
- });
16330
- // Wait for transaction confirmation with more blocks to ensure propagation
16331
- this.logger.info(`Waiting for transaction confirmation: ${hash}`);
16332
- const receipt = await this.signingClient.waitForTransactionReceipt({
16333
- hash: hash,
16334
- confirmations: 1
16335
- });
16336
- if (receipt.status === 'reverted') {
16337
- throw new PaymentNetworkError(`Transaction reverted: ${hash}`, new Error('Transaction reverted on chain'));
16338
- }
16339
- this.logger.info(`Transaction confirmed: ${hash} in block ${receipt.blockNumber}`);
16340
- // Return payment result with chain and currency
16341
- return {
16342
- transactionId: hash,
16343
- chain: 'base',
16344
- currency: 'USDC'
16345
- };
16346
- }
16347
- catch (error) {
16348
- if (error instanceof InsufficientFundsError || error instanceof PaymentNetworkError) {
16349
- throw error;
16350
- }
16351
- // Wrap other errors in PaymentNetworkError
16352
- throw new PaymentNetworkError(`Payment failed on Base network: ${error.message}`, error);
16353
- }
16354
- }
16355
- }
16356
-
16357
- class SolanaAccount {
16358
- constructor(solanaEndpoint, sourceSecretKey) {
16359
- if (!solanaEndpoint) {
16360
- throw new Error('Solana endpoint is required');
16361
- }
16362
- if (!sourceSecretKey) {
16363
- throw new Error('Source secret key is required');
16364
- }
16365
- const source = web3_js.Keypair.fromSecretKey(bs58.decode(sourceSecretKey));
16366
- this.sourcePublicKey = source.publicKey.toBase58();
16367
- // Format accountId as network:address
16368
- this.accountId = `solana:${this.sourcePublicKey}`;
16369
- this.paymentMakers = [
16370
- new SolanaPaymentMaker(solanaEndpoint, sourceSecretKey)
16371
- ];
16372
- }
16373
- /**
16374
- * Get sources for this account
16375
- */
16376
- async getSources() {
16377
- return [{
16378
- address: this.sourcePublicKey,
16379
- chain: 'solana',
16380
- walletType: 'eoa'
16381
- }];
16382
- }
16383
- }
16384
-
16385
16251
  const USDC_CONTRACT_ADDRESS_WORLD_MAINNET = "0x79A02482A880bCE3F13e09Da970dC34db4CD24d1"; // USDC.e on World Chain mainnet
16386
16252
  const USDC_CONTRACT_ADDRESS_WORLD_SEPOLIA = "0x79A02482A880bCE3F13e09Da970dC34db4CD24d1"; // USDC.e on World Chain Sepolia (placeholder - update with actual address)
16387
16253
  // World Chain Mainnet (Chain ID: 480)
@@ -16544,45 +16410,6 @@ const getPolygonUSDCAddress = (chainId) => {
16544
16410
  }
16545
16411
  };
16546
16412
 
16547
- class BaseAccount {
16548
- constructor(baseRPCUrl, sourceSecretKey) {
16549
- if (!baseRPCUrl) {
16550
- throw new Error('Base RPC URL is required');
16551
- }
16552
- if (!sourceSecretKey) {
16553
- throw new Error('Source secret key is required');
16554
- }
16555
- this.account = accounts.privateKeyToAccount(sourceSecretKey);
16556
- // Format accountId as network:address
16557
- this.accountId = `base:${this.account.address}`;
16558
- this.walletClient = viem.createWalletClient({
16559
- account: this.account,
16560
- chain: chains.base,
16561
- transport: viem.http(baseRPCUrl),
16562
- });
16563
- this.paymentMakers = [
16564
- new BasePaymentMaker(baseRPCUrl, this.walletClient)
16565
- ];
16566
- }
16567
- /**
16568
- * Get the LocalAccount (signer) for this account.
16569
- * This can be used with the x402 library or other signing operations.
16570
- */
16571
- getLocalAccount() {
16572
- return this.account;
16573
- }
16574
- /**
16575
- * Get sources for this account
16576
- */
16577
- async getSources() {
16578
- return [{
16579
- address: this.account.address,
16580
- chain: 'base',
16581
- walletType: 'eoa'
16582
- }];
16583
- }
16584
- }
16585
-
16586
16413
  function toBasicAuth(token) {
16587
16414
  // Basic auth is base64("username:password"), password is blank
16588
16415
  const b64 = Buffer.from(`${token}:`).toString('base64');
@@ -16689,32 +16516,32 @@ Object.defineProperty(exports, "ATXPAccount", {
16689
16516
  });
16690
16517
  exports.ATXPDestinationMaker = ATXPDestinationMaker;
16691
16518
  exports.ATXPLocalAccount = ATXPLocalAccount;
16692
- exports.BaseAccount = BaseAccount;
16693
- exports.BasePaymentMaker = BasePaymentMaker;
16519
+ exports.ATXPPaymentError = ATXPPaymentError;
16694
16520
  exports.DEFAULT_CLIENT_CONFIG = DEFAULT_CLIENT_CONFIG;
16521
+ exports.GasEstimationError = GasEstimationError;
16695
16522
  exports.InsufficientFundsError = InsufficientFundsError;
16696
16523
  exports.OAuthAuthenticationRequiredError = OAuthAuthenticationRequiredError;
16697
16524
  exports.OAuthClient = OAuthClient;
16698
16525
  exports.POLYGON_AMOY = POLYGON_AMOY;
16699
16526
  exports.POLYGON_MAINNET = POLYGON_MAINNET;
16700
16527
  exports.PassthroughDestinationMaker = PassthroughDestinationMaker;
16528
+ exports.PaymentExpiredError = PaymentExpiredError;
16701
16529
  exports.PaymentNetworkError = PaymentNetworkError;
16702
- exports.SolanaAccount = SolanaAccount;
16703
- exports.SolanaPaymentMaker = SolanaPaymentMaker;
16704
- exports.USDC_CONTRACT_ADDRESS_BASE = USDC_CONTRACT_ADDRESS_BASE;
16705
- exports.USDC_CONTRACT_ADDRESS_BASE_SEPOLIA = USDC_CONTRACT_ADDRESS_BASE_SEPOLIA;
16530
+ exports.PaymentServerError = PaymentServerError;
16531
+ exports.RpcError = RpcError;
16532
+ exports.TransactionRevertedError = TransactionRevertedError;
16706
16533
  exports.USDC_CONTRACT_ADDRESS_POLYGON_AMOY = USDC_CONTRACT_ADDRESS_POLYGON_AMOY;
16707
16534
  exports.USDC_CONTRACT_ADDRESS_POLYGON_MAINNET = USDC_CONTRACT_ADDRESS_POLYGON_MAINNET;
16708
16535
  exports.USDC_CONTRACT_ADDRESS_WORLD_MAINNET = USDC_CONTRACT_ADDRESS_WORLD_MAINNET;
16709
16536
  exports.USDC_CONTRACT_ADDRESS_WORLD_SEPOLIA = USDC_CONTRACT_ADDRESS_WORLD_SEPOLIA;
16710
- exports.ValidateTransferError = ValidateTransferError;
16537
+ exports.UnsupportedCurrencyError = UnsupportedCurrencyError;
16538
+ exports.UserRejectedError = UserRejectedError;
16711
16539
  exports.WORLD_CHAIN_MAINNET = WORLD_CHAIN_MAINNET;
16712
16540
  exports.WORLD_CHAIN_SEPOLIA = WORLD_CHAIN_SEPOLIA;
16713
16541
  exports.atxpClient = atxpClient;
16714
16542
  exports.atxpFetch = atxpFetch;
16715
16543
  exports.buildClientConfig = buildClientConfig;
16716
16544
  exports.buildStreamableTransport = buildStreamableTransport;
16717
- exports.getBaseUSDCAddress = getBaseUSDCAddress;
16718
16545
  exports.getPolygonAmoyWithRPC = getPolygonAmoyWithRPC;
16719
16546
  exports.getPolygonByChainId = getPolygonByChainId;
16720
16547
  exports.getPolygonMainnetWithRPC = getPolygonMainnetWithRPC;