@atxp/polygon 0.8.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.
Files changed (44) hide show
  1. package/README.md +497 -0
  2. package/dist/cache.d.ts +19 -0
  3. package/dist/cache.d.ts.map +1 -0
  4. package/dist/cache.js +11 -0
  5. package/dist/cache.js.map +1 -0
  6. package/dist/directWalletPaymentMaker.d.ts +35 -0
  7. package/dist/directWalletPaymentMaker.d.ts.map +1 -0
  8. package/dist/directWalletPaymentMaker.js +143 -0
  9. package/dist/directWalletPaymentMaker.js.map +1 -0
  10. package/dist/index.cjs +458 -0
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/index.d.ts +145 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +446 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/polygonBrowserAccount.d.ts +40 -0
  17. package/dist/polygonBrowserAccount.d.ts.map +1 -0
  18. package/dist/polygonBrowserAccount.js +70 -0
  19. package/dist/polygonBrowserAccount.js.map +1 -0
  20. package/dist/polygonServerAccount.d.ts +35 -0
  21. package/dist/polygonServerAccount.d.ts.map +1 -0
  22. package/dist/polygonServerAccount.js +78 -0
  23. package/dist/polygonServerAccount.js.map +1 -0
  24. package/dist/serverPaymentMaker.d.ts +29 -0
  25. package/dist/serverPaymentMaker.d.ts.map +1 -0
  26. package/dist/serverPaymentMaker.js +173 -0
  27. package/dist/serverPaymentMaker.js.map +1 -0
  28. package/dist/smartWalletHelpers.d.ts +18 -0
  29. package/dist/smartWalletHelpers.d.ts.map +1 -0
  30. package/dist/smartWalletHelpers.js +93 -0
  31. package/dist/smartWalletHelpers.js.map +1 -0
  32. package/dist/smartWalletPaymentMaker.d.ts +29 -0
  33. package/dist/smartWalletPaymentMaker.d.ts.map +1 -0
  34. package/dist/smartWalletPaymentMaker.js +172 -0
  35. package/dist/smartWalletPaymentMaker.js.map +1 -0
  36. package/dist/spendPermissionShim.d.ts +19 -0
  37. package/dist/spendPermissionShim.d.ts.map +1 -0
  38. package/dist/spendPermissionShim.js +129 -0
  39. package/dist/spendPermissionShim.js.map +1 -0
  40. package/dist/testHelpers.d.ts +17 -0
  41. package/dist/testHelpers.d.ts.map +1 -0
  42. package/dist/types.d.ts +11 -0
  43. package/dist/types.d.ts.map +1 -0
  44. package/package.json +57 -0
