@atxp/client 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Account, Network, DestinationMaker, AuthorizationServerUrl, AccountId, Currency, OAuthDb, FetchLike, Logger, OAuthResourceClient, ClientCredentials, PKCEValues, AccessToken, PaymentMaker, Destination, PaymentIdentifier, Source, PaymentRequestOption } from '@atxp/common';
2
- export { Account, PaymentMaker } from '@atxp/common';
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';
@@ -175,23 +175,6 @@ declare class SolanaAccount implements Account {
175
175
  getSources(): Promise<Source[]>;
176
176
  }
177
177
 
178
- declare class ATXPAccount implements Account {
179
- accountId: AccountId;
180
- paymentMakers: PaymentMaker[];
181
- origin: string;
182
- token: string;
183
- fetchFn: FetchLike;
184
- private unqualifiedAccountId;
185
- constructor(connectionString: string, opts?: {
186
- fetchFn?: FetchLike;
187
- });
188
- getSigner(): Promise<LocalAccount>;
189
- /**
190
- * Get sources for this account by calling the accounts service
191
- */
192
- getSources(): Promise<Source[]>;
193
- }
194
-
195
178
  declare const USDC_CONTRACT_ADDRESS_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
196
179
  declare const USDC_CONTRACT_ADDRESS_BASE_SEPOLIA = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
197
180
  /**
@@ -280,22 +263,29 @@ type PolygonChain = {
280
263
  readonly testnet?: boolean;
281
264
  };
282
265
  declare const USDC_CONTRACT_ADDRESS_POLYGON_MAINNET = "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359";
266
+ declare const USDC_CONTRACT_ADDRESS_POLYGON_AMOY = "0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582";
283
267
  declare const POLYGON_MAINNET: PolygonChain;
268
+ declare const POLYGON_AMOY: PolygonChain;
284
269
  /**
285
270
  * Get Polygon Mainnet configuration with custom RPC URL (e.g., with API key)
286
271
  * @param rpcUrl - Custom RPC URL, e.g., 'https://polygon-mainnet.g.alchemy.com/v2/YOUR_API_KEY'
287
272
  */
288
273
  declare const getPolygonMainnetWithRPC: (rpcUrl: string) => PolygonChain;
274
+ /**
275
+ * Get Polygon Amoy Testnet configuration with custom RPC URL (e.g., with API key)
276
+ * @param rpcUrl - Custom RPC URL, e.g., 'https://polygon-amoy.g.alchemy.com/v2/YOUR_API_KEY'
277
+ */
278
+ declare const getPolygonAmoyWithRPC: (rpcUrl: string) => PolygonChain;
289
279
  /**
290
280
  * Get Polygon Chain configuration by chain ID
291
- * @param chainId - Chain ID (137 for mainnet)
281
+ * @param chainId - Chain ID (137 for mainnet, 80002 for Amoy testnet)
292
282
  * @returns Polygon Chain configuration
293
283
  * @throws Error if chain ID is not supported
294
284
  */
295
285
  declare const getPolygonByChainId: (chainId: number) => PolygonChain;
296
286
  /**
297
287
  * Get USDC contract address for Polygon by chain ID
298
- * @param chainId - Chain ID (137 for mainnet)
288
+ * @param chainId - Chain ID (137 for mainnet, 80002 for Amoy testnet)
299
289
  * @returns USDC contract address
300
290
  * @throws Error if chain ID is not supported
301
291
  */
