@atxp/base 0.2.21 → 0.3.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 (55) hide show
  1. package/dist/baseAppAccount.js +15 -4
  2. package/dist/baseAppAccount.js.map +1 -1
  3. package/dist/baseAppPaymentMaker.js +43 -50
  4. package/dist/baseAppPaymentMaker.js.map +1 -1
  5. package/dist/eip1271JwtHelper.js +83 -0
  6. package/dist/eip1271JwtHelper.js.map +1 -0
  7. package/dist/index.cjs +630 -0
  8. package/dist/index.cjs.map +1 -0
  9. package/dist/index.d.ts +157 -6
  10. package/dist/index.js +623 -5
  11. package/dist/index.js.map +1 -1
  12. package/dist/mainWalletPaymentMaker.js +26 -48
  13. package/dist/mainWalletPaymentMaker.js.map +1 -1
  14. package/dist/smartWalletHelpers.js +6 -3
  15. package/dist/smartWalletHelpers.js.map +1 -1
  16. package/dist/spendPermissionUtils.js +19 -0
  17. package/dist/spendPermissionUtils.js.map +1 -0
  18. package/dist/storage.js +6 -4
  19. package/dist/storage.js.map +1 -1
  20. package/package.json +22 -8
  21. package/dist/baseAppAccount.d.ts +0 -28
  22. package/dist/baseAppAccount.d.ts.map +0 -1
  23. package/dist/baseAppAccount.ephemeral.test.d.ts +0 -2
  24. package/dist/baseAppAccount.ephemeral.test.d.ts.map +0 -1
  25. package/dist/baseAppAccount.ephemeral.test.js +0 -420
  26. package/dist/baseAppAccount.ephemeral.test.js.map +0 -1
  27. package/dist/baseAppAccount.mainWallet.test.d.ts +0 -2
  28. package/dist/baseAppAccount.mainWallet.test.d.ts.map +0 -1
  29. package/dist/baseAppAccount.mainWallet.test.js +0 -259
  30. package/dist/baseAppAccount.mainWallet.test.js.map +0 -1
  31. package/dist/baseAppPaymentMaker.d.ts +0 -16
  32. package/dist/baseAppPaymentMaker.d.ts.map +0 -1
  33. package/dist/baseAppPaymentMaker.test.d.ts +0 -2
  34. package/dist/baseAppPaymentMaker.test.d.ts.map +0 -1
  35. package/dist/baseAppPaymentMaker.test.js +0 -107
  36. package/dist/baseAppPaymentMaker.test.js.map +0 -1
  37. package/dist/index.d.ts.map +0 -1
  38. package/dist/mainWalletPaymentMaker.d.ts +0 -22
  39. package/dist/mainWalletPaymentMaker.d.ts.map +0 -1
  40. package/dist/mainWalletPaymentMaker.test.d.ts +0 -2
  41. package/dist/mainWalletPaymentMaker.test.d.ts.map +0 -1
  42. package/dist/mainWalletPaymentMaker.test.js +0 -340
  43. package/dist/mainWalletPaymentMaker.test.js.map +0 -1
  44. package/dist/smartWalletHelpers.d.ts +0 -13
  45. package/dist/smartWalletHelpers.d.ts.map +0 -1
  46. package/dist/storage.d.ts +0 -51
  47. package/dist/storage.d.ts.map +0 -1
  48. package/dist/testHelpers.d.ts +0 -88
  49. package/dist/testHelpers.d.ts.map +0 -1
  50. package/dist/testHelpers.js +0 -202
  51. package/dist/testHelpers.js.map +0 -1
  52. package/dist/types.d.ts +0 -35
  53. package/dist/types.d.ts.map +0 -1
  54. package/dist/types.js +0 -3
  55. package/dist/types.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,630 @@