@@ -0,0 +1,145 @@
1
+ import { PaymentMaker, Logger, Currency, AccountId, Destination, PaymentIdentifier, Account, Source } from '@atxp/common';
2
+ export { ATXPAccount } from '@atxp/common';
3
+ import BigNumber$1 from 'bignumber.js';
4
+ import { WalletClient, PublicActions } from 'viem';
5
+
6
+ type MainWalletProvider = {
7
+ request: (params: {
8
+ method: string;
9
+ params?: any[];
10
+ }) => Promise<any>;
11
+ };
12
+ /**
13
+ * Browser-based payment maker using direct wallet signing.
14
+ * Each transaction requires user approval in their wallet.
15
+ * User pays gas fees in POL.
16
+ */
17
+ declare class DirectWalletPaymentMaker implements PaymentMaker {
18
+ private walletAddress;
19
+ private provider;
20
+ private logger;
21
+ private chainId;
22
+ private usdcAddress;
23
+ constructor(walletAddress: string, provider: MainWalletProvider, logger?: Logger, chainId?: number);
24
+ getSourceAddress(_params: {
25
+ amount: BigNumber$1;
26
+ currency: Currency;
27
+ receiver: string;
28
+ memo: string;
29
+ }): string;
30
+ generateJWT(payload: {
31
+ paymentRequestId: string;
32
+ codeChallenge: string;
33
+ accountId?: AccountId | null;
34
+ }): Promise<string>;
35
+ makePayment(destinations: Destination[], _memo: string, _paymentRequestId?: string): Promise<PaymentIdentifier | null>;
36
+ private waitForTransactionConfirmations;
37
+ }
38
+
39
+ /**
40
+ * EIP-1193 compliant Ethereum provider interface
41
+ * Used for browser wallet integrations
42
+ */
43
+ type Eip1193Provider = {
44
+ request: (params: {
45
+ method: string;
46
+ params?: unknown[];
47
+ }) => Promise<unknown>;
48
+ };
49
+
50
+ /**
51
+ * Polygon browser account implementation using Direct Wallet mode.
52
+ *
53
+ * Direct Wallet mode:
54
+ * - User signs each transaction with their wallet
55
+ * - User pays gas fees in POL
56
+ * - No smart wallet or gasless transactions
57
+ *
58
+ * Note: Smart Wallet mode is not supported on Polygon because Coinbase CDP
59
+ * does not provide Paymaster services for Polygon mainnet.
60
+ */
61
+ declare class PolygonBrowserAccount implements Account {
62
+ accountId: AccountId;
63
+ paymentMakers: PaymentMaker[];
64
+ private walletAddress;
65
+ private chainId;
66
+ static initialize(config: {
67
+ walletAddress: string;
68
+ provider: Eip1193Provider;
69
+ logger?: Logger;
70
+ chainId?: number;
71
+ useEphemeralWallet?: boolean;
72
+ allowance?: bigint;
73
+ periodInDays?: number;
74
+ cache?: unknown;
75
+ coinbaseCdpApiKey?: string;
76
+ }): Promise<PolygonBrowserAccount>;
77
+ constructor(walletAddress: string, provider: MainWalletProvider, logger: Logger, chainId?: number);
78
+ getSources(): Promise<Source[]>;
79
+ /**
80
+ * Clear cached data (no-op in Direct Wallet mode, kept for backward compatibility)
81
+ * @deprecated This method is a no-op in Direct Wallet mode
82
+ */
83
+ static clearAllCachedData(_userWalletAddress: string, _cache?: unknown): void;
84
+ }
85
+
86
+ /**
87
+ * Polygon account for server-side/CLI usage
88
+ *
89
+ * This account type works without browser providers and uses direct private key signing.
90
+ * It uses direct wallet signing (similar to BaseAccount) rather than ephemeral wallets
91
+ * and spend permissions.
92
+ *
93
+ * For browser-based applications with wallet providers, use PolygonBrowserAccount.initialize() instead.
94
+ *
95
+ * @example
96
+ * ```typescript
97
+ * // Server-side usage
98
+ * const account = new PolygonServerAccount(
99
+ * 'https://polygon-rpc.com',
100
+ * '0x_your_private_key',
101
+ * 137 // Polygon mainnet
102
+ * );
103
+ * ```
104
+ */
105
+ declare class PolygonServerAccount implements Account {
106
+ accountId: AccountId;
107
+ paymentMakers: PaymentMaker[];
108
+ private walletClient;
109
+ private account;
110
+ private chainId;
111
+ constructor(polygonRPCUrl: string, sourceSecretKey: string, chainId?: number);
112
+ private getChain;
113
+ /**
114
+ * Get sources for this account
115
+ */
116
+ getSources(): Promise<Source[]>;
117
+ }
118
+
119
+ type ExtendedWalletClient = WalletClient & PublicActions;
120
+ /**
121
+ * Server-side Polygon payment maker for CLI/backend usage
122
+ * Uses direct private key signing without browser providers.
123
+ * Similar to BasePaymentMaker but for Polygon network.
124
+ */
125
+ declare class ServerPaymentMaker implements PaymentMaker {
126
+ protected signingClient: ExtendedWalletClient;
127
+ protected logger: Logger;
128
+ protected chainId: number;
129
+ constructor(polygonRPCUrl: string, walletClient: WalletClient, chainId: number, logger?: Logger);
130
+ getSourceAddress(_params: {
131
+ amount: BigNumber;
132
+ currency: Currency;
133
+ receiver: string;
134
+ memo: string;
135
+ }): string;
136
+ generateJWT({ paymentRequestId, codeChallenge, accountId }: {
137
+ paymentRequestId: string;
138
+ codeChallenge: string;
139
+ accountId?: AccountId | null;
140
+ }): Promise<string>;
141
+ makePayment(destinations: Destination[], _memo: string, _paymentRequestId?: string): Promise<PaymentIdentifier | null>;
142
+ }
143
+
144
+ export { DirectWalletPaymentMaker, DirectWalletPaymentMaker as MainWalletPaymentMaker, PolygonBrowserAccount as PolygonAccount, PolygonBrowserAccount, PolygonServerAccount, ServerPaymentMaker, PolygonServerAccount as SimplePolygonAccount, ServerPaymentMaker as SimplePolygonPaymentMaker };
145
+ export type { Eip1193Provider, MainWalletProvider };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAGjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,wBAAwB,EAAE,KAAK,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAGlG,OAAO,EAAE,qBAAqB,IAAI,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACrF,OAAO,EAAE,oBAAoB,IAAI,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACzF,OAAO,EAAE,kBAAkB,IAAI,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAC1F,OAAO,EAAE,wBAAwB,IAAI,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAGnG,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAGlD,OAAO,EACL,WAAW,EACZ,MAAM,cAAc,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,446 @@
1
+ import { ConsoleLogger, buildES256KJWTMessage, completeES256KJWT, ChainEnum, WalletTypeEnum } from '@atxp/common';
2
+ export { ATXPAccount } from '@atxp/common';
3
+ import { encodeFunctionData, publicActions, createWalletClient, http } from 'viem';
4
+ import { getPolygonUSDCAddress } from '@atxp/client';
5
+ import { polygon, polygonAmoy } from 'viem/chains';
6
+ import { privateKeyToAccount } from 'viem/accounts';
7
+
8
+ const USDC_DECIMALS$1 = 6;
9
+ /**
10
+ * Browser-based payment maker using direct wallet signing.
11
+ * Each transaction requires user approval in their wallet.
12
+ * User pays gas fees in POL.
13
+ */
14
+ class DirectWalletPaymentMaker {
15
+ constructor(walletAddress, provider, logger, chainId = polygon.id) {
16
+ this.walletAddress = walletAddress;
17
+ this.provider = provider;
18
+ this.logger = logger || new ConsoleLogger();
19
+ this.chainId = chainId;
20
+ this.usdcAddress = getPolygonUSDCAddress(chainId);
21
+ }
22
+ getSourceAddress(_params) {
23
+ return this.walletAddress;
24
+ }
25
+ async generateJWT(payload) {
26
+ this.logger.info(`codeChallenge: ${payload.codeChallenge}`);
27
+ this.logger.info(`paymentRequestId: ${payload.paymentRequestId}`);
28
+ this.logger.info(`walletAddress: ${this.walletAddress}`);
29
+ // Step 1: Build the JWT message (header.payload) that needs to be signed
30
+ const { message } = buildES256KJWTMessage({
31
+ walletAddress: this.walletAddress,
32
+ codeChallenge: payload.codeChallenge,
33
+ paymentRequestId: payload.paymentRequestId,
34
+ accountId: payload.accountId,
35
+ });
36
+ this.logger.info(`Requesting signature for JWT message: ${message}`);
37
+ // Step 2: Request signature from the wallet using personal_sign
38
+ // The user will sign the JWT message (header.payload)
39
+ // This returns a 65-byte ECDSA signature (130 hex chars + 0x prefix)
40
+ const signature = await this.provider.request({
41
+ method: 'personal_sign',
42
+ params: [message, this.walletAddress]
43
+ });
44
+ this.logger.info(`Received signature: ${signature}`);
45
+ // Step 3: Complete the JWT by adding the signature
46
+ const jwtToken = completeES256KJWT({
47
+ message,
48
+ signature
49
+ });
50
+ this.logger.info(`Generated ES256K JWT: ${jwtToken}`);
51
+ return jwtToken;
52
+ }
53
+ async makePayment(destinations, _memo, _paymentRequestId) {
54
+ // Filter to polygon chain destinations
55
+ const polygonDestinations = destinations.filter(d => d.chain === 'polygon');
56
+ if (polygonDestinations.length === 0) {
57
+ this.logger.debug('MainWalletPaymentMaker: No polygon destinations found, cannot handle payment');
58
+ return null; // Cannot handle these destinations
59
+ }
60
+ // Pick first polygon destination
61
+ const dest = polygonDestinations[0];
62
+ const amount = dest.amount;
63
+ const currency = dest.currency;
64
+ const receiver = dest.address;
65
+ if (currency !== 'USDC') {
66
+ throw new Error('Only usdc currency is supported');
67
+ }
68
+ this.logger.info(`Making direct payment of ${amount} ${currency} to ${receiver} on Polygon`);
69
+ // Convert amount to USDC units (6 decimals)
70
+ const amountInUSDCUnits = BigInt(amount.multipliedBy(10 ** USDC_DECIMALS$1).toFixed(0));
71
+ // Encode the transfer function data
72
+ const transferData = encodeFunctionData({
73
+ abi: [{
74
+ name: 'transfer',
75
+ type: 'function',
76
+ inputs: [
77
+ { name: 'to', type: 'address' },
78
+ { name: 'amount', type: 'uint256' }
79
+ ],
80
+ outputs: [{ name: '', type: 'bool' }]
81
+ }],
82
+ functionName: 'transfer',
83
+ args: [receiver, amountInUSDCUnits]
84
+ });
85
+ // Send the transaction through the user's wallet
86
+ const txHash = await this.provider.request({
87
+ method: 'eth_sendTransaction',
88
+ params: [{
89
+ from: this.walletAddress,
90
+ to: this.usdcAddress,
91
+ data: transferData,
92
+ value: '0x0'
93
+ }]
94
+ });
95
+ this.logger.info(`Transaction submitted. TxHash: ${txHash}`);
96
+ // Wait for confirmations
97
+ const CONFIRMATIONS = 2;
98
+ await this.waitForTransactionConfirmations(txHash, CONFIRMATIONS);
99
+ // Return payment result with chain and currency
100
+ return {
101
+ transactionId: txHash,
102
+ chain: 'polygon',
103
+ currency: 'USDC'
104
+ };
105
+ }
106
+ async waitForTransactionConfirmations(txHash, confirmations) {
107
+ this.logger.info(`Waiting for ${confirmations} confirmations...`);
108
+ // Poll for transaction receipt
109
+ let receipt = null;
110
+ while (!receipt) {
111
+ try {
112
+ receipt = await this.provider.request({
113
+ method: 'eth_getTransactionReceipt',
114
+ params: [txHash]
115
+ });
116
+ if (!receipt) {
117
+ await new Promise(resolve => setTimeout(resolve, 1000));
118
+ }
119
+ }
120
+ catch (error) {
121
+ this.logger.warn(`Error getting receipt: ${error}`);
122
+ await new Promise(resolve => setTimeout(resolve, 1000));
123
+ }
124
+ }
125
+ // Check if transaction was successful
126
+ if (receipt.status === '0x0') {
127
+ throw new Error(`Transaction failed. TxHash: ${txHash}`);
128
+ }
129
+ // Wait for confirmations
130
+ const startBlock = parseInt(receipt.blockNumber, 16);
131
+ let currentBlock = startBlock;
132
+ while (currentBlock - startBlock < confirmations - 1) {
133
+ await new Promise(resolve => setTimeout(resolve, 1000));
134
+ const blockNumber = await this.provider.request({
135
+ method: 'eth_blockNumber',
136
+ params: []
137
+ });
138
+ currentBlock = parseInt(blockNumber, 16);
139
+ }
140
+ this.logger.info(`Transaction confirmed with ${confirmations} confirmations`);
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Polygon browser account implementation using Direct Wallet mode.
146
+ *
147
+ * Direct Wallet mode:
148
+ * - User signs each transaction with their wallet
149
+ * - User pays gas fees in POL
150
+ * - No smart wallet or gasless transactions
151
+ *
152
+ * Note: Smart Wallet mode is not supported on Polygon because Coinbase CDP
153
+ * does not provide Paymaster services for Polygon mainnet.
154
+ */
155
+ class PolygonBrowserAccount {
156
+ static async initialize(config) {
157
+ const logger = config.logger || new ConsoleLogger();
158
+ const chainId = config.chainId || polygon.id; // Default to Polygon mainnet
159
+ // Warn if deprecated smart wallet parameters are provided
160
+ if (config.useEphemeralWallet === true) {
161
+ logger.warn('Smart Wallet mode (useEphemeralWallet=true) is not supported on Polygon. Using Direct Wallet mode instead.');
162
+ }
163
+ if (config.allowance !== undefined || config.periodInDays !== undefined) {
164
+ logger.warn('allowance and periodInDays parameters are ignored in Direct Wallet mode.');
165
+ }
166
+ if (config.coinbaseCdpApiKey !== undefined) {
167
+ logger.warn('coinbaseCdpApiKey parameter is ignored in Direct Wallet mode.');
168
+ }
169
+ // Some wallets don't support wallet_connect, so
170
+ // will just continue if it fails
171
+ try {
172
+ await config.provider.request({ method: 'wallet_connect' });
173
+ }
174
+ catch (error) {
175
+ // Continue if wallet_connect is not supported
176
+ logger.warn(`wallet_connect not supported, continuing with initialization. ${error}`);
177
+ }
178
+ logger.info(`Initializing Polygon account in Direct Wallet mode for address: ${config.walletAddress}`);
179
+ return new PolygonBrowserAccount(config.walletAddress, config.provider, logger, chainId);
180
+ }
181
+ constructor(walletAddress, provider, logger, chainId = polygon.id) {
182
+ this.walletAddress = walletAddress;
183
+ this.chainId = chainId;
184
+ // Format accountId as network:address
185
+ this.accountId = `polygon:${walletAddress}`;
186
+ this.paymentMakers = [
187
+ new DirectWalletPaymentMaker(walletAddress, provider, logger, chainId)
188
+ ];
189
+ }
190
+ async getSources() {
191
+ // For Polygon, we support both mainnet (137) and Amoy testnet (80002)
192
+ const chain = ChainEnum.Polygon;
193
+ return [{
194
+ address: this.walletAddress,
195
+ chain,
196
+ walletType: WalletTypeEnum.EOA
197
+ }];
198
+ }
199
+ /**
200
+ * Clear cached data (no-op in Direct Wallet mode, kept for backward compatibility)
201
+ * @deprecated This method is a no-op in Direct Wallet mode
202
+ */
203
+ static clearAllCachedData(_userWalletAddress, _cache) {
204
+ // No-op: Direct Wallet mode doesn't cache any data
205
+ }
206
+ }
207
+
208
+ // Helper function to convert to base64url that works in both Node.js and browsers
209
+ function toBase64Url(data) {
210
+ // Convert string to base64
211
+ const base64 = typeof Buffer !== 'undefined'
212
+ ? Buffer.from(data).toString('base64')
213
+ : btoa(data);
214
+ // Convert base64 to base64url
215
+ return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
216
+ }
217
+ const USDC_DECIMALS = 6;
218
+ const ERC20_ABI = [
219
+ {
220
+ constant: false,
221
+ inputs: [
222
+ { name: "_to", type: "address" },
223
+ { name: "_value", type: "uint256" },
224
+ ],
225
+ name: "transfer",
226
+ outputs: [{ name: "", type: "bool" }],
227
+ type: "function",
228
+ },
229
+ {
230
+ "constant": true,
231
+ "inputs": [
232
+ {
233
+ "name": "_owner",
234
+ "type": "address"
235
+ }
236
+ ],
237
+ "name": "balanceOf",
238
+ "outputs": [
239
+ {
240
+ "name": "balance",
241
+ "type": "uint256"
242
+ }
243
+ ],
244
+ "payable": false,
245
+ "stateMutability": "view",
246
+ "type": "function"
247
+ }
248
+ ];
249
+ /**
250
+ * Server-side Polygon payment maker for CLI/backend usage
251
+ * Uses direct private key signing without browser providers.
252
+ * Similar to BasePaymentMaker but for Polygon network.
253
+ */
254
+ class ServerPaymentMaker {
255
+ constructor(polygonRPCUrl, walletClient, chainId, logger) {
256
+ if (!polygonRPCUrl) {
257
+ throw new Error('polygonRPCUrl was empty');
258
+ }
259
+ if (!walletClient) {
260
+ throw new Error('walletClient was empty');
261
+ }
262
+ if (!walletClient.account) {
263
+ throw new Error('walletClient.account was empty');
264
+ }
265
+ if (!chainId) {
266
+ throw new Error('chainId was empty');
267
+ }
268
+ this.signingClient = walletClient.extend(publicActions);
269
+ this.logger = logger ?? new ConsoleLogger();
270
+ this.chainId = chainId;
271
+ }
272
+ getSourceAddress(_params) {
273
+ return this.signingClient.account.address;
274
+ }
275
+ async generateJWT({ paymentRequestId, codeChallenge, accountId }) {
276
+ const headerObj = { alg: 'ES256K' };
277
+ const payloadObj = {
278
+ sub: this.signingClient.account.address,
279
+ iss: 'accounts.atxp.ai',
280
+ aud: 'https://auth.atxp.ai',
281
+ iat: Math.floor(Date.now() / 1000),
282
+ exp: Math.floor(Date.now() / 1000) + 60 * 60,
283
+ ...(codeChallenge ? { code_challenge: codeChallenge } : {}),
284
+ ...(paymentRequestId ? { payment_request_id: paymentRequestId } : {}),
285
+ ...(accountId ? { account_id: accountId } : {}),
286
+ };
287
+ const header = toBase64Url(JSON.stringify(headerObj));
288
+ const payload = toBase64Url(JSON.stringify(payloadObj));
289
+ const message = `${header}.${payload}`;
290
+ // Convert message to bytes
291
+ const messageBytes = typeof Buffer !== 'undefined'
292
+ ? Buffer.from(message, 'utf8')
293
+ : new TextEncoder().encode(message);
294
+ // Sign the message with raw bytes
295
+ const signResult = await this.signingClient.signMessage({
296
+ account: this.signingClient.account,
297
+ message: { raw: messageBytes },
298
+ });
299
+ // For ES256K, signature is typically 65 bytes (r,s,v)
300
+ // Server expects the hex signature string (with 0x prefix) to be base64url encoded
301
+ // This creates: base64url("0x6eb2565...") not base64url(rawBytes)
302
+ // Pass the hex string directly to toBase64Url which will UTF-8 encode and base64url it
303
+ const signature = toBase64Url(signResult);
304
+ const jwt = `${header}.${payload}.${signature}`;
305
+ this.logger.info(`Generated ES256K JWT: ${jwt}`);
306
+ return jwt;
307
+ }
308
+ async makePayment(destinations, _memo, _paymentRequestId) {
309
+ this.logger.info(`Making payment with ${destinations.length} destination(s)`);
310
+ // Filter to polygon chain destinations
311
+ const polygonDestinations = destinations.filter(d => d.chain === 'polygon');
312
+ if (polygonDestinations.length === 0) {
313
+ this.logger.debug('SimplePolygonPaymentMaker: No polygon destinations found, cannot handle payment');
314
+ return null; // Cannot handle these destinations
315
+ }
316
+ // Pick first polygon destination
317
+ const destination = polygonDestinations[0];
318
+ // Validate currency
319
+ if (destination.currency !== 'USDC') {
320
+ throw new Error(`Unsupported currency: ${destination.currency}. Only USDC is supported on Polygon.`);
321
+ }
322
+ // Get USDC contract address for this chain
323
+ const usdcAddress = getPolygonUSDCAddress(this.chainId);
324
+ // Convert amount to smallest unit (USDC has 6 decimals)
325
+ const amountInSmallestUnit = destination.amount.multipliedBy(10 ** USDC_DECIMALS);
326
+ this.logger.info(`Transferring ${destination.amount.toString()} USDC to ${destination.address}`);
327
+ this.logger.info(`Amount in smallest unit: ${amountInSmallestUnit.toString()}`);
328
+ try {
329
+ // Check balance first
330
+ const balance = await this.signingClient.readContract({
331
+ address: usdcAddress,
332
+ abi: ERC20_ABI,
333
+ functionName: 'balanceOf',
334
+ args: [this.signingClient.account.address],
335
+ });
336
+ this.logger.info(`Current USDC balance: ${balance.toString()}`);
337
+ if (balance < BigInt(amountInSmallestUnit.toFixed(0))) {
338
+ throw new Error(`Insufficient USDC balance. Have: ${balance.toString()}, Need: ${amountInSmallestUnit.toString()}`);
339
+ }
340
+ // Encode the transfer function call
341
+ const data = encodeFunctionData({
342
+ abi: ERC20_ABI,
343
+ functionName: 'transfer',
344
+ args: [destination.address, BigInt(amountInSmallestUnit.toFixed(0))],
345
+ });
346
+ // Send the transaction
347
+ const hash = await this.signingClient.sendTransaction({
348
+ account: this.signingClient.account,
349
+ to: usdcAddress,
350
+ data,
351
+ chain: this.signingClient.chain,
352
+ });
353
+ this.logger.info(`Transaction sent: ${hash}`);
354
+ // Wait for confirmation
355
+ const receipt = await this.signingClient.waitForTransactionReceipt({ hash });
356
+ if (receipt.status === 'success') {
357
+ this.logger.info(`Payment successful! Transaction: ${hash}`);
358
+ return {
359
+ transactionId: hash,
360
+ chain: 'polygon',
361
+ currency: 'USDC',
362
+ };
363
+ }
364
+ else {
365
+ throw new Error(`Transaction failed: ${hash}`);
366
+ }
367
+ }
368
+ catch (error) {
369
+ this.logger.error(`Payment failed: ${error}`);
370
+ throw error;
371
+ }
372
+ }
373
+ }
374
+
375
+ /**
376
+ * Polygon account for server-side/CLI usage
377
+ *
378
+ * This account type works without browser providers and uses direct private key signing.
379
+ * It uses direct wallet signing (similar to BaseAccount) rather than ephemeral wallets
380
+ * and spend permissions.
381
+ *
382
+ * For browser-based applications with wallet providers, use PolygonBrowserAccount.initialize() instead.
383
+ *
384
+ * @example
385
+ * ```typescript
386
+ * // Server-side usage
387
+ * const account = new PolygonServerAccount(
388
+ * 'https://polygon-rpc.com',
389
+ * '0x_your_private_key',
390
+ * 137 // Polygon mainnet
391
+ * );
392
+ * ```
393
+ */
394
+ class PolygonServerAccount {
395
+ constructor(polygonRPCUrl, sourceSecretKey, chainId = 137) {
396
+ if (!polygonRPCUrl) {
397
+ throw new Error('Polygon RPC URL is required');
398
+ }
399
+ if (!sourceSecretKey) {
400
+ throw new Error('Source secret key is required');
401
+ }
402
+ if (!chainId) {
403
+ throw new Error('Chain ID is required');
404
+ }
405
+ this.chainId = chainId;
406
+ this.account = privateKeyToAccount(sourceSecretKey);
407
+ // Determine network name for accountId
408
+ const networkName = chainId === 137 ? 'polygon' : 'polygon_amoy';
409
+ this.accountId = `${networkName}:${this.account.address}`;
410
+ // Get the appropriate chain configuration
411
+ const chain = this.getChain(chainId);
412
+ this.walletClient = createWalletClient({
413
+ account: this.account,
414
+ chain,
415
+ transport: http(polygonRPCUrl),
416
+ });
417
+ this.paymentMakers = [
418
+ new ServerPaymentMaker(polygonRPCUrl, this.walletClient, chainId)
419
+ ];
420
+ }
421
+ getChain(chainId) {
422
+ switch (chainId) {
423
+ case 137:
424
+ return polygon;
425
+ case 80002:
426
+ return polygonAmoy;
427
+ default:
428
+ throw new Error(`Unsupported Polygon chain ID: ${chainId}. Supported: 137 (mainnet), 80002 (Amoy testnet)`);
429
+ }
430
+ }
431
+ /**
432
+ * Get sources for this account
433
+ */
434
+ async getSources() {
435
+ // Determine chain enum value
436
+ const chain = this.chainId === 137 ? ChainEnum.Polygon : ChainEnum.PolygonAmoy;
437
+ return [{
438
+ address: this.account.address,
439
+ chain,
440
+ walletType: WalletTypeEnum.EOA
441
+ }];
442
+ }
443
+ }
444
+
445
+ export { DirectWalletPaymentMaker, DirectWalletPaymentMaker as MainWalletPaymentMaker, PolygonBrowserAccount as PolygonAccount, PolygonBrowserAccount, PolygonServerAccount, ServerPaymentMaker, PolygonServerAccount as SimplePolygonAccount, ServerPaymentMaker as SimplePolygonPaymentMaker };
446
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/directWalletPaymentMaker.ts","../src/polygonBrowserAccount.ts","../src/serverPaymentMaker.ts","../src/polygonServerAccount.ts"],"sourcesContent":[null,null,null,null],"names":["USDC_DECIMALS"],"mappings":";;;;;;;AAUA,MAAMA,eAAa,GAAG,CAAC;AASvB;;;;AAIG;MACU,wBAAwB,CAAA;IAKnC,WAAA,CACU,aAAqB,EACrB,QAA4B,EACpC,MAAe,EACf,OAAA,GAAkB,OAAO,CAAC,EAAE,EAAA;QAHpB,IAAA,CAAA,aAAa,GAAb,aAAa;QACb,IAAA,CAAA,QAAQ,GAAR,QAAQ;QAIhB,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,IAAI,aAAa,EAAE;AAC3C,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;AACtB,QAAA,IAAI,CAAC,WAAW,GAAG,qBAAqB,CAAC,OAAO,CAAC;IACnD;AAEA,IAAA,gBAAgB,CAAC,OAAgF,EAAA;QAC/F,OAAO,IAAI,CAAC,aAAa;IAC3B;IAEA,MAAM,WAAW,CAAC,OAIjB,EAAA;QACC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA,eAAA,EAAkB,OAAO,CAAC,aAAa,CAAA,CAAE,CAAC;QAC3D,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA,kBAAA,EAAqB,OAAO,CAAC,gBAAgB,CAAA,CAAE,CAAC;QACjE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA,eAAA,EAAkB,IAAI,CAAC,aAAa,CAAA,CAAE,CAAC;;AAGxD,QAAA,MAAM,EAAE,OAAO,EAAE,GAAG,qBAAqB,CAAC;YACxC,a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,KAAK,GAAG,IAAI,CAAC,OAAO,KAAK,GAAG,GAAG,SAAS,CAAC,OAAO,GAAG,SAAS,CAAC,WAAW;AAE9E,QAAA,OAAO,CAAC;AACN,gBAAA,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO;gBAC7B,KAAK;gBACL,UAAU,EAAE,cAAc,CAAC;AAC5B,aAAA,CAAC;IACJ;AACD;;;;"}
@@ -0,0 +1,40 @@
1
+ import type { Account, PaymentMaker, AccountId, Source } from '@atxp/common';
2
+ import { type MainWalletProvider } from './directWalletPaymentMaker.js';
3
+ import { Eip1193Provider } from './types.js';
4
+ import { Logger } from '@atxp/common';
5
+ /**
6
+ * Polygon browser account implementation using Direct Wallet mode.
7
+ *
8
+ * Direct Wallet mode:
9
+ * - User signs each transaction with their wallet
10
+ * - User pays gas fees in POL
11
+ * - No smart wallet or gasless transactions
12
+ *
13
+ * Note: Smart Wallet mode is not supported on Polygon because Coinbase CDP
14
+ * does not provide Paymaster services for Polygon mainnet.
15
+ */
16
+ export declare class PolygonBrowserAccount implements Account {
17
+ accountId: AccountId;
18
+ paymentMakers: PaymentMaker[];
19
+ private walletAddress;
20
+ private chainId;
21
+ static initialize(config: {
22
+ walletAddress: string;
23
+ provider: Eip1193Provider;
24
+ logger?: Logger;
25
+ chainId?: number;
26
+ useEphemeralWallet?: boolean;
27
+ allowance?: bigint;
28
+ periodInDays?: number;
29
+ cache?: unknown;
30
+ coinbaseCdpApiKey?: string;
31
+ }): Promise<PolygonBrowserAccount>;
32
+ constructor(walletAddress: string, provider: MainWalletProvider, logger: Logger, chainId?: number);
33
+ getSources(): Promise<Source[]>;
34
+ /**
35
+ * Clear cached data (no-op in Direct Wallet mode, kept for backward compatibility)
36
+ * @deprecated This method is a no-op in Direct Wallet mode
37
+ */
38
+ static clearAllCachedData(_userWalletAddress: string, _cache?: unknown): void;
39
+ }
40
+ //# sourceMappingURL=polygonBrowserAccount.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"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