@aztec/wallet-sdk 0.0.1-commit.d431d1c → 0.0.1-commit.d939eb5aa

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 (99) hide show
  1. package/README.md +217 -294
  2. package/dest/base-wallet/base_wallet.d.ts +86 -37
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +237 -69
  5. package/dest/base-wallet/index.d.ts +3 -2
  6. package/dest/base-wallet/index.d.ts.map +1 -1
  7. package/dest/base-wallet/index.js +1 -0
  8. package/dest/base-wallet/utils.d.ts +50 -0
  9. package/dest/base-wallet/utils.d.ts.map +1 -0
  10. package/dest/base-wallet/utils.js +133 -0
  11. package/dest/crypto.d.ts +97 -50
  12. package/dest/crypto.d.ts.map +1 -1
  13. package/dest/crypto.js +290 -108
  14. package/dest/emoji_alphabet.d.ts +35 -0
  15. package/dest/emoji_alphabet.d.ts.map +1 -0
  16. package/dest/emoji_alphabet.js +299 -0
  17. package/dest/extension/handlers/background_connection_handler.d.ts +158 -0
  18. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -0
  19. package/dest/extension/handlers/background_connection_handler.js +258 -0
  20. package/dest/extension/handlers/content_script_connection_handler.d.ts +56 -0
  21. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -0
  22. package/dest/extension/handlers/content_script_connection_handler.js +174 -0
  23. package/dest/extension/handlers/index.d.ts +12 -0
  24. package/dest/extension/handlers/index.d.ts.map +1 -0
  25. package/dest/extension/handlers/index.js +10 -0
  26. package/dest/extension/handlers/internal_message_types.d.ts +63 -0
  27. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -0
  28. package/dest/extension/handlers/internal_message_types.js +22 -0
  29. package/dest/extension/provider/extension_provider.d.ts +107 -0
  30. package/dest/extension/provider/extension_provider.d.ts.map +1 -0
  31. package/dest/extension/provider/extension_provider.js +160 -0
  32. package/dest/extension/provider/extension_wallet.d.ts +129 -0
  33. package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
  34. package/dest/{providers/extension → extension/provider}/extension_wallet.js +57 -97
  35. package/dest/extension/provider/index.d.ts +3 -0
  36. package/dest/extension/provider/index.d.ts.map +1 -0
  37. package/dest/{providers/extension → extension/provider}/index.js +0 -2
  38. package/dest/iframe/handlers/iframe_connection_handler.d.ts +118 -0
  39. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -0
  40. package/dest/iframe/handlers/iframe_connection_handler.js +228 -0
  41. package/dest/iframe/handlers/index.d.ts +2 -0
  42. package/dest/iframe/handlers/index.d.ts.map +1 -0
  43. package/dest/iframe/handlers/index.js +1 -0
  44. package/dest/iframe/provider/iframe_discovery.d.ts +25 -0
  45. package/dest/iframe/provider/iframe_discovery.d.ts.map +1 -0
  46. package/dest/iframe/provider/iframe_discovery.js +167 -0
  47. package/dest/iframe/provider/iframe_provider.d.ts +65 -0
  48. package/dest/iframe/provider/iframe_provider.d.ts.map +1 -0
  49. package/dest/iframe/provider/iframe_provider.js +257 -0
  50. package/dest/iframe/provider/iframe_wallet.d.ts +68 -0
  51. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -0
  52. package/dest/iframe/provider/iframe_wallet.js +200 -0
  53. package/dest/iframe/provider/index.d.ts +4 -0
  54. package/dest/iframe/provider/index.d.ts.map +1 -0
  55. package/dest/iframe/provider/index.js +3 -0
  56. package/dest/manager/index.d.ts +2 -8
  57. package/dest/manager/index.d.ts.map +1 -1
  58. package/dest/manager/index.js +0 -6
  59. package/dest/manager/types.d.ts +92 -9
  60. package/dest/manager/types.d.ts.map +1 -1
  61. package/dest/manager/types.js +17 -1
  62. package/dest/manager/wallet_manager.d.ts +50 -7
  63. package/dest/manager/wallet_manager.d.ts.map +1 -1
  64. package/dest/manager/wallet_manager.js +203 -43
  65. package/dest/types.d.ts +55 -12
  66. package/dest/types.d.ts.map +1 -1
  67. package/dest/types.js +7 -2
  68. package/package.json +21 -10
  69. package/src/base-wallet/base_wallet.ts +334 -126
  70. package/src/base-wallet/index.ts +7 -1
  71. package/src/base-wallet/utils.ts +240 -0
  72. package/src/crypto.ts +341 -113
  73. package/src/emoji_alphabet.ts +317 -0
  74. package/src/extension/handlers/background_connection_handler.ts +423 -0
  75. package/src/extension/handlers/content_script_connection_handler.ts +246 -0
  76. package/src/extension/handlers/index.ts +25 -0
  77. package/src/extension/handlers/internal_message_types.ts +69 -0
  78. package/src/extension/provider/extension_provider.ts +233 -0
  79. package/src/{providers/extension → extension/provider}/extension_wallet.ts +61 -116
  80. package/src/extension/provider/index.ts +7 -0
  81. package/src/iframe/handlers/iframe_connection_handler.ts +328 -0
  82. package/src/iframe/handlers/index.ts +7 -0
  83. package/src/iframe/provider/iframe_discovery.ts +185 -0
  84. package/src/iframe/provider/iframe_provider.ts +331 -0
  85. package/src/iframe/provider/iframe_wallet.ts +229 -0
  86. package/src/iframe/provider/index.ts +3 -0
  87. package/src/manager/index.ts +2 -10
  88. package/src/manager/types.ts +95 -8
  89. package/src/manager/wallet_manager.ts +223 -45
  90. package/src/types.ts +57 -10
  91. package/dest/providers/extension/extension_provider.d.ts +0 -63
  92. package/dest/providers/extension/extension_provider.d.ts.map +0 -1
  93. package/dest/providers/extension/extension_provider.js +0 -124
  94. package/dest/providers/extension/extension_wallet.d.ts +0 -155
  95. package/dest/providers/extension/extension_wallet.d.ts.map +0 -1
  96. package/dest/providers/extension/index.d.ts +0 -6
  97. package/dest/providers/extension/index.d.ts.map +0 -1
  98. package/src/providers/extension/extension_provider.ts +0 -167
  99. package/src/providers/extension/index.ts +0 -5
