@smoothsend/sdk 2.2.10 → 2.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.
@@ -1,4 +1,4 @@
1
- import { Address, Hex, PublicClient, WalletClient } from 'viem';
1
+ import { PublicClient, WalletClient, Address, Hex } from 'viem';
2
2
  import { UserOperation } from 'viem/account-abstraction';
3
3
  import * as react_jsx_runtime from 'react/jsx-runtime';
4
4
  import { ReactNode } from 'react';
@@ -49,14 +49,29 @@ interface PaymasterSignRequestAvax {
49
49
  allowAnyBundler?: boolean;
50
50
  sponsorUUID?: string;
51
51
  }
52
+ interface AvaxFeePreview {
53
+ predictedGasCostWei: string;
54
+ predictedTokenFee: string;
55
+ minTokenFee: string;
56
+ variableTokenFee: string;
57
+ floorApplied: boolean;
58
+ }
59
+ interface AvaxHashTypes {
60
+ sendUserOperationResult?: 'userOpHash';
61
+ explorerTxLinkRequires?: 'transactionHash';
62
+ userOpHash?: 'userOpHash';
63
+ transactionHash?: 'transactionHash';
64
+ }
52
65
  interface PaymasterSignResponseAvax {
53
66
  success: boolean;
54
67
  requestId?: string;
55
68
  network?: string;
69
+ hashTypes?: AvaxHashTypes;
56
70
  paymasterAndData: string;
57
71
  paymasterData?: string;
58
72
  signature?: string;
59
73
  exchangeRate?: string;
74
+ feePreview?: AvaxFeePreview;
60
75
  paymasterDataParts?: Record<string, string>;
61
76
  error?: string;
62
77
  }
@@ -75,6 +90,7 @@ interface UserOperationReceiptAvax {
75
90
  blockNumber: number;
76
91
  blockHash: string;
77
92
  };
93
+ hashTypes?: AvaxHashTypes;
78
94
  }
79
95
  /** Partial UserOp before estimate/paymaster (signature optional, usually `0x` until wallet signs). */
