@atxp/client 0.8.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,12 +1,10 @@
1
- import { Account, Network, DestinationMaker, AuthorizationServerUrl, AccountId, Currency, OAuthDb, FetchLike, Logger, OAuthResourceClient, ClientCredentials, PKCEValues, AccessToken, PaymentMaker, Destination, PaymentIdentifier, Source, PaymentRequestOption } from '@atxp/common';
1
+ import { Account, Network, DestinationMaker, AuthorizationServerUrl, AccountId, Currency, OAuthDb, FetchLike, Logger, OAuthResourceClient, ClientCredentials, PKCEValues, AccessToken, PaymentRequestOption, Source, Destination } from '@atxp/common';
2
2
  export { ATXPAccount, Account, PaymentMaker } from '@atxp/common';
3
3
  import { ClientOptions, Client } from '@modelcontextprotocol/sdk/client/index.js';
4
4
  import { Implementation } from '@modelcontextprotocol/sdk/types.js';
5
5
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
6
6
  import * as oauth from 'oauth4webapi';
7
- import { ValidateTransferError as ValidateTransferError$1 } from '@solana/pay';
8
- import BigNumber$1 from 'bignumber.js';
9
- import { WalletClient, PublicActions, LocalAccount, Address, TypedData, Hex as Hex$1, SignableMessage, TransactionSerializable } from 'viem';
7
+ import { LocalAccount, Address, TypedData, Hex as Hex$1, SignableMessage, TransactionSerializable } from 'viem';
10
8
 
11
9
  type Hex = `0x${string}`;
12
10
  type AccountPrefix = Network;