@@ -1,28 +1,37 @@
1
- import type { Account } from '@aztec/aztec.js/account';
1
+ import type { Account, NoFrom } from '@aztec/aztec.js/account';
2
+ import { NO_FROM } from '@aztec/aztec.js/account';
2
3
  import type { CallIntent, IntentInnerHash } from '@aztec/aztec.js/authorization';
4
+ import {
5
+ type InteractionWaitOptions,
6
+ NO_WAIT,
7
+ type SendReturn,
8
+ extractOffchainOutput,
9
+ } from '@aztec/aztec.js/contracts';
3
10
  import type { FeePaymentMethod } from '@aztec/aztec.js/fee';
4
- import type {
5
- Aliased,
6
- BatchResults,
7
- BatchedMethod,
8
- PrivateEvent,
9
- PrivateEventFilter,
10
- ProfileOptions,
11
- SendOptions,
12
- SimulateOptions,
13
- Wallet,
14
- } from '@aztec/aztec.js/wallet';
11
+ import { waitForTx } from '@aztec/aztec.js/node';
15
12
  import {
16
- GAS_ESTIMATION_DA_GAS_LIMIT,
17
- GAS_ESTIMATION_L2_GAS_LIMIT,
18
- GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT,
19
- GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT,
20
- } from '@aztec/constants';
13
+ type Aliased,
14
+ type AppCapabilities,
15
+ type BatchResults,
16
+ type BatchedMethod,
17
+ ContractInitializationStatus,
18
+ type ExecuteUtilityOptions,
19
+ type PrivateEvent,
20
+ type PrivateEventFilter,
21
+ type ProfileOptions,
22
+ type SendOptions,
23
+ type SimulateOptions,
24
+ TxSimulationResultWithAppOffset,
25
+ type Wallet,
26
+ type WalletCapabilities,
27
+ } from '@aztec/aztec.js/wallet';
21
28
  import { AccountFeePaymentMethodOptions, type DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
29
+ import { DefaultEntrypoint } from '@aztec/entrypoints/default';
22
30
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
23
31
  import { Fr } from '@aztec/foundation/curves/bn254';
24
32
  import { createLogger } from '@aztec/foundation/log';
25
33
  import type { FieldsOf } from '@aztec/foundation/types';
34
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
26
35
  import type { PXE, PackedPrivateEvent } from '@aztec/pxe/server';
27
36
  import {
28
37
  type ContractArtifact,
@@ -31,28 +40,32 @@ import {
31
40
  decodeFromAbi,
32
41
  } from '@aztec/stdlib/abi';
33
42
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
34
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
43
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
35
44
  import {
36
45
  type ContractInstanceWithAddress,
37
46
  computePartialAddress,
38
47
  getContractClassFromArtifact,
39
48
  } from '@aztec/stdlib/contract';
40
49
  import { SimulationError } from '@aztec/stdlib/errors';
41
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
42
- import { siloNullifier } from '@aztec/stdlib/hash';
50
+ import { Gas, GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
51
+ import {
52
+ computeSiloedPrivateInitializationNullifier,
53
+ computeSiloedPublicInitializationNullifier,
54
+ } from '@aztec/stdlib/hash';
43
55
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
44
- import type {
45
- TxExecutionRequest,
46
- TxHash,
47
- TxProfileResult,
48
- TxReceipt,
49
- TxSimulationResult,
50
- UtilitySimulationResult,
56
+ import {
57
+ BlockHeader,
58
+ ExecutionPayload,
59
+ type TxExecutionRequest,
60
+ type TxProfileResult,
61
+ type UtilityExecutionResult,
62
+ mergeExecutionPayloads,
51
63
  } from '@aztec/stdlib/tx';
52
- import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
53
64
 
54
65
  import { inspect } from 'util';
55
66
 
67
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
68
+
56
69
  /**
57
70
  * Options to configure fee payment for a transaction
58
71
  */
@@ -63,17 +76,41 @@ export type FeeOptions = {
63
76
  */
64
77
  walletFeePaymentMethod?: FeePaymentMethod;
65
78
  /** Configuration options for the account to properly handle the selected fee payment method */
66
- accountFeePaymentMethodOptions: AccountFeePaymentMethodOptions;
79
+ accountFeePaymentMethodOptions?: AccountFeePaymentMethodOptions;
67
80
  /** The gas settings to use for the transaction */
68
81
  gasSettings: GasSettings;
69
82
  };
70
83
 
84
+ /** Options for `simulateViaEntrypoint`. */
85
+ export type SimulateViaEntrypointOptions = Pick<
86
+ SimulateOptions,
87
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement'
88
+ > & {
89
+ /** Fee options for the entrypoint */
90
+ feeOptions: FeeOptions;
91
+ };
92
+
93
+ /** Options for `completeFeeOptions`. */
94
+ export type CompleteFeeOptionsConfig = {
95
+ /** The address where the transaction is being sent from. */
96
+ from: AztecAddress | NoFrom;
97
+ /** The address paying for fees (if any fee payment method is embedded in the execution payload). */
98
+ feePayer?: AztecAddress;
99
+ /** User-provided partial gas settings. */
100
+ gasSettings?: Partial<FieldsOf<GasSettings>>;
101
+ /** If true, returns gas settings with high gas limits for estimation. If false, uses fallback limits. */
102
+ forEstimation?: boolean;
103
+ /**
104
+ * Assumed network congestion level for fee prediction. Controls how aggressively the wallet
105
+ * estimates future fees. Defaults to Limit (worst case) when not specified.
106
+ */
107
+ congestionEstimate?: ManaUsageEstimate;
108
+ };
109
+
71
110
  /**
72
111
  * A base class for Wallet implementations
73
112
  */
74
113
  export abstract class BaseWallet implements Wallet {
75
- protected log = createLogger('wallet-sdk:base_wallet');
76
-
77
114
  protected minFeePadding = 0.5;
78
115
  protected cancellableTransactions = false;
79
116
 
@@ -81,8 +118,15 @@ export abstract class BaseWallet implements Wallet {
81
118
  protected constructor(
82
119
  protected readonly pxe: PXE,
83
120
  protected readonly aztecNode: AztecNode,
121
+ protected log = createLogger('wallet-sdk:base_wallet'),
84
122
  ) {}
85
123
 
124
+ protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
125
+ const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
126
+ const scopeSet = new Set(allScopes.map(address => address.toString()));
127
+ return [...scopeSet].map(AztecAddress.fromString);
128
+ }
129
+
86
130
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
87
131
 
88
132
  abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
@@ -106,26 +150,33 @@ export abstract class BaseWallet implements Wallet {
106
150
 
107
151
  protected async createTxExecutionRequestFromPayloadAndFee(
108
152
  executionPayload: ExecutionPayload,
109
- from: AztecAddress,
153
+ from: AztecAddress | NoFrom,
110
154
  feeOptions: FeeOptions,
111
155
  ): Promise<TxExecutionRequest> {
112
156
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
113
- const executionOptions: DefaultAccountEntrypointOptions = {
114
- txNonce: Fr.random(),
115
- cancellable: this.cancellableTransactions,
116
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
117
- };
118
157
  const finalExecutionPayload = feeExecutionPayload
119
158
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
120
159
  : executionPayload;
121
- const fromAccount = await this.getAccountFromAddress(from);
122
160
  const chainInfo = await this.getChainInfo();
123
- return fromAccount.createTxExecutionRequest(
124
- finalExecutionPayload,
125
- feeOptions.gasSettings,
126
- chainInfo,
127
- executionOptions,
128
- );
161
+
162
+ if (from === NO_FROM) {
163
+ const entrypoint = new DefaultEntrypoint();
164
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
165
+ } else {
166
+ const fromAccount = await this.getAccountFromAddress(from);
167
+ const executionOptions: DefaultAccountEntrypointOptions = {
168
+ txNonce: Fr.random(),
169
+ cancellable: this.cancellableTransactions,
170
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
171
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
172
+ };
173
+ return fromAccount.createTxExecutionRequest(
174
+ finalExecutionPayload,
175
+ feeOptions.gasSettings,
176
+ chainInfo,
177
+ executionOptions,
178
+ );
179
+ }
129
180
  }
130
181
 
131
182
  public async createAuthWit(
@@ -137,6 +188,23 @@ export abstract class BaseWallet implements Wallet {
137
188
  return account.createAuthWit(messageHashOrIntent, chainInfo);
138
189
  }
139
190
 
191
+ /**
192
+ * Request capabilities from the wallet.
193
+ *
194
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
195
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
196
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
197
+ * friction by allowing apps to request permissions upfront.
198
+ *
199
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
200
+ * while the feature stabilizes.
201
+ *
202
+ * @param _manifest - Application capability manifest declaring what operations the app needs
203
+ */
204
+ public requestCapabilities(_manifest: AppCapabilities): Promise<WalletCapabilities> {
205
+ throw new Error('Not implemented');
206
+ }
207
+
140
208
  public async batch<const T extends readonly BatchedMethod[]>(methods: T): Promise<BatchResults<T>> {
141
209
  const results: any[] = [];
142
210
  for (const method of methods) {
@@ -157,31 +225,39 @@ export abstract class BaseWallet implements Wallet {
157
225
 
158
226
  /**
159
227
  * Completes partial user-provided fee options with wallet defaults.
160
- * @param from - The address where the transaction is being sent from
161
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
162
- * @param gasSettings - User-provided partial gas settings
163
- * @returns - Complete fee options that can be used to create a transaction execution request
228
+ * @param config - Fee completion config.
164
229
  */
165
- protected async completeFeeOptions(
166
- from: AztecAddress,
167
- feePayer?: AztecAddress,
168
- gasSettings?: Partial<FieldsOf<GasSettings>>,
169
- ): Promise<FeeOptions> {
230
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
231
+ const { from, feePayer, gasSettings, forEstimation, congestionEstimate } = config;
170
232
  const maxFeesPerGas =
171
- gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
233
+ gasSettings?.maxFeesPerGas ?? (await this.getMinFees(congestionEstimate)).mul(1 + this.minFeePadding);
172
234
  let accountFeePaymentMethodOptions;
173
- // The transaction does not include a fee payment method, so we set the flag
174
- // for the account to use its fee juice balance
175
- if (!feePayer) {
176
- accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
177
- } else {
178
- // The transaction includes fee payment method, so we check if we are the fee payer for it
179
- // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
180
- accountFeePaymentMethodOptions = from.equals(feePayer)
181
- ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
182
- : AccountFeePaymentMethodOptions.EXTERNAL;
235
+ // If from is an address, we need to determine the appropriate fee payment method options for the
236
+ // account contract entrypoint to use
237
+ if (from !== NO_FROM) {
238
+ if (!feePayer) {
239
+ // The transaction does not include a fee payment method, so we set the flag
240
+ // for the account to use its fee juice balance
241
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
242
+ } else {
243
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
244
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
245
+ accountFeePaymentMethodOptions = from.equals(feePayer)
246
+ ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
247
+ : AccountFeePaymentMethodOptions.EXTERNAL;
248
+ }
183
249
  }
184
- const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
250
+ const gasSettingsOverrides = {
251
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
252
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
253
+ maxFeesPerGas,
254
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty(),
255
+ };
256
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
257
+ // When sending for real, use protocol max limits that the network will actually accept.
258
+ const fullGasSettings = forEstimation
259
+ ? GasSettings.forEstimation(gasSettingsOverrides)
260
+ : GasSettings.fallback(gasSettingsOverrides);
185
261
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
186
262
  return {
187
263
  gasSettings: fullGasSettings,
@@ -191,34 +267,25 @@ export abstract class BaseWallet implements Wallet {
191
267
  }
192
268
 
193
269
  /**
194
- * Completes partial user-provided fee options with unreasonably high gas limits
195
- * for gas estimation. Uses the same logic as completeFeeOptions but sets high limits
196
- * to avoid running out of gas during estimation.
197
- * @param from - The address where the transaction is being sent from
198
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
199
- * @param gasSettings - User-provided partial gas settings
270
+ * Returns the worst-case min fee across predicted future slots.
271
+ * Falls back to getCurrentMinFees if the node doesn't support getPredictedMinFees.
272
+ * @param estimate - The mana usage estimate to use for fee prediction. Defaults to Limit for conservative estimation.
200
273
  */
201
- protected async completeFeeOptionsForEstimation(
202
- from: AztecAddress,
203
- feePayer?: AztecAddress,
204
- gasSettings?: Partial<FieldsOf<GasSettings>>,
205
- ) {
206
- const defaultFeeOptions = await this.completeFeeOptions(from, feePayer, gasSettings);
207
- const {
208
- gasSettings: { maxFeesPerGas, maxPriorityFeesPerGas },
209
- } = defaultFeeOptions;
210
- // Use unrealistically high gas limits for estimation to avoid running out of gas.
211
- // They will be tuned down after the simulation.
212
- const gasSettingsForEstimation = new GasSettings(
213
- new Gas(GAS_ESTIMATION_DA_GAS_LIMIT, GAS_ESTIMATION_L2_GAS_LIMIT),
214
- new Gas(GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT),
215
- maxFeesPerGas,
216
- maxPriorityFeesPerGas,
217
- );
218
- return {
219
- ...defaultFeeOptions,
220
- gasSettings: gasSettingsForEstimation,
221
- };
274
+ protected async getMinFees(estimate: ManaUsageEstimate = ManaUsageEstimate.Limit): Promise<GasFees> {
275
+ try {
276
+ const predicted = await this.aztecNode.getPredictedMinFees(estimate);
277
+ if (predicted.length === 0) {
278
+ return this.aztecNode.getCurrentMinFees();
279
+ }
280
+ return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
281
+ } catch (err: any) {
282
+ // Fallback for old nodes that don't support getPredictedMinFees.
283
+ // Only fall back on method-not-found errors (JSON-RPC code -32601); rethrow others.
284
+ if (err?.cause?.code === -32601 || err?.message?.includes('Method not found')) {
285
+ return this.aztecNode.getCurrentMinFees();
286
+ }
287
+ throw err;
288
+ }
222
289
  }
223
290
 
224
291
  registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
@@ -263,29 +330,132 @@ export abstract class BaseWallet implements Wallet {
263
330
  return instance;
264
331
  }
265
332
 
266
- async simulateTx(executionPayload: ExecutionPayload, opts: SimulateOptions): Promise<TxSimulationResult> {
267
- const feeOptions = opts.fee?.estimateGas
268
- ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings)
269
- : await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
270
- const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
271
- return this.pxe.simulateTx(
272
- txRequest,
273
- true /* simulatePublic */,
274
- opts?.skipTxValidation,
275
- opts?.skipFeeEnforcement ?? true,
333
+ /**
334
+ * Simulates calls through the standard PXE path (account entrypoint).
335
+ * @param executionPayload - The execution payload to simulate.
336
+ * @param opts - Simulation options.
337
+ */
338
+ protected async simulateViaEntrypoint(executionPayload: ExecutionPayload, opts: SimulateViaEntrypointOptions) {
339
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(
340
+ executionPayload,
341
+ opts.from,
342
+ opts.feeOptions,
276
343
  );
344
+ const result = await this.pxe.simulateTx(txRequest, {
345
+ simulatePublic: true,
346
+ skipTxValidation: opts.skipTxValidation,
347
+ skipFeeEnforcement: opts.skipFeeEnforcement,
348
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
349
+ });
350
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
351
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
352
+ }
353
+
354
+ /**
355
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
356
+ * calls, N+1 = app).
357
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
358
+ * @param feeOptions - Fee options containing the wallet fee payment method.
359
+ */
360
+ protected async computeAppCallOffset(from: AztecAddress | NoFrom, feeOptions: FeeOptions): Promise<number> {
361
+ if (from === NO_FROM) {
362
+ return 0;
363
+ }
364
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
365
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
366
+ }
367
+
368
+ /**
369
+ * Simulates a transaction, optimizing leading public static calls by running them directly
370
+ * on the node while sending the remaining calls through the standard PXE path.
371
+ * Return values from both paths are merged back in original call order.
372
+ * @param executionPayload - The execution payload to simulate.
373
+ * @param opts - Simulation options (from address, fee settings, etc.).
374
+ * @returns The merged simulation result.
375
+ */
376
+ async simulateTx(
377
+ executionPayload: ExecutionPayload,
378
+ opts: SimulateOptions,
379
+ ): Promise<TxSimulationResultWithAppOffset> {
380
+ const feeOptions = await this.completeFeeOptions({
381
+ from: opts.from,
382
+ feePayer: executionPayload.feePayer,
383
+ gasSettings: opts.fee?.gasSettings,
384
+ forEstimation: true,
385
+ congestionEstimate: opts.fee?.congestionEstimate,
386
+ });
387
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
388
+ const remainingPayload = { ...executionPayload, calls: remainingCalls };
389
+
390
+ const chainInfo = await this.getChainInfo();
391
+ let blockHeader: BlockHeader;
392
+ // PXE might not be synced yet, so we pull the latest header from the node
393
+ // To keep things consistent, we'll always try with PXE first
394
+ try {
395
+ blockHeader = await this.pxe.getSyncedBlockHeader();
396
+ } catch {
397
+ blockHeader = (await this.aztecNode.getBlockHeader())!;
398
+ }
399
+
400
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
401
+ const [optimizedResults, normalResult] = await Promise.all([
402
+ optimizableCalls.length > 0
403
+ ? simulateViaNode(
404
+ this.aztecNode,
405
+ optimizableCalls,
406
+ simulationOrigin,
407
+ chainInfo,
408
+ feeOptions.gasSettings,
409
+ blockHeader,
410
+ opts.skipFeeEnforcement ?? true,
411
+ this.getContractName.bind(this),
412
+ )
413
+ : Promise.resolve([]),
414
+ remainingCalls.length > 0
415
+ ? this.simulateViaEntrypoint(remainingPayload, {
416
+ from: opts.from,
417
+ feeOptions,
418
+ additionalScopes: opts.additionalScopes,
419
+ skipTxValidation: opts.skipTxValidation,
420
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
421
+ })
422
+ : Promise.resolve(null),
423
+ ]);
424
+
425
+ return buildMergedSimulationResult(optimizedResults, normalResult);
277
426
  }
278
427
 
279
428
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
280
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
429
+ const feeOptions = await this.completeFeeOptions({
430
+ from: opts.from,
431
+ feePayer: executionPayload.feePayer,
432
+ gasSettings: opts.fee?.gasSettings,
433
+ congestionEstimate: opts.fee?.congestionEstimate,
434
+ });
281
435
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
282
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
436
+ return this.pxe.profileTx(txRequest, {
437
+ profileMode: opts.profileMode,
438
+ skipProofGeneration: opts.skipProofGeneration ?? true,
439
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
440
+ });
283
441
  }
284
442
 
285
- async sendTx(executionPayload: ExecutionPayload, opts: SendOptions): Promise<TxHash> {
286
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
443
+ public async sendTx<W extends InteractionWaitOptions = undefined>(
444
+ executionPayload: ExecutionPayload,
445
+ opts: SendOptions<W>,
446
+ ): Promise<SendReturn<W>> {
447
+ const feeOptions = await this.completeFeeOptions({
448
+ from: opts.from,
449
+ feePayer: executionPayload.feePayer,
450
+ gasSettings: opts.fee?.gasSettings,
451
+ congestionEstimate: opts.fee?.congestionEstimate,
452
+ });
287
453
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
288
- const provenTx = await this.pxe.proveTx(txRequest);
454
+ const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
455
+ const offchainOutput = extractOffchainOutput(
456
+ provenTx.getOffchainEffects(),
457
+ provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
458
+ );
289
459
  const tx = await provenTx.toTx();
290
460
  const txHash = tx.getTxHash();
291
461
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -296,7 +466,35 @@ export abstract class BaseWallet implements Wallet {
296
466
  throw this.contextualizeError(err, inspect(tx));
297
467
  });
298
468
  this.log.info(`Sent transaction ${txHash}`);
299
- return txHash;
469
+
470
+ // If wait is NO_WAIT, return txHash immediately
471
+ if (opts.wait === NO_WAIT) {
472
+ return { txHash, ...offchainOutput } as SendReturn<W>;
473
+ }
474
+
475
+ // Otherwise, wait for the full receipt (default behavior on wait: undefined)
476
+ const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
477
+ const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
478
+
479
+ // Display debug logs from public execution if present (served in test mode only)
480
+ if (receipt.debugLogs?.length) {
481
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
482
+ }
483
+
484
+ return { receipt, ...offchainOutput } as SendReturn<W>;
485
+ }
486
+
487
+ /**
488
+ * Resolves a contract address to a human-readable name via PXE, if available.
489
+ * @param address - The contract address to resolve.
490
+ */
491
+ protected async getContractName(address: AztecAddress): Promise<string | undefined> {
492
+ const instance = await this.pxe.getContractInstance(address);
493
+ if (!instance) {
494
+ return undefined;
495
+ }
496
+ const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
497
+ return artifact?.name;
300
498
  }
301
499
 
302
500
  protected contextualizeError(err: Error, ...context: string[]): Error {
@@ -313,12 +511,8 @@ export abstract class BaseWallet implements Wallet {
313
511
  return err;
314
512
  }
315
513
 
316
- simulateUtility(call: FunctionCall, authwits?: AuthWitness[]): Promise<UtilitySimulationResult> {
317
- return this.pxe.simulateUtility(call, authwits);
318
- }
319
-
320
- getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
321
- return this.aztecNode.getTxReceipt(txHash);
514
+ executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
515
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: opts.scopes });
322
516
  }
323
517
 
324
518
  async getPrivateEvents<T>(
@@ -341,26 +535,40 @@ export abstract class BaseWallet implements Wallet {
341
535
  return decodedEvents;
342
536
  }
343
537
 
538
+ /**
539
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
540
+ * @param address - The contract address to query.
541
+ */
344
542
  async getContractMetadata(address: AztecAddress) {
345
543
  const instance = await this.pxe.getContractInstance(address);
346
- const initNullifier = await siloNullifier(address, address.toField());
347
- const publiclyRegisteredContract = await this.aztecNode.getContract(address);
348
- const [initNullifierMembershipWitness, publiclyRegisteredContractClass] = await Promise.all([
349
- this.aztecNode.getNullifierMembershipWitness('latest', initNullifier),
350
- publiclyRegisteredContract
351
- ? this.aztecNode.getContractClass(
352
- publiclyRegisteredContract.currentContractClassId || instance?.currentContractClassId,
353
- )
354
- : undefined,
355
- ]);
544
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
545
+
546
+ let initializationStatus: ContractInitializationStatus;
547
+ if (instance) {
548
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
549
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
550
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
551
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
552
+ initializationStatus = witness
553
+ ? ContractInitializationStatus.INITIALIZED
554
+ : ContractInitializationStatus.UNINITIALIZED;
555
+ } else {
556
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
557
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
558
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
559
+ // uninitialized.
560
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
561
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
562
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
563
+ }
564
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
356
565
  const isContractUpdated =
357
566
  publiclyRegisteredContract &&
358
567
  !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
359
568
  return {
360
569
  instance: instance ?? undefined,
361
- isContractInitialized: !!initNullifierMembershipWitness,
570
+ initializationStatus,
362
571
  isContractPublished: !!publiclyRegisteredContract,
363
- isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass,
364
572
  isContractUpdated: !!isContractUpdated,
365
573
  updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined,
366
574
  };
@@ -1 +1,7 @@
1
- export { BaseWallet, type FeeOptions } from './base_wallet.js';
1
+ export {
2
+ BaseWallet,
3
+ type CompleteFeeOptionsConfig,
4
+ type FeeOptions,
5
+ type SimulateViaEntrypointOptions,
6
+ } from './base_wallet.js';
7
+ export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';