80
96
  type SponsoredUserOpDraftAvax = Omit<UserOperationAvax, 'signature'> & {
@@ -82,14 +98,22 @@ type SponsoredUserOpDraftAvax = Omit<UserOperationAvax, 'signature'> & {
82
98
  };
83
99
 
84
100
  /**
85
- * Avalanche ERC-4337 (EntryPoint v0.7) via SmoothSend gateway — same idea as Aptos submitter.
86
- *
87
- * Minimal dApp flow:
88
- * ```ts
89
- * const avax = new SmoothSendAvaxSubmitter({ apiKey, network: 'testnet' });
90
- * await avax.submitSponsoredUserOperation({ userOp: draft, signUserOp: wallet.sign });
91
- * ```
101
+ * Public gateway defaults for Avalanche AA (no API key).
102
+ */
103
+ /** Canonical ERC-4337 EntryPoint v0.7 on Fuji / Avalanche C-Chain */
104
+ declare const ENTRY_POINT_V07_ADDRESS: "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
105
+ type AvaxAaPublicDefaults = {
106
+ success?: boolean;
107
+ simpleAccountFactoryFuji: `0x${string}` | null;
108
+ simpleAccountFactoryMainnet: `0x${string}` | null;
109
+ entryPointV07: typeof ENTRY_POINT_V07_ADDRESS;
110
+ paymasterFuji: `0x${string}` | null;
111
+ paymasterMainnet: `0x${string}` | null;
112
+ };
113
+ /**
114
+ * Fetch SimpleAccount factory and Paymaster hints from SmoothSend gateway (GET; no auth).
92
115
  */
116
+ declare function fetchAvaxAaPublicDefaults(gatewayUrl?: string): Promise<AvaxAaPublicDefaults>;
93
117
 
94
118
  /** Options for {@link SmoothSendAvaxSubmitter.submitSponsoredUserOperation} */
95
119
  interface SubmitSponsoredAvaxUserOpOptions {
@@ -109,6 +133,14 @@ interface SubmitSponsoredAvaxUserOpOptions {
109
133
  timeoutMs?: number;
110
134
  };
111
135
  }
136
+ interface EstimateUserPaysFeeAvaxOptions {
137
+ /** Draft UserOperation (same shape as submit flow before signing) */
138
+ userOp: SponsoredUserOpDraftAvax;
139
+ /** Optional entrypoint, defaults to eth_supportedEntryPoints()[0] */
140
+ entryPoint?: string;
141
+ /** Optional paymaster params such as token/receiver overrides */
142
+ paymaster?: Omit<PaymasterSignRequestAvax, 'mode' | 'userOp'>;
143
+ }
112
144
  interface SmoothSendAvaxSubmitterConfig {
113
145
  apiKey: string;
114
146
  network?: 'testnet' | 'mainnet';
@@ -144,7 +176,24 @@ declare class SmoothSendAvaxSubmitter {
144
176
  timeoutMs?: number;
145
177
  }): Promise<UserOperationReceiptAvax | null>;
146
178
  paymasterSign(body: PaymasterSignRequestAvax): Promise<PaymasterSignResponseAvax>;
179
+ /**
180
+ * Preflight fee estimate for `user-pays-erc20` mode.
181
+ *
182
+ * This performs:
183
+ * 1) `eth_estimateUserOperationGas`
184
+ * 2) `paymaster/sign` in `user-pays-erc20` mode
185
+ * and returns `feePreview` when available.
186
+ */
187
+ estimateUserPaysFee(opts: EstimateUserPaysFeeAvaxOptions): Promise<{
188
+ entryPoint: string;
189
+ userOp: UserOperationAvax;
190
+ gas: GasEstimateAvax;
191
+ exchangeRate?: string;
192
+ feePreview?: AvaxFeePreview;
193
+ }>;
147
194
  getBundlerHealth(): Promise<unknown>;
195
+ /** Fetch public AA addresses (Factory, Paymaster) from gateway. */
196
+ getPublicAaDefaults(): Promise<AvaxAaPublicDefaults>;
148
197
  /**
149
198
  * One call: estimate gas → paymaster/sign → merge → your sign → send → (optional) wait for receipt.
150
199
  */
@@ -160,6 +209,61 @@ declare class SmoothSendAvaxSubmitter {
160
209
  declare const AvaxSubmitter: typeof SmoothSendAvaxSubmitter;
161
210
  declare function createSmoothSendAvaxSubmitter(config: SmoothSendAvaxSubmitterConfig): SmoothSendAvaxSubmitter;
162
211
 
212
+ interface SmoothSendAvaxClientConfig {
213
+ apiKey: string;
214
+ network?: 'testnet' | 'mainnet';
215
+ gatewayUrl?: string;
216
+ timeout?: number;
217
+ chain?: string;
218
+ corsOrigin?: string;
219
+ publicClient: PublicClient;
220
+ walletClient: WalletClient;
221
+ smartAccountAddress?: Address;
222
+ accountFactory?: Address;
223
+ accountSalt?: bigint;
224
+ }
225
+ interface SimpleCallInput {
226
+ to: Address;
227
+ data?: Hex;
228
+ value?: bigint;
229
+ }
230
+ declare class SmoothSendAvaxClient {
231
+ readonly submitter: SmoothSendAvaxSubmitter;
232
+ readonly config: SmoothSendAvaxClientConfig;
233
+ constructor(config: SmoothSendAvaxClientConfig);
234
+ submitCall(args: {
235
+ call: SimpleCallInput;
236
+ mode?: AvaxSponsorshipMode;
237
+ paymaster?: Omit<PaymasterSignRequestAvax, 'mode' | 'userOp'>;
238
+ waitForReceipt?: boolean;
239
+ }): Promise<{
240
+ userOpHash: string;
241
+ transactionHash: string | undefined;
242
+ receipt: UserOperationReceiptAvax | null;
243
+ }>;
244
+ submitCalls(args: {
245
+ calls: SimpleCallInput[];
246
+ mode?: AvaxSponsorshipMode;
247
+ paymaster?: Omit<PaymasterSignRequestAvax, 'mode' | 'userOp'>;
248
+ waitForReceipt?: boolean;
249
+ }): Promise<{
250
+ userOpHash: string;
251
+ transactionHash: string | undefined;
252
+ receipt: UserOperationReceiptAvax | null;
253
+ }>;
254
+ estimateUserPaysFee(args: {
255
+ calls: SimpleCallInput[];
256
+ paymaster?: Omit<PaymasterSignRequestAvax, 'mode' | 'userOp'>;
257
+ }): Promise<{
258
+ feePreview?: AvaxFeePreview;
259
+ exchangeRate?: string;
260
+ entryPoint: string;
261
+ }>;
262
+ private buildDraft;
263
+ private signUserOpHash;
264
+ }
265
+ declare function createSmoothSendAvaxClient(config: SmoothSendAvaxClientConfig): SmoothSendAvaxClient;
266
+
163
267
  /**
164
268
  * Viem helpers for ERC-4337 v0.7 + common smart-account `execute` encoding.
165
269
  * Peer dependency: `viem` (optional install).
@@ -257,24 +361,6 @@ declare function predictSimpleAccountAddress(params: {
257
361
  }): Promise<Address>;
258
362
  declare function encodeCreateAccountFactoryData(owner: Address, salt: bigint): Hex;
259
363
 
260
- /**
261
- * Public gateway defaults for Avalanche AA (no API key).
262
- */
263
- /** Canonical ERC-4337 EntryPoint v0.7 on Fuji / Avalanche C-Chain */
264
- declare const ENTRY_POINT_V07_ADDRESS: "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
265
- type AvaxAaPublicDefaults = {
266
- success?: boolean;
267
- simpleAccountFactoryFuji: `0x${string}` | null;
268
- simpleAccountFactoryMainnet: `0x${string}` | null;
269
- entryPointV07: typeof ENTRY_POINT_V07_ADDRESS;
270
- paymasterFuji: `0x${string}` | null;
271
- paymasterMainnet: `0x${string}` | null;
272
- };
273
- /**
274
- * Fetch SimpleAccount factory and Paymaster hints from SmoothSend gateway (GET; no auth).
275
- */
276
- declare function fetchAvaxAaPublicDefaults(gatewayUrl?: string): Promise<AvaxAaPublicDefaults>;
277
-
278
364
  type SmoothSendAvaxContextValue = {
279
365
  apiKey: string;
280
366
  network: 'testnet' | 'mainnet';
@@ -309,6 +395,8 @@ type UseSmoothSendAvaxParams = {
309
395
  };
310
396
  declare function useSmoothSendAvax(params: UseSmoothSendAvaxParams): {
311
397
  submitter: SmoothSendAvaxSubmitter;
398
+ paymasterAddress: Address | null;
399
+ discoveredFactory: Address | null;
312
400
  submitCall: (args: {
313
401
  to: Address;
314
402
  data?: Hex;
@@ -327,7 +415,27 @@ declare function useSmoothSendAvax(params: UseSmoothSendAvaxParams): {
327
415
  paymaster?: Omit<PaymasterSignRequestAvax, 'mode' | 'userOp'>;
328
416
  waitForReceipt?: boolean;
329
417
  }) => ReturnType<SmoothSendAvaxSubmitter['submitSponsoredUserOperation']>;
418
+ estimateUserPaysFee: (args: {
419
+ to?: Address;
420
+ data?: Hex;
421
+ value?: bigint;
422
+ call?: {
423
+ to: Address;
424
+ data?: Hex;
425
+ value?: bigint;
426
+ };
427
+ calls?: {
428
+ to: Address;
429
+ data?: Hex;
430
+ value?: bigint;
431
+ }[];
432
+ paymaster?: Omit<PaymasterSignRequestAvax, 'mode' | 'userOp'>;
433
+ }) => Promise<{
434
+ entryPoint: string;
435
+ feePreview?: AvaxFeePreview;
436
+ exchangeRate?: string;
437
+ }>;
330
438
  };
331
439
 
332
- export { AvaxSubmitter, ENTRY_POINT_V07_ADDRESS, SIMPLE_ACCOUNT_FACTORY_ABI, SmoothSendAvaxProvider, SmoothSendAvaxSubmitter, avaxExecuteAbi, createSmoothSendAvaxSubmitter, encodeAvaxExecuteCalldata, encodeCreateAccountFactoryData, fetchAvaxAaPublicDefaults, hashUserOperationAvax, predictSimpleAccountAddress, readAvaxSenderNonce, useSmoothSendAvax, useSmoothSendAvaxContext, userOperationAvaxToViem };
333
- export type { AvaxAaPublicDefaults, AvaxSponsorshipMode, GasEstimateAvax, PaymasterSignRequestAvax, PaymasterSignResponseAvax, SmoothSendAvaxContextValue, SmoothSendAvaxSubmitterConfig, SponsoredUserOpDraftAvax, SubmitSponsoredAvaxUserOpOptions, UseSmoothSendAvaxParams, UserOperationAvax, UserOperationReceiptAvax };
440
+ export { AvaxSubmitter, ENTRY_POINT_V07_ADDRESS, SIMPLE_ACCOUNT_FACTORY_ABI, SmoothSendAvaxClient, SmoothSendAvaxProvider, SmoothSendAvaxSubmitter, avaxExecuteAbi, createSmoothSendAvaxClient, createSmoothSendAvaxSubmitter, encodeAvaxExecuteCalldata, encodeCreateAccountFactoryData, fetchAvaxAaPublicDefaults, hashUserOperationAvax, predictSimpleAccountAddress, readAvaxSenderNonce, useSmoothSendAvax, useSmoothSendAvaxContext, userOperationAvaxToViem };
441
+ export type { AvaxAaPublicDefaults, AvaxFeePreview, AvaxHashTypes, AvaxSponsorshipMode, EstimateUserPaysFeeAvaxOptions, GasEstimateAvax, PaymasterSignRequestAvax, PaymasterSignResponseAvax, SimpleCallInput, SmoothSendAvaxClientConfig, SmoothSendAvaxContextValue, SmoothSendAvaxSubmitterConfig, SponsoredUserOpDraftAvax, SubmitSponsoredAvaxUserOpOptions, UseSmoothSendAvaxParams, UserOperationAvax, UserOperationReceiptAvax };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/avax/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,mBAAmB,EACnB,eAAe,EACf,mBAAmB,EACnB,wBAAwB,EACxB,yBAAyB,EACzB,wBAAwB,EACxB,iBAAiB,EACjB,wBAAwB,GACzB,MAAM,SAAS,CAAC;AAEjB,OAAO,EACL,aAAa,EACb,uBAAuB,EACvB,6BAA6B,EAC7B,KAAK,6BAA6B,EAClC,KAAK,gCAAgC,GACtC,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EACL,cAAc,EACd,yBAAyB,EACzB,qBAAqB,EACrB,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,0BAA0B,EAC1B,8BAA8B,EAC9B,2BAA2B,GAC5B,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,KAAK,oBAAoB,GAC1B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,sBAAsB,EACtB,iBAAiB,EACjB,wBAAwB,EACxB,KAAK,0BAA0B,EAC/B,KAAK,uBAAuB,GAC7B,MAAM,qBAAqB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/avax/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,cAAc,EACd,aAAa,EACb,mBAAmB,EACnB,eAAe,EACf,mBAAmB,EACnB,wBAAwB,EACxB,yBAAyB,EACzB,wBAAwB,EACxB,iBAAiB,EACjB,wBAAwB,GACzB,MAAM,SAAS,CAAC;AAEjB,OAAO,EACL,aAAa,EACb,uBAAuB,EACvB,6BAA6B,EAC7B,KAAK,6BAA6B,EAClC,KAAK,8BAA8B,EACnC,KAAK,gCAAgC,GACtC,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EACL,oBAAoB,EACpB,0BAA0B,EAC1B,KAAK,0BAA0B,EAC/B,KAAK,eAAe,EACrB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACL,cAAc,EACd,yBAAyB,EACzB,qBAAqB,EACrB,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,0BAA0B,EAC1B,8BAA8B,EAC9B,2BAA2B,GAC5B,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,KAAK,oBAAoB,GAC1B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,sBAAsB,EACtB,iBAAiB,EACjB,wBAAwB,EACxB,KAAK,0BAA0B,EAC/B,KAAK,uBAAuB,GAC7B,MAAM,qBAAqB,CAAC"}
@@ -4,7 +4,7 @@ import { encodeFunctionData, slice, size, hexToBigInt, toHex } from 'viem';
4
4
  import { getUserOperationHash, entryPoint07Abi } from 'viem/account-abstraction';
5
5
  import { readContract } from 'viem/actions';
6
6
  import { jsx } from 'react/jsx-runtime';
7
- import { createContext, useMemo, useCallback, useContext } from 'react';
7
+ import { createContext, useMemo, useState, useEffect, useCallback, useContext } from 'react';
8
8
 
9
9
  /**
10
10
  * Avalanche ERC-4337 (EntryPoint v0.7) via SmoothSend gateway — same idea as Aptos submitter.
@@ -113,12 +113,49 @@ class SmoothSendAvaxSubmitter {
113
113
  }
114
114
  return data;
115
115
  }
116
+ /**
117
+ * Preflight fee estimate for `user-pays-erc20` mode.
118
+ *
119
+ * This performs:
120
+ * 1) `eth_estimateUserOperationGas`
121
+ * 2) `paymaster/sign` in `user-pays-erc20` mode
122
+ * and returns `feePreview` when available.
123
+ */
124
+ async estimateUserPaysFee(opts) {
125
+ const entryPoint = opts.entryPoint ?? (await this.getSupportedEntryPoints())[0];
126
+ if (!entryPoint) {
127
+ throw new Error('[SmoothSendAvaxSubmitter] no EntryPoint from bundler');
128
+ }
129
+ let userOp = {
130
+ ...opts.userOp,
131
+ signature: opts.userOp.signature ?? '0x',
132
+ };
133
+ const gas = await this.estimateUserOperationGas(userOp, entryPoint);
134
+ userOp = SmoothSendAvaxSubmitter.applyGasEstimate(userOp, gas);
135
+ const signedPm = await this.paymasterSign({
136
+ mode: 'user-pays-erc20',
137
+ userOp,
138
+ ...opts.paymaster,
139
+ });
140
+ return {
141
+ entryPoint,
142
+ userOp,
143
+ gas,
144
+ exchangeRate: signedPm.exchangeRate,
145
+ feePreview: signedPm.feePreview,
146
+ };
147
+ }
116
148
  async getBundlerHealth() {
117
149
  const res = await this.http.get('/api/v1/bundler/health');
118
150
  if (!res.success)
119
151
  throw new Error('[SmoothSendAvaxSubmitter] health failed');
120
152
  return res.data;
121
153
  }
154
+ /** Fetch public AA addresses (Factory, Paymaster) from gateway. */
155
+ async getPublicAaDefaults() {
156
+ const { fetchAvaxAaPublicDefaults } = await Promise.resolve().then(function () { return publicAaDefaults; });
157
+ return fetchAvaxAaPublicDefaults(this.config.gatewayUrl ?? DEFAULT_GATEWAY);
158
+ }
122
159
  /**
123
160
  * One call: estimate gas → paymaster/sign → merge → your sign → send → (optional) wait for receipt.
124
161
  */
@@ -348,6 +385,164 @@ function encodeCreateAccountFactoryData(owner, salt) {
348
385
  });
349
386
  }
350
387
 
388
+ class SmoothSendAvaxClient {
389
+ constructor(config) {
390
+ this.config = config;
391
+ this.submitter = new SmoothSendAvaxSubmitter({
392
+ apiKey: config.apiKey,
393
+ network: config.network,
394
+ gatewayUrl: config.gatewayUrl,
395
+ timeout: config.timeout,
396
+ chain: config.chain,
397
+ corsOrigin: config.corsOrigin
398
+ });
399
+ }
400
+ async submitCall(args) {
401
+ return this.submitCalls({
402
+ calls: [args.call],
403
+ mode: args.mode,
404
+ paymaster: args.paymaster,
405
+ waitForReceipt: args.waitForReceipt
406
+ });
407
+ }
408
+ async submitCalls(args) {
409
+ if (args.calls.length === 0) {
410
+ throw new Error('[SmoothSend AVAX] No calls provided');
411
+ }
412
+ const built = await this.buildDraft(args.calls);
413
+ const result = await this.submitter.submitSponsoredUserOperation({
414
+ userOp: built.userOp,
415
+ mode: args.mode ?? 'developer-sponsored',
416
+ paymaster: args.paymaster,
417
+ waitForReceipt: args.waitForReceipt,
418
+ signUserOp: async (op) => {
419
+ const hash = hashUserOperationAvax({
420
+ chainId: built.chainId,
421
+ entryPointAddress: built.entryPoint,
422
+ userOperation: op
423
+ });
424
+ return this.signUserOpHash(hash);
425
+ }
426
+ });
427
+ return {
428
+ userOpHash: result.userOpHash,
429
+ transactionHash: result.receipt?.receipt?.transactionHash,
430
+ receipt: result.receipt
431
+ };
432
+ }
433
+ async estimateUserPaysFee(args) {
434
+ if (args.calls.length === 0) {
435
+ throw new Error('[SmoothSend AVAX] No calls provided');
436
+ }
437
+ const built = await this.buildDraft(args.calls);
438
+ const estimate = await this.submitter.estimateUserPaysFee({
439
+ userOp: built.userOp,
440
+ entryPoint: built.entryPoint,
441
+ paymaster: args.paymaster
442
+ });
443
+ return {
444
+ feePreview: estimate.feePreview,
445
+ exchangeRate: estimate.exchangeRate,
446
+ entryPoint: estimate.entryPoint
447
+ };
448
+ }
449
+ async buildDraft(calls) {
450
+ const { publicClient, walletClient } = this.config;
451
+ const account = walletClient.account;
452
+ if (!account) {
453
+ throw new Error('[SmoothSend AVAX] walletClient.account missing');
454
+ }
455
+ const ownerAddress = account.address;
456
+ const defaults = await this.submitter.getPublicAaDefaults().catch(() => null);
457
+ const accountFactory = this.config.accountFactory ??
458
+ ((this.config.network ?? 'testnet') === 'mainnet'
459
+ ? defaults?.simpleAccountFactoryMainnet
460
+ : defaults?.simpleAccountFactoryFuji) ??
461
+ undefined;
462
+ const chainId = Number(publicClient.chain?.id ?? (await publicClient.getChainId()));
463
+ const entryPoint = (await this.submitter.getSupportedEntryPoints())[0];
464
+ let sender;
465
+ if (accountFactory) {
466
+ const predicted = await predictSimpleAccountAddress({
467
+ publicClient,
468
+ factory: accountFactory,
469
+ owner: ownerAddress,
470
+ salt: this.config.accountSalt ?? 0n
471
+ });
472
+ if (this.config.smartAccountAddress &&
473
+ predicted.toLowerCase() !== this.config.smartAccountAddress.toLowerCase()) {
474
+ throw new Error(`[SmoothSend AVAX] smartAccountAddress ${this.config.smartAccountAddress} does not match factory prediction ${predicted}`);
475
+ }
476
+ sender = predicted;
477
+ }
478
+ else if (this.config.smartAccountAddress) {
479
+ sender = this.config.smartAccountAddress;
480
+ }
481
+ else {
482
+ throw new Error('[SmoothSend AVAX] Provide smartAccountAddress or accountFactory (or use gateway public defaults).');
483
+ }
484
+ const code = await publicClient.getBytecode({ address: sender });
485
+ const deployed = typeof code === 'string' && code !== '0x' && code.length > 2;
486
+ let nonce;
487
+ let factory;
488
+ let factoryData;
489
+ if (!deployed) {
490
+ if (!accountFactory) {
491
+ throw new Error('[SmoothSend AVAX] Sender is not deployed and no accountFactory available');
492
+ }
493
+ nonce = 0n;
494
+ factory = accountFactory;
495
+ factoryData = encodeCreateAccountFactoryData(ownerAddress, this.config.accountSalt ?? 0n);
496
+ }
497
+ else {
498
+ nonce = await readAvaxSenderNonce({
499
+ publicClient,
500
+ entryPointAddress: entryPoint,
501
+ sender
502
+ });
503
+ }
504
+ let maxFeePerGas = 50n * 10n ** 9n;
505
+ let maxPriorityFeePerGas = 2n * 10n ** 9n;
506
+ try {
507
+ const est = await publicClient.estimateFeesPerGas();
508
+ if (est.maxFeePerGas)
509
+ maxFeePerGas = est.maxFeePerGas;
510
+ if (est.maxPriorityFeePerGas)
511
+ maxPriorityFeePerGas = est.maxPriorityFeePerGas;
512
+ }
513
+ catch {
514
+ // ignore and use fallbacks
515
+ }
516
+ const callData = calls.length === 1
517
+ ? encodeAvaxExecuteCalldata(calls[0].to, calls[0].value ?? 0n, calls[0].data ?? '0x')
518
+ : encodeAvaxExecuteBatchCalldata(calls.map((c) => c.to), calls.map((c) => c.value ?? 0n), calls.map((c) => c.data ?? '0x'));
519
+ return {
520
+ userOp: {
521
+ sender,
522
+ nonce: toHex(nonce),
523
+ callData,
524
+ maxFeePerGas: toHex(maxFeePerGas),
525
+ maxPriorityFeePerGas: toHex(maxPriorityFeePerGas),
526
+ ...(factory && factoryData ? { factory, factoryData } : {})
527
+ },
528
+ chainId,
529
+ entryPoint
530
+ };
531
+ }
532
+ async signUserOpHash(hash) {
533
+ const account = this.config.walletClient.account;
534
+ if (!account)
535
+ throw new Error('[SmoothSend AVAX] walletClient.account missing');
536
+ return this.config.walletClient.signMessage({
537
+ account,
538
+ message: { raw: hash }
539
+ });
540
+ }
541
+ }
542
+ function createSmoothSendAvaxClient(config) {
543
+ return new SmoothSendAvaxClient(config);
544
+ }
545
+
351
546
  /**
352
547
  * Public gateway defaults for Avalanche AA (no API key).
353
548
  */
@@ -382,6 +577,12 @@ async function fetchAvaxAaPublicDefaults(gatewayUrl = 'https://proxy.smoothsend.
382
577
  };
383
578
  }
384
579
 
580
+ var publicAaDefaults = /*#__PURE__*/Object.freeze({
581
+ __proto__: null,
582
+ ENTRY_POINT_V07_ADDRESS: ENTRY_POINT_V07_ADDRESS,
583
+ fetchAvaxAaPublicDefaults: fetchAvaxAaPublicDefaults
584
+ });
585
+
385
586
  const SmoothSendAvaxContext = createContext(null);
386
587
  function SmoothSendAvaxProvider({ apiKey, network = 'testnet', smartAccountAddress, accountFactory, accountSalt, children, }) {
387
588
  const value = useMemo(() => ({
@@ -401,12 +602,20 @@ function useSmoothSendAvax(params) {
401
602
  const apiKey = params.apiKey ?? ctx?.apiKey;
402
603
  const network = params.network ?? ctx?.network ?? 'testnet';
403
604
  const smartAccountAddressProp = params.smartAccountAddress ?? ctx?.smartAccountAddress;
404
- const accountFactory = params.accountFactory ?? ctx?.accountFactory;
605
+ const accountFactoryProp = params.accountFactory ?? ctx?.accountFactory;
405
606
  const accountSalt = params.accountSalt ?? ctx?.accountSalt ?? 0n;
406
607
  if (!apiKey) {
407
608
  throw new Error('[SmoothSend AVAX] apiKey required — pass useSmoothSendAvax({ apiKey }) or wrap SmoothSendAvaxProvider');
408
609
  }
409
610
  const submitter = useMemo(() => new SmoothSendAvaxSubmitter({ apiKey, network }), [apiKey, network]);
611
+ const [discovered, setDiscovered] = useState(null);
612
+ useEffect(() => {
613
+ submitter.getPublicAaDefaults().then(setDiscovered).catch(err => {
614
+ console.warn('[SmoothSend AVAX] Auto-discovery failed:', err);
615
+ });
616
+ }, [submitter]);
617
+ const accountFactory = accountFactoryProp ?? (network === 'mainnet' ? discovered?.simpleAccountFactoryMainnet : discovered?.simpleAccountFactoryFuji);
618
+ const paymasterAddress = (network === 'mainnet' ? discovered?.paymasterMainnet : discovered?.paymasterFuji);
410
619
  const { publicClient, walletClient } = params;
411
620
  const submitCall = useCallback(async (params) => {
412
621
  if (!publicClient) {
@@ -530,8 +739,116 @@ function useSmoothSendAvax(params) {
530
739
  waitForReceipt: args.waitForReceipt,
531
740
  });
532
741
  }, [submitCall]);
533
- return { submitter, submitCall, submitSponsoredUserOp };
742
+ const estimateUserPaysFee = useCallback(async (params) => {
743
+ if (!publicClient) {
744
+ throw new Error('[SmoothSend AVAX] publicClient missing (wagmi usePublicClient)');
745
+ }
746
+ if (!walletClient) {
747
+ throw new Error('[SmoothSend AVAX] walletClient missing (wagmi useWalletClient)');
748
+ }
749
+ if (!smartAccountAddressProp && !accountFactory) {
750
+ throw new Error('[SmoothSend AVAX] No smartAccountAddress or accountFactory provided. Pass them to SmoothSendAvaxProvider or useSmoothSendAvax hook.');
751
+ }
752
+ const account = walletClient.account;
753
+ if (!account) {
754
+ throw new Error('[SmoothSend AVAX] walletClient.account missing — connect wallet (wagmi useWalletClient)');
755
+ }
756
+ const ownerAddress = account.address;
757
+ let sender;
758
+ if (accountFactory) {
759
+ const predicted = await predictSimpleAccountAddress({
760
+ publicClient,
761
+ factory: accountFactory,
762
+ owner: ownerAddress,
763
+ salt: accountSalt,
764
+ });
765
+ if (smartAccountAddressProp &&
766
+ predicted.toLowerCase() !== smartAccountAddressProp.toLowerCase()) {
767
+ throw new Error(`[SmoothSend AVAX] smartAccountAddress ${smartAccountAddressProp} does not match factory prediction ${predicted}`);
768
+ }
769
+ sender = predicted;
770
+ }
771
+ else {
772
+ sender = smartAccountAddressProp;
773
+ }
774
+ const entryPoint = (await submitter.getSupportedEntryPoints())[0];
775
+ const code = await publicClient.getBytecode({ address: sender });
776
+ const deployed = typeof code === 'string' &&
777
+ code !== '0x' &&
778
+ code.length > 2;
779
+ let nonce;
780
+ let factory;
781
+ let factoryData;
782
+ if (!deployed) {
783
+ if (!accountFactory) {
784
+ throw new Error('[SmoothSend AVAX] No bytecode at sender — pass accountFactory so the paymaster can sponsor deploy + call in one UserOp');
785
+ }
786
+ nonce = 0n;
787
+ factory = accountFactory;
788
+ factoryData = encodeCreateAccountFactoryData(ownerAddress, accountSalt);
789
+ }
790
+ else {
791
+ nonce = await readAvaxSenderNonce({
792
+ publicClient,
793
+ entryPointAddress: entryPoint,
794
+ sender,
795
+ });
796
+ }
797
+ let maxFeePerGas = 50n * 10n ** 9n;
798
+ let maxPriorityFeePerGas = 2n * 10n ** 9n;
799
+ try {
800
+ const est = await publicClient.estimateFeesPerGas();
801
+ if (est.maxFeePerGas)
802
+ maxFeePerGas = est.maxFeePerGas;
803
+ if (est.maxPriorityFeePerGas)
804
+ maxPriorityFeePerGas = est.maxPriorityFeePerGas;
805
+ }
806
+ catch {
807
+ // ignore and use fallback values
808
+ }
809
+ let callData;
810
+ if (params.calls && params.calls.length > 0) {
811
+ callData = encodeAvaxExecuteBatchCalldata(params.calls.map(c => c.to), params.calls.map(c => c.value ?? 0n), params.calls.map(c => c.data ?? '0x'));
812
+ }
813
+ else {
814
+ const target = params.call?.to ?? params.to;
815
+ if (!target)
816
+ throw new Error('[SmoothSend AVAX] No target address (to) provided');
817
+ callData = encodeAvaxExecuteCalldata(target, params.call?.value ?? params.value ?? 0n, params.call?.data ?? params.data ?? '0x');
818
+ }
819
+ const quote = await submitter.estimateUserPaysFee({
820
+ userOp: {
821
+ sender,
822
+ nonce: toHex(nonce),
823
+ callData,
824
+ maxFeePerGas: toHex(maxFeePerGas),
825
+ maxPriorityFeePerGas: toHex(maxPriorityFeePerGas),
826
+ ...(factory && factoryData ? { factory, factoryData } : {}),
827
+ },
828
+ paymaster: params.paymaster,
829
+ });
830
+ return {
831
+ entryPoint: quote.entryPoint,
832
+ feePreview: quote.feePreview,
833
+ exchangeRate: quote.exchangeRate,
834
+ };
835
+ }, [
836
+ accountFactory,
837
+ accountSalt,
838
+ publicClient,
839
+ smartAccountAddressProp,
840
+ submitter,
841
+ walletClient,
842
+ ]);
843
+ return {
844
+ submitter,
845
+ submitCall,
846
+ submitSponsoredUserOp,
847
+ estimateUserPaysFee,
848
+ paymasterAddress,
849
+ discoveredFactory: accountFactory ?? null,
850
+ };
534
851
  }
535
852
 
536
- export { AvaxSubmitter, ENTRY_POINT_V07_ADDRESS, HttpClient, SIMPLE_ACCOUNT_FACTORY_ABI, SmoothSendAvaxProvider, SmoothSendAvaxSubmitter, avaxExecuteAbi, createSmoothSendAvaxSubmitter, encodeAvaxExecuteCalldata, encodeCreateAccountFactoryData, fetchAvaxAaPublicDefaults, hashUserOperationAvax, predictSimpleAccountAddress, readAvaxSenderNonce, useSmoothSendAvax, useSmoothSendAvaxContext, userOperationAvaxToViem };
853
+ export { AvaxSubmitter, ENTRY_POINT_V07_ADDRESS, HttpClient, SIMPLE_ACCOUNT_FACTORY_ABI, SmoothSendAvaxClient, SmoothSendAvaxProvider, SmoothSendAvaxSubmitter, avaxExecuteAbi, createSmoothSendAvaxClient, createSmoothSendAvaxSubmitter, encodeAvaxExecuteCalldata, encodeCreateAccountFactoryData, fetchAvaxAaPublicDefaults, hashUserOperationAvax, predictSimpleAccountAddress, readAvaxSenderNonce, useSmoothSendAvax, useSmoothSendAvaxContext, userOperationAvaxToViem };
537
854
  //# sourceMappingURL=index.js.map