@@ -125,66 +123,6 @@ declare class OAuthClient extends OAuthResourceClient {
125
123
  */
126
124
  declare function atxpFetch(config: ClientConfig): FetchLike;
127
125
 
128
- declare const ValidateTransferError: typeof ValidateTransferError$1;
129
- declare class SolanaPaymentMaker implements PaymentMaker {
130
- private connection;
131
- private source;
132
- private logger;
133
- constructor(solanaEndpoint: string, sourceSecretKey: string, logger?: Logger);
134
- getSourceAddress(_params: {
135
- amount: BigNumber$1;
136
- currency: Currency;
137
- receiver: string;
138
- memo: string;
139
- }): string;
140
- generateJWT: ({ paymentRequestId, codeChallenge, accountId }: {
141
- paymentRequestId: string;
142
- codeChallenge: string;
143
- accountId?: AccountId | null;
144
- }) => Promise<string>;
145
- makePayment: (destinations: Destination[], memo: string, _paymentRequestId?: string) => Promise<PaymentIdentifier | null>;
146
- }
147
-
148
- type ExtendedWalletClient = WalletClient & PublicActions;
149
- declare class BasePaymentMaker implements PaymentMaker {
150
- protected signingClient: ExtendedWalletClient;
151
- protected logger: Logger;
152
- constructor(baseRPCUrl: string, walletClient: WalletClient, logger?: Logger);
153
- getSourceAddress(_params: {
154
- amount: BigNumber;
155
- currency: Currency;
156
- receiver: string;
157
- memo: string;
158
- }): string;
159
- generateJWT({ paymentRequestId, codeChallenge, accountId }: {
160
- paymentRequestId: string;
161
- codeChallenge: string;
162
- accountId?: AccountId | null;
163
- }): Promise<string>;
164
- makePayment(destinations: Destination[], _memo: string, _paymentRequestId?: string): Promise<PaymentIdentifier | null>;
165
- }
166
-
167
- declare class SolanaAccount implements Account {
168
- accountId: AccountId;
169
- paymentMakers: PaymentMaker[];
170
- private sourcePublicKey;
171
- constructor(solanaEndpoint: string, sourceSecretKey: string);
172
- /**
173
- * Get sources for this account
174
- */
175
- getSources(): Promise<Source[]>;
176
- }
177
-
178
- declare const USDC_CONTRACT_ADDRESS_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
179
- declare const USDC_CONTRACT_ADDRESS_BASE_SEPOLIA = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
180
- /**
181
- * Get USDC contract address for Base chain by chain ID
182
- * @param chainId - Chain ID (8453 for mainnet, 84532 for sepolia)
183
- * @returns USDC contract address
184
- * @throws Error if chain ID is not supported
185
- */
186
- declare const getBaseUSDCAddress: (chainId: number) => string;
187
-
188
126
  /**
189
127
  * World Chain configuration type, compatible with viem's Chain interface
190
128
  */
@@ -291,23 +229,6 @@ declare const getPolygonByChainId: (chainId: number) => PolygonChain;
291
229
  */
292
230
  declare const getPolygonUSDCAddress: (chainId: number) => string;
293
231
 
294
- declare class BaseAccount implements Account {
295
- accountId: AccountId;
296
- paymentMakers: PaymentMaker[];
297
- private walletClient;
298
- private account;
299
- constructor(baseRPCUrl: string, sourceSecretKey: string);
300
- /**
301
- * Get the LocalAccount (signer) for this account.
302
- * This can be used with the x402 library or other signing operations.
303
- */
304
- getLocalAccount(): LocalAccount;
305
- /**
306
- * Get sources for this account
307
- */
308
- getSources(): Promise<Source[]>;
309
- }
310
-
311
232
  /**
312
233
  * ATXP implementation of viem's LocalAccount interface.
313
234
  * Delegates signing operations to the accounts-x402 API.
@@ -375,5 +296,5 @@ declare class PassthroughDestinationMaker implements DestinationMaker {
375
296
  makeDestinations(option: PaymentRequestOption, _logger: Logger, _paymentRequestId: string, _sources: Source[]): Promise<Destination[]>;
376
297
  }
377
298
 
378
- export { ATXPDestinationMaker, ATXPLocalAccount, BaseAccount, BasePaymentMaker, DEFAULT_CLIENT_CONFIG, InsufficientFundsError, OAuthAuthenticationRequiredError, OAuthClient, POLYGON_AMOY, POLYGON_MAINNET, PassthroughDestinationMaker, PaymentNetworkError, SolanaAccount, SolanaPaymentMaker, USDC_CONTRACT_ADDRESS_BASE, USDC_CONTRACT_ADDRESS_BASE_SEPOLIA, USDC_CONTRACT_ADDRESS_POLYGON_AMOY, USDC_CONTRACT_ADDRESS_POLYGON_MAINNET, USDC_CONTRACT_ADDRESS_WORLD_MAINNET, USDC_CONTRACT_ADDRESS_WORLD_SEPOLIA, ValidateTransferError, WORLD_CHAIN_MAINNET, WORLD_CHAIN_SEPOLIA, atxpClient, atxpFetch, buildClientConfig, buildStreamableTransport, getBaseUSDCAddress, getPolygonAmoyWithRPC, getPolygonByChainId, getPolygonMainnetWithRPC, getPolygonUSDCAddress, getWorldChainByChainId, getWorldChainMainnetWithRPC, getWorldChainSepoliaWithRPC, getWorldChainUSDCAddress };
299
+ export { ATXPDestinationMaker, ATXPLocalAccount, DEFAULT_CLIENT_CONFIG, InsufficientFundsError, OAuthAuthenticationRequiredError, OAuthClient, POLYGON_AMOY, POLYGON_MAINNET, PassthroughDestinationMaker, PaymentNetworkError, USDC_CONTRACT_ADDRESS_POLYGON_AMOY, USDC_CONTRACT_ADDRESS_POLYGON_MAINNET, USDC_CONTRACT_ADDRESS_WORLD_MAINNET, USDC_CONTRACT_ADDRESS_WORLD_SEPOLIA, WORLD_CHAIN_MAINNET, WORLD_CHAIN_SEPOLIA, atxpClient, atxpFetch, buildClientConfig, buildStreamableTransport, getPolygonAmoyWithRPC, getPolygonByChainId, getPolygonMainnetWithRPC, getPolygonUSDCAddress, getWorldChainByChainId, getWorldChainMainnetWithRPC, getWorldChainSepoliaWithRPC, getWorldChainUSDCAddress };
379
300
  export type { AccountIdString, ClientArgs, ClientConfig, FetchWrapper, Hex, OAuthClientConfig, PolygonChain, ProspectivePayment, WorldChain };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,qBAAqB,EACrB,iBAAiB,EACjB,wBAAwB,EACxB,UAAU,EACX,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACL,gCAAgC,EAChC,KAAK,iBAAiB,EACtB,WAAW,EACZ,MAAM,YAAY,CAAC;AAGpB,OAAO,EACL,SAAS,EACV,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EACnB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EACL,gBAAgB,EACjB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,aAAa,EACd,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,WAAW,EACZ,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,0BAA0B,EAC1B,kCAAkC,EAClC,kBAAkB,EACnB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,mCAAmC,EACnC,mCAAmC,EACnC,mBAAmB,EACnB,mBAAmB,EACnB,2BAA2B,EAC3B,2BAA2B,EAC3B,sBAAsB,EACtB,wBAAwB,EACxB,KAAK,UAAU,EAChB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,qCAAqC,EACrC,kCAAkC,EAClC,eAAe,EACf,YAAY,EACZ,wBAAwB,EACxB,qBAAqB,EACrB,mBAAmB,EACnB,qBAAqB,EACrB,KAAK,YAAY,EAClB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EACL,WAAW,EACZ,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,KAAK,GAAG,EACR,KAAK,eAAe,EACpB,KAAK,OAAO,EACZ,KAAK,kBAAkB,EACvB,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,sBAAsB,EACtB,mBAAmB,EACnB,KAAK,YAAY,EAClB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,gBAAgB,EACjB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,oBAAoB,EACpB,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,qBAAqB,EACrB,iBAAiB,EACjB,wBAAwB,EACxB,UAAU,EACX,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACL,gCAAgC,EAChC,KAAK,iBAAiB,EACtB,WAAW,EACZ,MAAM,YAAY,CAAC;AAGpB,OAAO,EACL,SAAS,EACV,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACL,WAAW,EACZ,MAAM,cAAc,CAAC;AAGtB,OAAO,EACL,mCAAmC,EACnC,mCAAmC,EACnC,mBAAmB,EACnB,mBAAmB,EACnB,2BAA2B,EAC3B,2BAA2B,EAC3B,sBAAsB,EACtB,wBAAwB,EACxB,KAAK,UAAU,EAChB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EACL,qCAAqC,EACrC,kCAAkC,EAClC,eAAe,EACf,YAAY,EACZ,wBAAwB,EACxB,qBAAqB,EACrB,mBAAmB,EACnB,qBAAqB,EACrB,KAAK,YAAY,EAClB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,KAAK,GAAG,EACR,KAAK,eAAe,EACpB,KAAK,OAAO,EACZ,KAAK,kBAAkB,EACvB,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,sBAAsB,EACtB,mBAAmB,EACnB,KAAK,YAAY,EAClB,MAAM,YAAY,CAAC;AAGpB,OAAO,EACL,gBAAgB,EACjB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,oBAAoB,EACpB,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC"}
package/dist/index.js CHANGED
@@ -1,15 +1,7 @@
1
- import { crypto as crypto$1, OAuthResourceClient, ConsoleLogger, PAYMENT_REQUIRED_ERROR_CODE, isSSEResponse, parseMcpMessages, parsePaymentRequests, paymentRequiredError, DEFAULT_AUTHORIZATION_SERVER, getIsReactNative, createReactNativeSafeFetch, isEnumValue, ChainEnum, CurrencyEnum, NetworkEnum, assertNever, DEFAULT_ATXP_ACCOUNTS_SERVER, MemoryOAuthDb, ATXPAccount, generateJWT } from '@atxp/common';
1
+ import { crypto as crypto$1, OAuthResourceClient, ConsoleLogger, PAYMENT_REQUIRED_ERROR_CODE, isSSEResponse, parseMcpMessages, parsePaymentRequests, paymentRequiredError, DEFAULT_AUTHORIZATION_SERVER, getIsReactNative, createReactNativeSafeFetch, isEnumValue, ChainEnum, CurrencyEnum, NetworkEnum, assertNever, DEFAULT_ATXP_ACCOUNTS_SERVER, MemoryOAuthDb, ATXPAccount } from '@atxp/common';
2
2
  export { ATXPAccount } from '@atxp/common';
3
3
  import * as oauth from 'oauth4webapi';
4
- import BigNumber$1, { BigNumber } from 'bignumber.js';
5
- import { PublicKey, ComputeBudgetProgram, sendAndConfirmTransaction, Connection, Keypair } from '@solana/web3.js';
6
- import { ValidateTransferError as ValidateTransferError$1, createTransfer } from '@solana/pay';
7
- import { getAssociatedTokenAddress, getAccount } from '@solana/spl-token';
8
- import bs58 from 'bs58';
9
- import { importJWK } from 'jose';
10
- import { publicActions, encodeFunctionData, parseEther, createWalletClient, http } from 'viem';
11
- import { base } from 'viem/chains';
12
- import { privateKeyToAccount } from 'viem/accounts';
4
+ import { BigNumber } from 'bignumber.js';
13
5
 
14
6
  class OAuthAuthenticationRequiredError extends Error {
15
7
  constructor(url, resourceServerUrl,
@@ -16058,310 +16050,6 @@ async function atxpClient(args) {
16058
16050
  return client;
16059
16051
  }
16060
16052
 
16061
- // this is a global public key for USDC on the solana mainnet
16062
- const USDC_MINT = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
16063
- const ValidateTransferError = ValidateTransferError$1;
16064
- class SolanaPaymentMaker {
16065
- constructor(solanaEndpoint, sourceSecretKey, logger) {
16066
- this.generateJWT = async ({ paymentRequestId, codeChallenge, accountId }) => {
16067
- // Solana/Web3.js secretKey is 64 bytes:
16068
- // first 32 bytes are the private scalar, last 32 are the public key.
16069
- // JWK expects only the 32-byte private scalar for 'd'
16070
- const jwk = {
16071
- kty: 'OKP',
16072
- crv: 'Ed25519',
16073
- d: Buffer.from(this.source.secretKey.slice(0, 32)).toString('base64url'),
16074
- x: Buffer.from(this.source.publicKey.toBytes()).toString('base64url'),
16075
- };
16076
- const privateKey = await importJWK(jwk, 'EdDSA');
16077
- if (!(privateKey instanceof CryptoKey)) {
16078
- throw new Error('Expected CryptoKey from importJWK');
16079
- }
16080
- return generateJWT(this.source.publicKey.toBase58(), privateKey, paymentRequestId || '', codeChallenge || '', accountId);
16081
- };
16082
- this.makePayment = async (destinations, memo, _paymentRequestId) => {
16083
- // Filter to solana chain destinations
16084
- const solanaDestinations = destinations.filter(d => d.chain === 'solana');
16085
- if (solanaDestinations.length === 0) {
16086
- this.logger.debug('SolanaPaymentMaker: No solana destinations found, cannot handle payment');
16087
- return null; // Cannot handle these destinations
16088
- }
16089
- // Pick first solana destination
16090
- const dest = solanaDestinations[0];
16091
- const amount = dest.amount;
16092
- const currency = dest.currency;
16093
- const receiver = dest.address;
16094
- if (currency.toUpperCase() !== 'USDC') {
16095
- throw new PaymentNetworkError('Only USDC currency is supported; received ' + currency);
16096
- }
16097
- const receiverKey = new PublicKey(receiver);
16098
- this.logger.info(`Making payment of ${amount} ${currency} to ${receiver} on Solana from ${this.source.publicKey.toBase58()}`);
16099
- try {
16100
- // Check balance before attempting payment
16101
- const tokenAccountAddress = await getAssociatedTokenAddress(USDC_MINT, this.source.publicKey);
16102
- const tokenAccount = await getAccount(this.connection, tokenAccountAddress);
16103
- const balance = new BigNumber$1(tokenAccount.amount.toString()).dividedBy(10 ** 6); // USDC has 6 decimals
16104
- if (balance.lt(amount)) {
16105
- this.logger.warn(`Insufficient ${currency} balance for payment. Required: ${amount}, Available: ${balance}`);
16106
- throw new InsufficientFundsError(currency, amount, balance, 'solana');
16107
- }
16108
- // Get the destination token account address (this will be the transactionId)
16109
- const destinationTokenAccount = await getAssociatedTokenAddress(USDC_MINT, receiverKey);
16110
- // Increase compute units to handle both memo and token transfer
16111
- // Memo uses ~6000 CUs, token transfer needs ~6500 CUs
16112
- const modifyComputeUnits = ComputeBudgetProgram.setComputeUnitLimit({
16113
- units: 50000,
16114
- });
16115
- const addPriorityFee = ComputeBudgetProgram.setComputeUnitPrice({
16116
- microLamports: 20000,
16117
- });
16118
- const transaction = await createTransfer(this.connection, this.source.publicKey, {
16119
- amount: amount,
16120
- recipient: receiverKey,
16121
- splToken: USDC_MINT,
16122
- memo,
16123
- });
16124
- transaction.add(modifyComputeUnits);
16125
- transaction.add(addPriorityFee);
16126
- const transactionSignature = await sendAndConfirmTransaction(this.connection, transaction, [this.source]);
16127
- // Return transaction signature as transactionId and token account address as transactionSubId
16128
- return {
16129
- transactionId: transactionSignature,
16130
- transactionSubId: destinationTokenAccount.toBase58(),
16131
- chain: 'solana',
16132
- currency: 'USDC'
16133
- };
16134
- }
16135
- catch (error) {
16136
- if (error instanceof InsufficientFundsError || error instanceof PaymentNetworkError) {
16137
- throw error;
16138
- }
16139
- // Wrap other errors in PaymentNetworkError
16140
- throw new PaymentNetworkError(`Payment failed on Solana network: ${error.message}`, error);
16141
- }
16142
- };
16143
- if (!solanaEndpoint) {
16144
- throw new Error('Solana endpoint is required');
16145
- }
16146
- if (!sourceSecretKey) {
16147
- throw new Error('Source secret key is required');
16148
- }
16149
- this.connection = new Connection(solanaEndpoint, { commitment: 'confirmed' });
16150
- this.source = Keypair.fromSecretKey(bs58.decode(sourceSecretKey));
16151
- this.logger = logger ?? new ConsoleLogger();
16152
- }
16153
- getSourceAddress(_params) {
16154
- return this.source.publicKey.toBase58();
16155
- }
16156
- }
16157
-
16158
- const USDC_CONTRACT_ADDRESS_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; // USDC on Base mainnet
16159
- const USDC_CONTRACT_ADDRESS_BASE_SEPOLIA = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; // USDC on Base Sepolia testnet
16160
- /**
16161
- * Get USDC contract address for Base chain by chain ID
16162
- * @param chainId - Chain ID (8453 for mainnet, 84532 for sepolia)
16163
- * @returns USDC contract address
16164
- * @throws Error if chain ID is not supported
16165
- */
16166
- const getBaseUSDCAddress = (chainId) => {
16167
- switch (chainId) {
16168
- case 8453: // Base mainnet
16169
- return USDC_CONTRACT_ADDRESS_BASE;
16170
- case 84532: // Base Sepolia
16171
- return USDC_CONTRACT_ADDRESS_BASE_SEPOLIA;
16172
- default:
16173
- throw new Error(`Unsupported Base Chain ID: ${chainId}. Supported chains: 8453 (mainnet), 84532 (sepolia)`);
16174
- }
16175
- };
16176
-
16177
- // Helper function to convert to base64url that works in both Node.js and browsers
16178
- function toBase64Url(data) {
16179
- // Convert string to base64
16180
- const base64 = typeof Buffer !== 'undefined'
16181
- ? Buffer.from(data).toString('base64')
16182
- : btoa(data);
16183
- // Convert base64 to base64url
16184
- return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
16185
- }
16186
- const USDC_DECIMALS = 6;
16187
- const ERC20_ABI = [
16188
- {
16189
- constant: false,
16190
- inputs: [
16191
- { name: "_to", type: "address" },
16192
- { name: "_value", type: "uint256" },
16193
- ],
16194
- name: "transfer",
16195
- outputs: [{ name: "", type: "bool" }],
16196
- type: "function",
16197
- },
16198
- {
16199
- "constant": true,
16200
- "inputs": [
16201
- {
16202
- "name": "_owner",
16203
- "type": "address"
16204
- }
16205
- ],
16206
- "name": "balanceOf",
16207
- "outputs": [
16208
- {
16209
- "name": "balance",
16210
- "type": "uint256"
16211
- }
16212
- ],
16213
- "payable": false,
16214
- "stateMutability": "view",
16215
- "type": "function"
16216
- }
16217
- ];
16218
- class BasePaymentMaker {
16219
- constructor(baseRPCUrl, walletClient, logger) {
16220
- if (!baseRPCUrl) {
16221
- throw new Error('baseRPCUrl was empty');
16222
- }
16223
- if (!walletClient) {
16224
- throw new Error('walletClient was empty');
16225
- }
16226
- if (!walletClient.account) {
16227
- throw new Error('walletClient.account was empty');
16228
- }
16229
- this.signingClient = walletClient.extend(publicActions);
16230
- this.logger = logger ?? new ConsoleLogger();
16231
- }
16232
- getSourceAddress(_params) {
16233
- return this.signingClient.account.address;
16234
- }
16235
- async generateJWT({ paymentRequestId, codeChallenge, accountId }) {
16236
- const headerObj = { alg: 'ES256K' };
16237
- const payloadObj = {
16238
- sub: this.signingClient.account.address,
16239
- iss: 'accounts.atxp.ai',
16240
- aud: 'https://auth.atxp.ai',
16241
- iat: Math.floor(Date.now() / 1000),
16242
- exp: Math.floor(Date.now() / 1000) + 60 * 60,
16243
- ...(codeChallenge ? { code_challenge: codeChallenge } : {}),
16244
- ...(paymentRequestId ? { payment_request_id: paymentRequestId } : {}),
16245
- ...(accountId ? { account_id: accountId } : {}),
16246
- };
16247
- const header = toBase64Url(JSON.stringify(headerObj));
16248
- const payload = toBase64Url(JSON.stringify(payloadObj));
16249
- const message = `${header}.${payload}`;
16250
- const messageBytes = typeof Buffer !== 'undefined'
16251
- ? Buffer.from(message, 'utf8')
16252
- : new TextEncoder().encode(message);
16253
- const signResult = await this.signingClient.signMessage({
16254
- account: this.signingClient.account,
16255
- message: { raw: messageBytes },
16256
- });
16257
- // For ES256K, signature is typically 65 bytes (r,s,v)
16258
- // Server expects the hex signature string (with 0x prefix) to be base64url encoded
16259
- // This creates: base64url("0x6eb2565...") not base64url(rawBytes)
16260
- // Pass the hex string directly to toBase64Url which will UTF-8 encode and base64url it
16261
- const signature = toBase64Url(signResult);
16262
- const jwt = `${header}.${payload}.${signature}`;
16263
- this.logger.info(`Generated ES256K JWT: ${jwt}`);
16264
- return jwt;
16265
- }
16266
- async makePayment(destinations, _memo, _paymentRequestId) {
16267
- // Filter to base chain destinations
16268
- const baseDestinations = destinations.filter(d => d.chain === 'base');
16269
- if (baseDestinations.length === 0) {
16270
- this.logger.debug('BasePaymentMaker: No base destinations found, cannot handle payment');
16271
- return null; // Cannot handle these destinations
16272
- }
16273
- // Pick first base destination
16274
- const dest = baseDestinations[0];
16275
- const amount = dest.amount;
16276
- const currency = dest.currency;
16277
- const receiver = dest.address;
16278
- if (currency.toUpperCase() !== 'USDC') {
16279
- throw new PaymentNetworkError('Only USDC currency is supported; received ' + currency);
16280
- }
16281
- this.logger.info(`Making payment of ${amount} ${currency} to ${receiver} on Base from ${this.signingClient.account.address}`);
16282
- try {
16283
- // Check balance before attempting payment
16284
- const balanceRaw = await this.signingClient.readContract({
16285
- address: USDC_CONTRACT_ADDRESS_BASE,
16286
- abi: ERC20_ABI,
16287
- functionName: 'balanceOf',
16288
- args: [this.signingClient.account.address],
16289
- });
16290
- const balance = new BigNumber(balanceRaw.toString()).dividedBy(10 ** USDC_DECIMALS);
16291
- if (balance.lt(amount)) {
16292
- this.logger.warn(`Insufficient ${currency} balance for payment. Required: ${amount}, Available: ${balance}`);
16293
- throw new InsufficientFundsError(currency, amount, balance, 'base');
16294
- }
16295
- // Convert amount to USDC units (6 decimals) as BigInt
16296
- const amountInUSDCUnits = BigInt(amount.multipliedBy(10 ** USDC_DECIMALS).toFixed(0));
16297
- const data = encodeFunctionData({
16298
- abi: ERC20_ABI,
16299
- functionName: "transfer",
16300
- args: [receiver, amountInUSDCUnits],
16301
- });
16302
- const hash = await this.signingClient.sendTransaction({
16303
- chain: base,
16304
- account: this.signingClient.account,
16305
- to: USDC_CONTRACT_ADDRESS_BASE,
16306
- data: data,
16307
- value: parseEther('0'),
16308
- maxPriorityFeePerGas: parseEther('0.000000001')
16309
- });
16310
- // Wait for transaction confirmation with more blocks to ensure propagation
16311
- this.logger.info(`Waiting for transaction confirmation: ${hash}`);
16312
- const receipt = await this.signingClient.waitForTransactionReceipt({
16313
- hash: hash,
16314
- confirmations: 1
16315
- });
16316
- if (receipt.status === 'reverted') {
16317
- throw new PaymentNetworkError(`Transaction reverted: ${hash}`, new Error('Transaction reverted on chain'));
16318
- }
16319
- this.logger.info(`Transaction confirmed: ${hash} in block ${receipt.blockNumber}`);
16320
- // Return payment result with chain and currency
16321
- return {
16322
- transactionId: hash,
16323
- chain: 'base',
16324
- currency: 'USDC'
16325
- };
16326
- }
16327
- catch (error) {
16328
- if (error instanceof InsufficientFundsError || error instanceof PaymentNetworkError) {
16329
- throw error;
16330
- }
16331
- // Wrap other errors in PaymentNetworkError
16332
- throw new PaymentNetworkError(`Payment failed on Base network: ${error.message}`, error);
16333
- }
16334
- }
16335
- }
16336
-
16337
- class SolanaAccount {
16338
- constructor(solanaEndpoint, sourceSecretKey) {
16339
- if (!solanaEndpoint) {
16340
- throw new Error('Solana endpoint is required');
16341
- }
16342
- if (!sourceSecretKey) {
16343
- throw new Error('Source secret key is required');
16344
- }
16345
- const source = Keypair.fromSecretKey(bs58.decode(sourceSecretKey));
16346
- this.sourcePublicKey = source.publicKey.toBase58();
16347
- // Format accountId as network:address
16348
- this.accountId = `solana:${this.sourcePublicKey}`;
16349
- this.paymentMakers = [
16350
- new SolanaPaymentMaker(solanaEndpoint, sourceSecretKey)
16351
- ];
16352
- }
16353
- /**
16354
- * Get sources for this account
16355
- */
16356
- async getSources() {
16357
- return [{
16358
- address: this.sourcePublicKey,
16359
- chain: 'solana',
16360
- walletType: 'eoa'
16361
- }];
16362
- }
16363
- }
16364
-
16365
16053
  const USDC_CONTRACT_ADDRESS_WORLD_MAINNET = "0x79A02482A880bCE3F13e09Da970dC34db4CD24d1"; // USDC.e on World Chain mainnet
16366
16054
  const USDC_CONTRACT_ADDRESS_WORLD_SEPOLIA = "0x79A02482A880bCE3F13e09Da970dC34db4CD24d1"; // USDC.e on World Chain Sepolia (placeholder - update with actual address)
16367
16055
  // World Chain Mainnet (Chain ID: 480)
@@ -16524,45 +16212,6 @@ const getPolygonUSDCAddress = (chainId) => {
16524
16212
  }
16525
16213
  };