1
+ 'use strict';
2
+
3
+ var client = require('@atxp/client');
4
+ var common = require('@atxp/common');
5
+ var viem = require('viem');
6
+ var accounts = require('viem/accounts');
7
+ var chains = require('viem/chains');
8
+ var accountAbstraction = require('viem/account-abstraction');
9
+ var account = require('@base-org/account');
10
+
11
+ /**
12
+ * Loads the browser-only spend permission module.
13
+ * Throws an error if called in a server environment.
14
+ *
15
+ * Both BaseAppAccount and BaseAppPaymentMaker should only run in browser environments
16
+ * since they require wallet interaction and browser APIs.
17
+ */
18
+ async function getSpendPermissionModule() {
19
+ // Check if we're in a browser environment
20
+ if (typeof window === 'undefined') {
21
+ throw new Error('Spend permission operations require browser environment. ' +
22
+ 'BaseAppAccount and BaseAppPaymentMaker should only be used client-side in Next.js apps.');
23
+ }
24
+ // Use browser version since both classes require browser environment
25
+ return await import('@base-org/account/spend-permission/browser');
26
+ }
27
+
28
+ /**
29
+ * EIP-1271 JWT helper utilities for creating properly formatted JWTs
30
+ * from EIP-1271 auth data.
31
+ */
32
+ // Helper function to convert to base64url that works in both Node.js and browsers
33
+ function toBase64Url(data) {
34
+ // Convert string to base64
35
+ const base64 = typeof Buffer !== 'undefined'
36
+ ? Buffer.from(data).toString('base64')
37
+ : btoa(data);
38
+ // Convert base64 to base64url
39
+ return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
40
+ }
41
+ /**
42
+ * Convert EIP-1271 auth data to JWT format
43
+ * @param authData The EIP-1271 auth data (signature will be moved to JWT signature section)
44
+ * @returns JWT string in the format header.payload.signature
45
+ */
46
+ function createEIP1271JWT(authData) {
47
+ // Create JWT header
48
+ const header = {
49
+ alg: 'EIP1271',
50
+ typ: 'JWT'
51
+ };
52
+ // Create payload without signature (signature goes in JWT signature section)
53
+ const payload = {
54
+ sub: authData.walletAddress,
55
+ iss: 'accounts.atxp.ai',
56
+ aud: 'https://auth.atxp.ai',
57
+ iat: authData.timestamp,
58
+ exp: authData.timestamp + 3600, // 1 hour expiration
59
+ msg: authData.message,
60
+ ...(authData.code_challenge && { code_challenge: authData.code_challenge }),
61
+ ...(authData.payment_request_id && { payment_request_id: authData.payment_request_id })
62
+ };
63
+ // Encode header and payload
64
+ const encodedHeader = toBase64Url(JSON.stringify(header));
65
+ const encodedPayload = toBase64Url(JSON.stringify(payload));
66
+ // EIP-1271 signature goes in JWT signature section
67
+ const encodedSignature = toBase64Url(authData.signature);
68
+ // Return JWT format: header.payload.signature
69
+ return `${encodedHeader}.${encodedPayload}.${encodedSignature}`;
70
+ }
71
+ /**
72
+ * Create auth data structure from signing parameters
73
+ */
74
+ function createEIP1271AuthData({ walletAddress, message, signature, timestamp, nonce, codeChallenge, paymentRequestId }) {
75
+ return {
76
+ type: 'EIP1271_AUTH',
77
+ walletAddress,
78
+ message,
79
+ signature,
80
+ timestamp,
81
+ ...(nonce && { nonce }),
82
+ ...(codeChallenge && { code_challenge: codeChallenge }),
83
+ ...(paymentRequestId && { payment_request_id: paymentRequestId })
84
+ };
85
+ }
86
+ /**
87
+ * Construct the standardized message format for EIP-1271 signing
88
+ */
89
+ function constructEIP1271Message({ walletAddress, timestamp, nonce, codeChallenge, paymentRequestId }) {
90
+ const messageParts = [
91
+ `PayMCP Authorization Request`,
92
+ ``,
93
+ `Wallet: ${walletAddress}`,
94
+ `Timestamp: ${timestamp}`
95
+ ];
96
+ if (nonce !== undefined && nonce !== null) {
97
+ messageParts.push(`Nonce: ${nonce}`);
98
+ }
99
+ if (codeChallenge) {
100
+ messageParts.push(`Code Challenge: ${codeChallenge}`);
101
+ }
102
+ if (paymentRequestId) {
103
+ messageParts.push(`Payment Request ID: ${paymentRequestId}`);
104
+ }
105
+ messageParts.push('', '', 'Sign this message to prove you control this wallet.');
106
+ return messageParts.join('\n');
107
+ }
108
+
109
+ const USDC_DECIMALS$1 = 6;
110
+ // Minimal ERC20 ABI for transfer function
111
+ const ERC20_ABI = [
112
+ {
113
+ inputs: [
114
+ { name: 'to', type: 'address' },
115
+ { name: 'amount', type: 'uint256' }
116
+ ],
117
+ name: 'transfer',
118
+ outputs: [{ name: '', type: 'bool' }],
119
+ stateMutability: 'nonpayable',
120
+ type: 'function'
121
+ }
122
+ ];
123
+ async function waitForTransactionConfirmations(smartWallet, txHash, confirmations, logger) {
124
+ try {
125
+ const publicClient = smartWallet.client.account?.client;
126
+ if (publicClient && 'waitForTransactionReceipt' in publicClient) {
127
+ logger.info(`Waiting for ${confirmations} confirmations...`);
128
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
129
+ await publicClient.waitForTransactionReceipt({
130
+ hash: txHash,
131
+ confirmations: confirmations
132
+ });
133
+ logger.info(`Transaction confirmed with ${confirmations} confirmations`);
134
+ }
135
+ else {
136
+ logger.warn('Unable to wait for confirmations: client does not support waitForTransactionReceipt');
137
+ }
138
+ }
139
+ catch (error) {
140
+ logger.warn(`Could not wait for additional confirmations: ${error}`);
141
+ // Continue anyway - the transaction is already mined
142
+ }
143
+ }
144
+ class BaseAppPaymentMaker {
145
+ constructor(spendPermission, smartWallet, logger) {
146
+ if (!spendPermission) {
147
+ throw new Error('Spend permission is required');
148
+ }
149
+ if (!smartWallet) {
150
+ throw new Error('Smart wallet is required');
151
+ }
152
+ this.logger = logger ?? new common.ConsoleLogger();
153
+ this.spendPermission = spendPermission;
154
+ this.smartWallet = smartWallet;
155
+ }
156
+ async generateJWT({ paymentRequestId, codeChallenge }) {
157
+ // Generate EIP-1271 auth data for smart wallet authentication
158
+ const timestamp = Math.floor(Date.now() / 1000);
159
+ const message = constructEIP1271Message({
160
+ walletAddress: this.smartWallet.account.address,
161
+ timestamp,
162
+ codeChallenge,
163
+ paymentRequestId
164
+ });
165
+ // Sign the message - this will return an ABI-encoded signature from the smart wallet
166
+ const signature = await this.smartWallet.account.signMessage({
167
+ message: message
168
+ });
169
+ const authData = createEIP1271AuthData({
170
+ walletAddress: this.smartWallet.account.address,
171
+ message,
172
+ signature,
173
+ timestamp,
174
+ codeChallenge,
175
+ paymentRequestId
176
+ });
177
+ const jwtToken = createEIP1271JWT(authData);
178
+ this.logger.info(`codeChallenge: ${codeChallenge}`);
179
+ this.logger.info(`paymentRequestId: ${paymentRequestId}`);
180
+ this.logger.info(`walletAddress: ${this.smartWallet.account.address}`);
181
+ this.logger.info(`Generated EIP-1271 JWT: ${jwtToken}`);
182
+ return jwtToken;
183
+ }
184
+ async makePayment(amount, currency, receiver, memo) {
185
+ if (currency !== 'USDC') {
186
+ throw new Error('Only usdc currency is supported; received ' + currency);
187
+ }
188
+ this.logger.info(`Making spendPermission payment of ${amount} ${currency} to ${receiver} on Base with memo: ${memo}`);
189
+ // Convert amount to USDC units (6 decimals) as BigInt for spendPermission
190
+ const amountInUSDCUnits = BigInt(amount.multipliedBy(10 ** USDC_DECIMALS$1).toFixed(0));
191
+ // Dynamically import prepareSpendCallData based on environment
192
+ const { prepareSpendCallData } = await getSpendPermissionModule();
193
+ const spendCalls = await prepareSpendCallData(this.spendPermission, amountInUSDCUnits);
194
+ // Add a second call to transfer USDC from the smart wallet to the receiver
195
+ let transferCallData = viem.encodeFunctionData({
196
+ abi: ERC20_ABI,
197
+ functionName: "transfer",
198
+ args: [receiver, amountInUSDCUnits],
199
+ });
200
+ // Append memo to transfer call data if present
201
+ // This works because the EVM ignores extra calldata beyond what a function expects.
202
+ // The ERC20 transfer() function only reads the first 68 bytes (4-byte selector + 32-byte address + 32-byte amount).
203
+ // Any additional data appended after those 68 bytes is safely ignored by the USDC contract
204
+ // but remains accessible in the transaction data for payment verification.
205
+ // This is a well-established pattern used by OpenSea, Uniswap, and other major protocols.
206
+ if (memo && memo.trim()) {
207
+ const memoHex = Buffer.from(memo.trim(), 'utf8').toString('hex');
208
+ transferCallData = (transferCallData + memoHex);
209
+ this.logger.info(`Added memo "${memo.trim()}" to transfer call`);
210
+ }
211
+ const transferCall = {
212
+ to: client.USDC_CONTRACT_ADDRESS_BASE,
213
+ data: transferCallData,
214
+ value: '0x0'
215
+ };
216
+ // Combine spend permission calls with the transfer call
217
+ const allCalls = [...spendCalls, transferCall];
218
+ this.logger.info(`Executing ${allCalls.length} calls (${spendCalls.length} spend permission + 1 transfer)`);
219
+ const hash = await this.smartWallet.client.sendUserOperation({
220
+ account: this.smartWallet.account,
221
+ calls: allCalls.map(call => {
222
+ return {
223
+ to: call.to,
224
+ data: call.data,
225
+ value: BigInt(call.value || '0x0')
226
+ };
227
+ }),
228
+ maxPriorityFeePerGas: viem.parseEther('0.000000001')
229
+ });
230
+ const receipt = await this.smartWallet.client.waitForUserOperationReceipt({ hash });
231
+ if (!receipt) {
232
+ throw new Error('User operation failed');
233
+ }
234
+ // The receipt contains the actual transaction hash that was mined on chain
235
+ const txHash = receipt.receipt.transactionHash;
236
+ if (!txHash) {
237
+ throw new Error('User operation was executed but no transaction hash was returned. This should not happen.');
238
+ }
239
+ this.logger.info(`Spend permission executed successfully. UserOp: ${receipt.userOpHash}, TxHash: ${txHash}`);
240
+ // Wait for additional confirmations to ensure the transaction is well-propagated
241
+ // This helps avoid the "Transaction receipt could not be found" error
242
+ await waitForTransactionConfirmations(this.smartWallet, txHash, 2, this.logger);
243
+ // Return the actual transaction hash, not the user operation hash
244
+ // The payment verification system needs the on-chain transaction hash
245
+ return txHash;
246
+ }
247
+ }
248
+
249
+ const USDC_DECIMALS = 6;
250
+ class MainWalletPaymentMaker {
251
+ constructor(walletAddress, provider, logger) {
252
+ this.walletAddress = walletAddress;
253
+ this.provider = provider;
254
+ this.logger = logger || new common.ConsoleLogger();
255
+ }
256
+ async generateJWT(payload) {
257
+ this.logger.info(`codeChallenge: ${payload.codeChallenge}`);
258
+ this.logger.info(`paymentRequestId: ${payload.paymentRequestId}`);
259
+ this.logger.info(`walletAddress: ${this.walletAddress}`);
260
+ // Generate EIP-1271 auth data for main wallet authentication
261
+ const timestamp = Math.floor(Date.now() / 1000);
262
+ const message = constructEIP1271Message({
263
+ walletAddress: this.walletAddress,
264
+ timestamp,
265
+ codeChallenge: payload.codeChallenge,
266
+ paymentRequestId: payload.paymentRequestId
267
+ });
268
+ // Sign with the main wallet
269
+ // Coinbase Wallet requires hex-encoded messages, while other wallets may accept plain strings
270
+ let messageToSign;
271
+ // Check if this is Coinbase Wallet by looking for provider properties
272
+ const providerWithCoinbase = this.provider;
273
+ const isCoinbaseWallet = providerWithCoinbase.isCoinbaseWallet ||
274
+ providerWithCoinbase.isCoinbaseBrowser;
275
+ if (isCoinbaseWallet) {
276
+ // Coinbase Wallet requires hex-encoded messages
277
+ messageToSign = viem.toHex(message);
278
+ this.logger.info('Using hex-encoded message for Coinbase Wallet');
279
+ }
280
+ else {
281
+ // Other wallets (MetaMask, etc.) typically accept plain strings
282
+ messageToSign = message;
283
+ this.logger.info('Using plain string message for wallet');
284
+ }
285
+ const signature = await this.provider.request({
286
+ method: 'personal_sign',
287
+ params: [messageToSign, this.walletAddress]
288
+ });
289
+ const authData = createEIP1271AuthData({
290
+ walletAddress: this.walletAddress,
291
+ message,
292
+ signature,
293
+ timestamp,
294
+ codeChallenge: payload.codeChallenge,
295
+ paymentRequestId: payload.paymentRequestId
296
+ });
297
+ const jwtToken = createEIP1271JWT(authData);
298
+ this.logger.info(`Generated EIP-1271 JWT: ${jwtToken}`);
299
+ return jwtToken;
300
+ }
301
+ async makePayment(amount, currency, receiver, _reason) {
302
+ if (currency !== 'USDC') {
303
+ throw new Error('Only usdc currency is supported');
304
+ }
305
+ this.logger.info(`Making direct payment of ${amount} ${currency} to ${receiver} on Base`);
306
+ // Convert amount to USDC units (6 decimals)
307
+ const amountInUSDCUnits = BigInt(amount.multipliedBy(10 ** USDC_DECIMALS).toFixed(0));
308
+ // Encode the transfer function data
309
+ const transferData = viem.encodeFunctionData({
310
+ abi: [{
311
+ name: 'transfer',
312
+ type: 'function',
313
+ inputs: [
314
+ { name: 'to', type: 'address' },
315
+ { name: 'amount', type: 'uint256' }
316
+ ],
317
+ outputs: [{ name: '', type: 'bool' }]
318
+ }],
319
+ functionName: 'transfer',
320
+ args: [receiver, amountInUSDCUnits]
321
+ });
322
+ // Send the transaction through the user's wallet
323
+ const txHash = await this.provider.request({
324
+ method: 'eth_sendTransaction',
325
+ params: [{
326
+ from: this.walletAddress,
327
+ to: client.USDC_CONTRACT_ADDRESS_BASE,
328
+ data: transferData,
329
+ value: '0x0'
330
+ }]
331
+ });
332
+ this.logger.info(`Transaction submitted. TxHash: ${txHash}`);
333
+ // Wait for confirmations
334
+ const CONFIRMATIONS = 2;
335
+ await this.waitForTransactionConfirmations(txHash, CONFIRMATIONS);
336
+ return txHash;
337
+ }
338
+ async waitForTransactionConfirmations(txHash, confirmations) {
339
+ this.logger.info(`Waiting for ${confirmations} confirmations...`);
340
+ // Poll for transaction receipt
341
+ let receipt = null;
342
+ while (!receipt) {
343
+ try {
344
+ receipt = await this.provider.request({
345
+ method: 'eth_getTransactionReceipt',
346
+ params: [txHash]
347
+ });
348
+ if (!receipt) {
349
+ await new Promise(resolve => setTimeout(resolve, 1000));
350
+ }
351
+ }
352
+ catch (error) {
353
+ this.logger.warn(`Error getting receipt: ${error}`);
354
+ await new Promise(resolve => setTimeout(resolve, 1000));
355
+ }
356
+ }
357
+ // Check if transaction was successful
358
+ if (receipt.status === '0x0') {
359
+ throw new Error(`Transaction failed. TxHash: ${txHash}`);
360
+ }
361
+ // Wait for confirmations
362
+ const startBlock = parseInt(receipt.blockNumber, 16);
363
+ let currentBlock = startBlock;
364
+ while (currentBlock - startBlock < confirmations - 1) {
365
+ await new Promise(resolve => setTimeout(resolve, 1000));
366
+ const blockNumber = await this.provider.request({
367
+ method: 'eth_blockNumber',
368
+ params: []
369
+ });
370
+ currentBlock = parseInt(blockNumber, 16);
371
+ }
372
+ this.logger.info(`Transaction confirmed with ${confirmations} confirmations`);
373
+ }
374
+ }
375
+
376
+ /**
377
+ * Type-safe storage wrapper for permission data
378
+ */
379
+ class IntermediaryStorage {
380
+ constructor(storage) {
381
+ this.storage = storage;
382
+ }
383
+ get(key) {
384
+ const data = this.storage.get(key);
385
+ if (!data)
386
+ return null;
387
+ try {
388
+ const parsed = JSON.parse(data);
389
+ return parsed;
390
+ }
391
+ catch {
392
+ return null;
393
+ }
394
+ }
395
+ set(key, data) {
396
+ this.storage.set(key, JSON.stringify(data));
397
+ }
398
+ delete(key) {
399
+ this.storage.delete(key);
400
+ }
401
+ }
402
+ /**
403
+ * Browser localStorage implementation
404
+ */
405
+ class BrowserStorage {
406
+ isAvailable() {
407
+ return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
408
+ }
409
+ get(key) {
410
+ if (!this.isAvailable())
411
+ return null;
412
+ return localStorage.getItem(key);
413
+ }
414
+ set(key, value) {
415
+ if (!this.isAvailable())
416
+ return;
417
+ localStorage.setItem(key, value);
418
+ }
419
+ delete(key) {
420
+ if (!this.isAvailable())
421
+ return;
422
+ localStorage.removeItem(key);
423
+ }
424
+ }
425
+ /**
426
+ * In-memory storage implementation for testing
427
+ */
428
+ class MemoryStorage {
429
+ constructor() {
430
+ this.store = new Map();
431
+ }
432
+ get(key) {
433
+ return this.store.get(key) || null;
434
+ }
435
+ set(key, value) {
436
+ this.store.set(key, value);
437
+ }
438
+ delete(key) {
439
+ this.store.delete(key);
440
+ }
441
+ clear() {
442
+ this.store.clear();
443
+ }
444
+ }
445
+
446
+ // Coinbase CDP Paymaster and Bundler endpoints
447
+ const COINBASE_BUNDLER_URL = 'https://api.developer.coinbase.com/rpc/v1/base';
448
+ const COINBASE_PAYMASTER_URL = 'https://api.developer.coinbase.com/rpc/v1/base';
449
+ /**
450
+ * Creates an ephemeral smart wallet with paymaster support
451
+ */
452
+ async function toEphemeralSmartWallet(privateKey, apiKey) {
453
+ const signer = accounts.privateKeyToAccount(privateKey);
454
+ const publicClient = viem.createPublicClient({
455
+ chain: chains.base,
456
+ transport: viem.http(`${COINBASE_BUNDLER_URL}/${apiKey}`)
457
+ });
458
+ // Create the Coinbase smart wallet
459
+ const account = await accountAbstraction.toCoinbaseSmartAccount({
460
+ client: publicClient,
461
+ owners: [signer],
462
+ version: '1'
463
+ });
464
+ // Create bundler client with paymaster support
465
+ const bundlerClient = accountAbstraction.createBundlerClient({
466
+ account,
467
+ client: publicClient,
468
+ transport: viem.http(`${COINBASE_BUNDLER_URL}/${apiKey}`),
469
+ chain: chains.base,
470
+ paymaster: true, // Enable paymaster sponsorship
471
+ paymasterContext: {
472
+ transport: viem.http(`${COINBASE_PAYMASTER_URL}/${apiKey}`)
473
+ }
474
+ });
475
+ return {
476
+ address: account.address,
477
+ client: bundlerClient,
478
+ account,
479
+ signer,
480
+ };
481
+ }
482
+
483
+ const DEFAULT_ALLOWANCE = 10n;
484
+ const DEFAULT_PERIOD_IN_DAYS = 7;
485
+ const PAYMASTER_URL = 'https://api.developer.coinbase.com/rpc/v1/base/snPdXqIzOGhRkGNJvEHM5bl9Hm3yRO3m';
486
+ class BaseAppAccount {
487
+ static toStorageKey(userWalletAddress) {
488
+ return `atxp-base-permission-${userWalletAddress}`;
489
+ }
490
+ static async initialize(config) {
491
+ const logger = config.logger || new common.ConsoleLogger();
492
+ const useEphemeralWallet = config.useEphemeralWallet ?? true; // Default to true for backward compatibility
493
+ // Initialize Base SDK
494
+ const sdk = account.createBaseAccountSDK({
495
+ appName: config?.appName,
496
+ appChainIds: [chains.base.id],
497
+ paymasterUrls: {
498
+ [chains.base.id]: PAYMASTER_URL
499
+ }
500
+ });
501
+ const provider = sdk.getProvider();
502
+ // Some wallets don't support wallet_connect, so
503
+ // will just continue if it fails
504
+ try {
505
+ await provider.request({ method: 'wallet_connect' });
506
+ }
507
+ catch (error) {
508
+ // Continue if wallet_connect is not supported
509
+ logger.warn(`wallet_connect not supported, continuing with initialization. ${error}`);
510
+ }
511
+ // If using main wallet mode, return early with main wallet payment maker
512
+ if (!useEphemeralWallet) {
513
+ logger.info(`Using main wallet mode for address: ${config.walletAddress}`);
514
+ return new BaseAppAccount(null, // No spend permission in main wallet mode
515
+ null, // No ephemeral wallet in main wallet mode
516
+ logger, config.walletAddress, provider);
517
+ }
518
+ // Validate smart wallet configuration for ephemeral mode
519
+ if (!config.apiKey) {
520
+ throw new Error('Smart wallet API key is required for ephemeral wallet mode. ' +
521
+ 'Get your API key from https://portal.cdp.coinbase.com/');
522
+ }
523
+ // Initialize storage
524
+ const baseStorage = config?.storage || new BrowserStorage();
525
+ const storage = new IntermediaryStorage(baseStorage);
526
+ const storageKey = this.toStorageKey(config.walletAddress);
527
+ // Try to load existing permission
528
+ const existingData = this.loadSavedWalletAndPermission(storage, storageKey);
529
+ if (existingData) {
530
+ const ephemeralSmartWallet = await toEphemeralSmartWallet(existingData.privateKey, config.apiKey);
531
+ return new BaseAppAccount(existingData.permission, ephemeralSmartWallet, logger);
532
+ }
533
+ const privateKey = accounts.generatePrivateKey();
534
+ const smartWallet = await toEphemeralSmartWallet(privateKey, config.apiKey);
535
+ logger.info(`Generated ephemeral wallet: ${smartWallet.address}`);
536
+ await this.deploySmartWallet(smartWallet);
537
+ logger.info(`Deployed smart wallet: ${smartWallet.address}`);
538
+ // Dynamically import requestSpendPermission based on environment
539
+ // This function requires browser APIs and wallet interaction
540
+ const { requestSpendPermission } = await getSpendPermissionModule();
541
+ const permission = await requestSpendPermission({
542
+ account: config.walletAddress,
543
+ spender: smartWallet.address,
544
+ token: client.USDC_CONTRACT_ADDRESS_BASE,
545
+ chainId: chains.base.id,
546
+ allowance: config?.allowance ?? DEFAULT_ALLOWANCE,
547
+ periodInDays: config?.periodInDays ?? DEFAULT_PERIOD_IN_DAYS,
548
+ provider,
549
+ });
550
+ // Save wallet and permission
551
+ storage.set(storageKey, { privateKey, permission });
552
+ return new BaseAppAccount(permission, smartWallet, logger);
553
+ }
554
+ static loadSavedWalletAndPermission(permissionStorage, storageKey) {
555
+ const storedData = permissionStorage.get(storageKey);
556
+ if (!storedData)
557
+ return null;
558
+ // Check if permission is not expired
559
+ const now = Math.floor(Date.now() / 1000);
560
+ const permissionEnd = parseInt(storedData.permission.permission.end.toString());
561
+ if (permissionEnd <= now) {
562
+ permissionStorage.delete(storageKey);
563
+ return null;
564
+ }
565
+ return storedData;
566
+ }
567
+ static async deploySmartWallet(smartWallet) {
568
+ const deployTx = await smartWallet.client.sendUserOperation({
569
+ calls: [{
570
+ to: smartWallet.address,
571
+ value: 0n,
572
+ data: '0x'
573
+ }],
574
+ paymaster: true
575
+ });
576
+ const receipt = await smartWallet.client.waitForUserOperationReceipt({
577
+ hash: deployTx
578
+ });
579
+ if (!receipt.success) {
580
+ throw new Error(`Smart wallet deployment failed. Receipt: ${JSON.stringify(receipt)}`);
581
+ }
582
+ }
583
+ constructor(spendPermission, ephemeralSmartWallet, logger, mainWalletAddress, provider) {
584
+ if (ephemeralSmartWallet) {
585
+ // Ephemeral wallet mode
586
+ if (!spendPermission) {
587
+ throw new Error('Spend permission is required for ephemeral wallet mode');
588
+ }
589
+ this.accountId = ephemeralSmartWallet.address;
590
+ this.paymentMakers = {
591
+ 'base': new BaseAppPaymentMaker(spendPermission, ephemeralSmartWallet, logger),
592
+ };
593
+ }
594
+ else {
595
+ // Main wallet mode
596
+ if (!mainWalletAddress || !provider) {
597
+ throw new Error('Main wallet address and provider are required for main wallet mode');
598
+ }
599
+ this.accountId = mainWalletAddress;
600
+ this.paymentMakers = {
601
+ 'base': new MainWalletPaymentMaker(mainWalletAddress, provider, logger),
602
+ };
603
+ }
604
+ }
605
+ /**
606
+ * Dynamically import the appropriate spend-permission module based on environment.
607
+ * Uses browser version as requestSpendPermission only exists there.
608
+ * Throws error if used in server-side environment.
609
+ */
610
+ static clearAllStoredData(userWalletAddress, storage) {
611
+ // In non-browser environments, require an explicit storage parameter
612
+ if (!storage) {
613
+ const browserStorage = new BrowserStorage();
614
+ // Check if BrowserStorage would work (i.e., we're in a browser)
615
+ if (typeof window === 'undefined') {
616
+ throw new Error('clearAllStoredData requires a storage to be provided outside of browser environments');
617
+ }
618
+ storage = browserStorage;
619
+ }
620
+ storage.delete(this.toStorageKey(userWalletAddress));
621
+ }
622
+ }
623
+
624
+ exports.BaseAppAccount = BaseAppAccount;
625
+ exports.BaseAppPaymentMaker = BaseAppPaymentMaker;
626
+ exports.BrowserStorage = BrowserStorage;
627
+ exports.MainWalletPaymentMaker = MainWalletPaymentMaker;
628
+ exports.MemoryStorage = MemoryStorage;
629
+ exports.PermissionStorage = IntermediaryStorage;
630
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../src/spendPermissionUtils.ts","../src/eip1271JwtHelper.ts","../src/baseAppPaymentMaker.ts","../src/mainWalletPaymentMaker.ts","../src/storage.ts","../src/smartWalletHelpers.ts","../src/baseAppAccount.ts"],"sourcesContent":[null,null,null,null,null,null,null],"names":["USDC_DECIMALS","ConsoleLogger","encodeFunctionData","USDC_CONTRACT_ADDRESS_BASE","parseEther","toHex","privateKeyToAccount","createPublicClient","base","http","toCoinbaseSmartAccount","createBundlerClient","createBaseAccountSDK","generatePrivateKey"],"mappings":";;;;;;;;;;AAAA;;;;;;AAMG;AACI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