@@ -308,10 +298,10 @@ declare class BaseAccount implements Account {
308
298
  private account;
309
299
  constructor(baseRPCUrl: string, sourceSecretKey: string);
310
300
  /**
311
- * Get a signer that can be used with the x402 library
312
- * This is only available for EVM-based accounts
301
+ * Get the LocalAccount (signer) for this account.
302
+ * This can be used with the x402 library or other signing operations.
313
303
  */
314
- getSigner(): LocalAccount;
304
+ getLocalAccount(): LocalAccount;
315
305
  /**
316
306
  * Get sources for this account
317
307
  */
@@ -385,5 +375,5 @@ declare class PassthroughDestinationMaker implements DestinationMaker {
385
375
  makeDestinations(option: PaymentRequestOption, _logger: Logger, _paymentRequestId: string, _sources: Source[]): Promise<Destination[]>;
386
376
  }
387
377
 
388
- export { ATXPAccount, ATXPDestinationMaker, ATXPLocalAccount, BaseAccount, BasePaymentMaker, DEFAULT_CLIENT_CONFIG, InsufficientFundsError, OAuthAuthenticationRequiredError, OAuthClient, POLYGON_MAINNET, PassthroughDestinationMaker, PaymentNetworkError, SolanaAccount, SolanaPaymentMaker, USDC_CONTRACT_ADDRESS_BASE, USDC_CONTRACT_ADDRESS_BASE_SEPOLIA, 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, getPolygonByChainId, getPolygonMainnetWithRPC, getPolygonUSDCAddress, getWorldChainByChainId, getWorldChainMainnetWithRPC, getWorldChainSepoliaWithRPC, getWorldChainUSDCAddress };
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 };
389
379
  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,kBAAkB,CAAC;AAE1B,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,eAAe,EACf,wBAAwB,EACxB,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,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"}
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
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, 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, generateJWT } from '@atxp/common';
2
+ export { ATXPAccount } from '@atxp/common';
2
3
  import * as oauth from 'oauth4webapi';
3
4
  import BigNumber$1, { BigNumber } from 'bignumber.js';
4
5
  import { PublicKey, ComputeBudgetProgram, sendAndConfirmTransaction, Connection, Keypair } from '@solana/web3.js';