16526
16214
 
16527
- class BaseAccount {
16528
- constructor(baseRPCUrl, sourceSecretKey) {
16529
- if (!baseRPCUrl) {
16530
- throw new Error('Base RPC URL is required');
16531
- }
16532
- if (!sourceSecretKey) {
16533
- throw new Error('Source secret key is required');
16534
- }
16535
- this.account = privateKeyToAccount(sourceSecretKey);
16536
- // Format accountId as network:address
16537
- this.accountId = `base:${this.account.address}`;
16538
- this.walletClient = createWalletClient({
16539
- account: this.account,
16540
- chain: base,
16541
- transport: http(baseRPCUrl),
16542
- });
16543
- this.paymentMakers = [
16544
- new BasePaymentMaker(baseRPCUrl, this.walletClient)
16545
- ];
16546
- }
16547
- /**
16548
- * Get the LocalAccount (signer) for this account.
16549
- * This can be used with the x402 library or other signing operations.
16550
- */
16551
- getLocalAccount() {
16552
- return this.account;
16553
- }
16554
- /**
16555
- * Get sources for this account
16556
- */
16557
- async getSources() {
16558
- return [{
16559
- address: this.account.address,
16560
- chain: 'base',
16561
- walletType: 'eoa'
16562
- }];
16563
- }
16564
- }
16565
-
16566
16215
  function toBasicAuth(token) {
16567
16216
  // Basic auth is base64("username:password"), password is blank
16568
16217
  const b64 = Buffer.from(`${token}:`).toString('base64');
@@ -16663,5 +16312,5 @@ class ATXPLocalAccount {
16663
16312
  }
16664
16313
  }
16665
16314
 
16666
- export { ATXPDestinationMaker, ATXPLocalAccount, BaseAccount, BasePaymentMaker, DEFAULT_CLIENT_CONFIG, InsufficientFundsError, OAuthAuthenticationRequiredError, OAuthClient, POLYGON_AMOY, POLYGON_MAINNET, PassthroughDestinationMaker, PaymentNetworkError, SolanaAccount, SolanaPaymentMaker, USDC_CONTRACT_ADDRESS_BASE, USDC_CONTRACT_ADDRESS_BASE_SEPOLIA, USDC_CONTRACT_ADDRESS_POLYGON_AMOY, USDC_CONTRACT_ADDRESS_POLYGON_MAINNET, USDC_CONTRACT_ADDRESS_WORLD_MAINNET, USDC_CONTRACT_ADDRESS_WORLD_SEPOLIA, ValidateTransferError, WORLD_CHAIN_MAINNET, WORLD_CHAIN_SEPOLIA, atxpClient, atxpFetch, buildClientConfig, buildStreamableTransport, getBaseUSDCAddress, getPolygonAmoyWithRPC, getPolygonByChainId, getPolygonMainnetWithRPC, getPolygonUSDCAddress, getWorldChainByChainId, getWorldChainMainnetWithRPC, getWorldChainSepoliaWithRPC, getWorldChainUSDCAddress };
16315
+ export { ATXPDestinationMaker, ATXPLocalAccount, DEFAULT_CLIENT_CONFIG, InsufficientFundsError, OAuthAuthenticationRequiredError, OAuthClient, POLYGON_AMOY, POLYGON_MAINNET, PassthroughDestinationMaker, PaymentNetworkError, USDC_CONTRACT_ADDRESS_POLYGON_AMOY, USDC_CONTRACT_ADDRESS_POLYGON_MAINNET, USDC_CONTRACT_ADDRESS_WORLD_MAINNET, USDC_CONTRACT_ADDRESS_WORLD_SEPOLIA, WORLD_CHAIN_MAINNET, WORLD_CHAIN_SEPOLIA, atxpClient, atxpFetch, buildClientConfig, buildStreamableTransport, getPolygonAmoyWithRPC, getPolygonByChainId, getPolygonMainnetWithRPC, getPolygonUSDCAddress, getWorldChainByChainId, getWorldChainMainnetWithRPC, getWorldChainSepoliaWithRPC, getWorldChainUSDCAddress };
16667
16316
  //# sourceMappingURL=index.js.map