@@ -15970,6 +15971,9 @@ function createDestinationMakers(config) {
15970
15971
  case NetworkEnum.WorldSepolia:
15971
15972
  makers.set(network, new PassthroughDestinationMaker(network));
15972
15973
  break;
15974
+ case NetworkEnum.PolygonAmoy:
15975
+ makers.set(network, new PassthroughDestinationMaker(network));
15976
+ break;
15973
15977
  case NetworkEnum.ATXP:
15974
15978
  makers.set(network, new ATXPDestinationMaker(atxpAccountsServer, fetchFn));
15975
15979
  break;
@@ -15981,263 +15985,6 @@ function createDestinationMakers(config) {
15981
15985
  return makers;
15982
15986
  }
15983
15987
 
15984
- function toBasicAuth$1(token) {
15985
- // Basic auth is base64("username:password"), password is blank
15986
- const b64 = Buffer.from(`${token}:`).toString('base64');
15987
- return `Basic ${b64}`;
15988
- }
15989
- /**
15990
- * ATXP implementation of viem's LocalAccount interface.
15991
- * Delegates signing operations to the accounts-x402 API.
15992
- * Includes properties needed by x402 library for wallet client compatibility.
15993
- */
15994
- class ATXPLocalAccount {
15995
- constructor(address, origin, token, fetchFn = fetch) {
15996
- this.address = address;
15997
- this.origin = origin;
15998
- this.token = token;
15999
- this.fetchFn = fetchFn;
16000
- this.type = 'local';
16001
- /**
16002
- * Get public key - required by LocalAccount interface
16003
- */
16004
- this.publicKey = '0x0000000000000000000000000000000000000000000000000000000000000000';
16005
- /**
16006
- * Source - required by LocalAccount interface (set to 'custom')
16007
- */
16008
- this.source = 'custom';
16009
- // x402 library expects these properties for wallet client compatibility
16010
- this.account = this; // Self-reference for x402's isSignerWallet check
16011
- this.chain = { id: 8453 }; // Base mainnet - could make this configurable
16012
- this.transport = {}; // Empty transport object for x402 compatibility
16013
- }
16014
- /**
16015
- * Fetch the wallet address from the /address endpoint
16016
- */
16017
- static async create(origin, token, fetchFn = fetch) {
16018
- // The /address endpoint uses Basic auth like other authenticated endpoints
16019
- // For X402, we need the Ethereum/Base address with USDC currency
16020
- const url = new URL(`${origin}/address`);
16021
- url.searchParams.set('network', 'base'); // X402 operates on Base
16022
- url.searchParams.set('currency', 'USDC'); // Always USDC for X402
16023
- const response = await fetchFn(url.toString(), {
16024
- method: 'GET',
16025
- headers: {
16026
- 'Authorization': toBasicAuth$1(token)
16027
- }
16028
- });
16029
- if (!response.ok) {
16030
- const errorText = await response.text();
16031
- throw new Error(`Failed to fetch destination address: ${response.status} ${response.statusText} ${errorText}`);
16032
- }
16033
- const data = await response.json();
16034
- const address = data.address;
16035
- if (!address) {
16036
- throw new Error('Address endpoint did not return an address');
16037
- }
16038
- // Check that the account is an Ethereum/Base account (required for X402/EVM operations)
16039
- const network = data.network;
16040
- if (!network) {
16041
- throw new Error('Address endpoint did not return a network');
16042
- }
16043
- if (network !== 'ethereum' && network !== 'base') {
16044
- throw new Error(`ATXPLocalAccount requires an Ethereum/Base account, but got ${network} account`);
16045
- }
16046
- return new ATXPLocalAccount(address, origin, token, fetchFn);
16047
- }
16048
- /**
16049
- * Sign a typed data structure using EIP-712
16050
- * This is what x402 library will call for EIP-3009 authorization
16051
- */
16052
- async signTypedData(typedData) {
16053
- const response = await this.fetchFn(`${this.origin}/sign-typed-data`, {
16054
- method: 'POST',
16055
- headers: {
16056
- 'Authorization': toBasicAuth$1(this.token),
16057
- 'Content-Type': 'application/json',
16058
- },
16059
- body: JSON.stringify({
16060
- typedData
16061
- })
16062
- });
16063
- if (!response.ok) {
16064
- const errorText = await response.text();
16065
- throw new Error(`Failed to sign typed data: ${response.status} ${response.statusText} ${errorText}`);
16066
- }
16067
- const result = await response.json();
16068
- return result.signature;
16069
- }
16070
- /**
16071
- * Sign a message - required by LocalAccount interface but not used for X402
16072
- */
16073
- async signMessage(_) {
16074
- throw new Error('Message signing not implemented for ATXP local account');
16075
- }
16076
- /**
16077
- * Sign a transaction - required by LocalAccount interface but not used for X402
16078
- */
16079
- async signTransaction(_transaction, _args) {
16080
- throw new Error('Transaction signing not implemented for ATXP local account');
16081
- }
16082
- }
16083
-
16084
- function toBasicAuth(token) {
16085
- // Basic auth is base64("username:password"), password is blank
16086
- const b64 = Buffer.from(`${token}:`).toString('base64');
16087
- return `Basic ${b64}`;
16088
- }
16089
- function parseConnectionString(connectionString) {
16090
- const url = new URL(connectionString);
16091
- const origin = url.origin;
16092
- const token = url.searchParams.get('connection_token') || '';
16093
- const accountId = url.searchParams.get('account_id');
16094
- if (!token) {
16095
- throw new Error('ATXPAccount: connection string missing connection token');
16096
- }
16097
- if (!accountId) {
16098
- throw new Error('ATXPAccount: connection string missing account id');
16099
- }
16100
- return { origin, token, accountId };
16101
- }
16102
- class ATXPHttpPaymentMaker {
16103
- constructor(origin, token, fetchFn = fetch) {
16104
- this.origin = origin;
16105
- this.token = token;
16106
- this.fetchFn = fetchFn;
16107
- }
16108
- async getSourceAddress(params) {
16109
- // Call the /address_for_payment endpoint to get the source address for this account
16110
- const response = await this.fetchFn(`${this.origin}/address_for_payment`, {
16111
- method: 'POST',
16112
- headers: {
16113
- 'Authorization': toBasicAuth(this.token),
16114
- 'Content-Type': 'application/json',
16115
- },
16116
- body: JSON.stringify({
16117
- amount: params.amount.toString(),
16118
- currency: params.currency,
16119
- receiver: params.receiver,
16120
- memo: params.memo,
16121
- }),
16122
- });
16123
- if (!response.ok) {
16124
- const text = await response.text();
16125
- throw new Error(`ATXPAccount: /address_for_payment failed: ${response.status} ${response.statusText} ${text}`);
16126
- }
16127
- const json = await response.json();
16128
- if (!json?.sourceAddress) {
16129
- throw new Error('ATXPAccount: /address_for_payment did not return sourceAddress');
16130
- }
16131
- return json.sourceAddress;
16132
- }
16133
- async makePayment(destinations, memo, paymentRequestId) {
16134
- // Make a payment via the /pay endpoint with multiple destinations
16135
- const response = await this.fetchFn(`${this.origin}/pay`, {
16136
- method: 'POST',
16137
- headers: {
16138
- 'Authorization': toBasicAuth(this.token),
16139
- 'Content-Type': 'application/json',
16140
- },
16141
- body: JSON.stringify({
16142
- destinations: destinations.map(d => ({
16143
- chain: d.chain,
16144
- address: d.address,
16145
- amount: d.amount.toString(),
16146
- currency: d.currency
16147
- })),
16148
- memo,
16149
- ...(paymentRequestId && { paymentRequestId })
16150
- }),
16151
- });
16152
- if (!response.ok) {
16153
- const text = await response.text();
16154
- throw new Error(`ATXPAccount: /pay failed: ${response.status} ${response.statusText} ${text}`);
16155
- }
16156
- const json = await response.json();
16157
- const transactionId = json.transactionId;
16158
- if (!transactionId) {
16159
- throw new Error('ATXPAccount: /pay did not return transactionId or txHash');
16160
- }
16161
- if (!json?.chain) {
16162
- throw new Error('ATXPAccount: /pay did not return chain');
16163
- }
16164
- if (!json?.currency) {
16165
- throw new Error('ATXPAccount: /pay did not return currency');
16166
- }
16167
- return {
16168
- transactionId,
16169
- ...(json.transactionSubId ? { transactionSubId: json.transactionSubId } : {}),
16170
- chain: json.chain,
16171
- currency: json.currency
16172
- };
16173
- }
16174
- async generateJWT(params) {
16175
- const response = await this.fetchFn(`${this.origin}/sign`, {
16176
- method: 'POST',
16177
- headers: {
16178
- 'Authorization': toBasicAuth(this.token),
16179
- 'Content-Type': 'application/json',
16180
- },
16181
- body: JSON.stringify({
16182
- paymentRequestId: params.paymentRequestId,
16183
- codeChallenge: params.codeChallenge,
16184
- ...(params.accountId ? { accountId: params.accountId } : {}),
16185
- }),
16186
- });
16187
- if (!response.ok) {
16188
- const text = await response.text();
16189
- throw new Error(`ATXPAccount: /sign failed: ${response.status} ${response.statusText} ${text}`);
16190
- }
16191
- const json = await response.json();
16192
- if (!json?.jwt) {
16193
- throw new Error('ATXPAccount: /sign did not return jwt');
16194
- }
16195
- return json.jwt;
16196
- }
16197
- }
16198
- class ATXPAccount {
16199
- constructor(connectionString, opts) {
16200
- const { origin, token, accountId } = parseConnectionString(connectionString);
16201
- const fetchFn = opts?.fetchFn ?? fetch;
16202
- // Store for use in X402 payment creation
16203
- this.origin = origin;
16204
- this.token = token;
16205
- this.fetchFn = fetchFn;
16206
- // Format accountId as network:address
16207
- // Connection string provides just the atxp_acct_xxx part (no prefix for UI)
16208
- this.unqualifiedAccountId = accountId;
16209
- this.accountId = `atxp:${accountId}`;
16210
- this.paymentMakers = [
16211
- new ATXPHttpPaymentMaker(origin, token, fetchFn)
16212
- ];
16213
- }
16214
- async getSigner() {
16215
- return ATXPLocalAccount.create(this.origin, this.token, this.fetchFn);
16216
- }
16217
- /**
16218
- * Get sources for this account by calling the accounts service
16219
- */
16220
- async getSources() {
16221
- // Use the unqualified account ID (without atxp: prefix) for the API call
16222
- const response = await this.fetchFn(`${this.origin}/account/${this.unqualifiedAccountId}/sources`, {
16223
- method: 'GET',
16224
- headers: {
16225
- 'Accept': 'application/json',
16226
- }
16227
- });
16228
- if (!response.ok) {
16229
- const text = await response.text();
16230
- throw new Error(`ATXPAccount: /account/${this.unqualifiedAccountId}/sources failed: ${response.status} ${response.statusText} ${text}`);
16231
- }
16232
- const json = await response.json();
16233
- // The accounts service returns the sources array directly, not wrapped in an object
16234
- if (!Array.isArray(json)) {
16235
- throw new Error(`ATXPAccount: /account/${this.unqualifiedAccountId}/sources did not return sources array`);
16236
- }
16237
- return json;
16238
- }
16239
- }
16240
-
16241
15988
  // Detect if we're in a browser environment and bind fetch appropriately
16242
15989
  const getFetch = () => {
16243
15990
  if (typeof window !== 'undefined' && typeof window.fetch === 'function') {
@@ -16695,11 +16442,13 @@ const getWorldChainUSDCAddress = (chainId) => {
16695
16442
  };
16696
16443
 
16697
16444
  const USDC_CONTRACT_ADDRESS_POLYGON_MAINNET = "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"; // Native USDC on Polygon mainnet
16445
+ const USDC_CONTRACT_ADDRESS_POLYGON_AMOY = "0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582"; // USDC on Polygon Amoy testnet
16698
16446
  // Polygon Mainnet (Chain ID: 137)
16447
+ // Note: Native currency upgraded from MATIC to POL on September 4, 2024
16699
16448
  const POLYGON_MAINNET = {
16700
16449
  id: 137,
16701
16450
  name: 'Polygon',
16702
- nativeCurrency: { name: 'MATIC', symbol: 'MATIC', decimals: 18 },
16451
+ nativeCurrency: { name: 'POL', symbol: 'POL', decimals: 18 },
16703
16452
  rpcUrls: {
16704
16453
  default: { http: ['https://polygon-rpc.com'] }
16705
16454
  },
@@ -16707,6 +16456,20 @@ const POLYGON_MAINNET = {
16707
16456
  default: { name: 'PolygonScan', url: 'https://polygonscan.com' }
16708
16457
  }
16709
16458
  };
16459
+ // Polygon Amoy Testnet (Chain ID: 80002)
16460
+ // Note: Amoy testnet also uses POL as native currency (following mainnet upgrade)
16461
+ const POLYGON_AMOY = {
16462
+ id: 80002,
16463
+ name: 'Polygon Amoy',
16464
+ nativeCurrency: { name: 'POL', symbol: 'POL', decimals: 18 },
16465
+ rpcUrls: {
16466
+ default: { http: ['https://rpc-amoy.polygon.technology'] }
16467
+ },
16468
+ blockExplorers: {
16469
+ default: { name: 'PolygonScan Amoy', url: 'https://amoy.polygonscan.com' }
16470
+ },
16471
+ testnet: true
16472
+ };
16710
16473
  /**
16711
16474
  * Get Polygon Mainnet configuration with custom RPC URL (e.g., with API key)
16712
16475
  * @param rpcUrl - Custom RPC URL, e.g., 'https://polygon-mainnet.g.alchemy.com/v2/YOUR_API_KEY'
@@ -16717,9 +16480,19 @@ const getPolygonMainnetWithRPC = (rpcUrl) => ({
16717
16480
  default: { http: [rpcUrl] }
16718
16481
  }
16719
16482
  });
16483
+ /**
16484
+ * Get Polygon Amoy Testnet configuration with custom RPC URL (e.g., with API key)
16485
+ * @param rpcUrl - Custom RPC URL, e.g., 'https://polygon-amoy.g.alchemy.com/v2/YOUR_API_KEY'
16486
+ */
16487
+ const getPolygonAmoyWithRPC = (rpcUrl) => ({
16488
+ ...POLYGON_AMOY,
16489
+ rpcUrls: {
16490
+ default: { http: [rpcUrl] }
16491
+ }
16492
+ });
16720
16493
  /**
16721
16494
  * Get Polygon Chain configuration by chain ID
16722
- * @param chainId - Chain ID (137 for mainnet)
16495
+ * @param chainId - Chain ID (137 for mainnet, 80002 for Amoy testnet)
16723
16496
  * @returns Polygon Chain configuration
16724
16497
  * @throws Error if chain ID is not supported
16725
16498
  */
@@ -16727,13 +16500,15 @@ const getPolygonByChainId = (chainId) => {
16727
16500
  switch (chainId) {
16728
16501
  case 137:
16729
16502
  return POLYGON_MAINNET;
16503
+ case 80002:
16504
+ return POLYGON_AMOY;
16730
16505
  default:
16731
- throw new Error(`Unsupported Polygon Chain ID: ${chainId}. Supported chains: 137 (mainnet)`);
16506
+ throw new Error(`Unsupported Polygon Chain ID: ${chainId}. Supported chains: 137 (mainnet), 80002 (Amoy testnet)`);
16732
16507
  }
16733
16508
  };
16734
16509
  /**
16735
16510
  * Get USDC contract address for Polygon by chain ID
16736
- * @param chainId - Chain ID (137 for mainnet)
16511
+ * @param chainId - Chain ID (137 for mainnet, 80002 for Amoy testnet)
16737
16512
  * @returns USDC contract address
16738
16513
  * @throws Error if chain ID is not supported
16739
16514
  */
@@ -16741,8 +16516,10 @@ const getPolygonUSDCAddress = (chainId) => {
16741
16516
  switch (chainId) {
16742
16517
  case 137:
16743
16518
  return USDC_CONTRACT_ADDRESS_POLYGON_MAINNET;
16519
+ case 80002:
16520
+ return USDC_CONTRACT_ADDRESS_POLYGON_AMOY;
16744
16521
  default:
16745
- throw new Error(`Unsupported Polygon Chain ID: ${chainId}. Supported chains: 137 (mainnet)`);
16522
+ throw new Error(`Unsupported Polygon Chain ID: ${chainId}. Supported chains: 137 (mainnet), 80002 (Amoy testnet)`);
16746
16523
  }
16747
16524
  };
16748
16525
 
@@ -16767,11 +16544,10 @@ class BaseAccount {
16767
16544
  ];
16768
16545
  }
16769
16546
  /**
16770
- * Get a signer that can be used with the x402 library
16771
- * This is only available for EVM-based accounts
16547
+ * Get the LocalAccount (signer) for this account.
16548
+ * This can be used with the x402 library or other signing operations.
16772
16549
  */
16773
- getSigner() {
16774
- // Return the viem account directly - it implements LocalAccount interface
16550
+ getLocalAccount() {
16775
16551
  return this.account;
16776
16552
  }
16777
16553
  /**
@@ -16786,5 +16562,105 @@ class BaseAccount {
16786
16562
  }
16787
16563
  }
16788
16564
 
16789
- export { ATXPAccount, ATXPDestinationMaker, ATXPLocalAccount, BaseAccount, BasePaymentMaker, DEFAULT_CLIENT_CONFIG, InsufficientFundsError, OAuthAuthenticationRequiredError, OAuthClient, POLYGON_MAINNET, PassthroughDestinationMaker, PaymentNetworkError, SolanaAccount, SolanaPaymentMaker, USDC_CONTRACT_ADDRESS_BASE, USDC_CONTRACT_ADDRESS_BASE_SEPOLIA, 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, getPolygonByChainId, getPolygonMainnetWithRPC, getPolygonUSDCAddress, getWorldChainByChainId, getWorldChainMainnetWithRPC, getWorldChainSepoliaWithRPC, getWorldChainUSDCAddress };
16565
+ function toBasicAuth(token) {
16566
+ // Basic auth is base64("username:password"), password is blank
16567
+ const b64 = Buffer.from(`${token}:`).toString('base64');
16568
+ return `Basic ${b64}`;
16569
+ }
16570
+ /**
16571
+ * ATXP implementation of viem's LocalAccount interface.
16572
+ * Delegates signing operations to the accounts-x402 API.
16573
+ * Includes properties needed by x402 library for wallet client compatibility.
16574
+ */
16575
+ class ATXPLocalAccount {
16576
+ constructor(address, origin, token, fetchFn = fetch) {
16577
+ this.address = address;
16578
+ this.origin = origin;
16579
+ this.token = token;
16580
+ this.fetchFn = fetchFn;
16581
+ this.type = 'local';
16582
+ /**
16583
+ * Get public key - required by LocalAccount interface
16584
+ */
16585
+ this.publicKey = '0x0000000000000000000000000000000000000000000000000000000000000000';
16586
+ /**
16587
+ * Source - required by LocalAccount interface (set to 'custom')
16588
+ */
16589
+ this.source = 'custom';
16590
+ // x402 library expects these properties for wallet client compatibility
16591
+ this.account = this; // Self-reference for x402's isSignerWallet check
16592
+ this.chain = { id: 8453 }; // Base mainnet - could make this configurable
16593
+ this.transport = {}; // Empty transport object for x402 compatibility
16594
+ }
16595
+ /**
16596
+ * Fetch the wallet address from the /address endpoint
16597
+ */
16598
+ static async create(origin, token, fetchFn = fetch) {
16599
+ // The /address endpoint uses Basic auth like other authenticated endpoints
16600
+ // For X402, we need the Ethereum/Base address with USDC currency
16601
+ const url = new URL(`${origin}/address`);
16602
+ url.searchParams.set('network', 'base'); // X402 operates on Base
16603
+ url.searchParams.set('currency', 'USDC'); // Always USDC for X402
16604
+ const response = await fetchFn(url.toString(), {
16605
+ method: 'GET',
16606
+ headers: {
16607
+ 'Authorization': toBasicAuth(token)
16608
+ }
16609
+ });
16610
+ if (!response.ok) {
16611
+ const errorText = await response.text();
16612
+ throw new Error(`Failed to fetch destination address: ${response.status} ${response.statusText} ${errorText}`);
16613
+ }
16614
+ const data = await response.json();
16615
+ const address = data.address;
16616
+ if (!address) {
16617
+ throw new Error('Address endpoint did not return an address');
16618
+ }
16619
+ // Check that the account is an Ethereum/Base account (required for X402/EVM operations)
16620
+ const network = data.network;
16621
+ if (!network) {
16622
+ throw new Error('Address endpoint did not return a network');
16623
+ }
16624
+ if (network !== 'ethereum' && network !== 'base') {
16625
+ throw new Error(`ATXPLocalAccount requires an Ethereum/Base account, but got ${network} account`);
16626
+ }
16627
+ return new ATXPLocalAccount(address, origin, token, fetchFn);
16628
+ }
16629
+ /**
16630
+ * Sign a typed data structure using EIP-712
16631
+ * This is what x402 library will call for EIP-3009 authorization
16632
+ */
16633
+ async signTypedData(typedData) {
16634
+ const response = await this.fetchFn(`${this.origin}/sign-typed-data`, {
16635
+ method: 'POST',
16636
+ headers: {
16637
+ 'Authorization': toBasicAuth(this.token),
16638
+ 'Content-Type': 'application/json',
16639
+ },
16640
+ body: JSON.stringify({
16641
+ typedData
16642
+ })
16643
+ });
16644
+ if (!response.ok) {
16645
+ const errorText = await response.text();
16646
+ throw new Error(`Failed to sign typed data: ${response.status} ${response.statusText} ${errorText}`);
16647
+ }
16648
+ const result = await response.json();
16649
+ return result.signature;
16650
+ }
16651
+ /**
16652
+ * Sign a message - required by LocalAccount interface but not used for X402
16653
+ */
16654
+ async signMessage(_) {
16655
+ throw new Error('Message signing not implemented for ATXP local account');
16656
+ }
16657
+ /**
16658
+ * Sign a transaction - required by LocalAccount interface but not used for X402
16659
+ */
16660
+ async signTransaction(_transaction, _args) {
16661
+ throw new Error('Transaction signing not implemented for ATXP local account');
16662
+ }
16663
+ }
16664
+
16665
+ 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 };
16790
16666
  //# sourceMappingURL=index.js.map