@aztec/wallet-sdk 0.0.1-commit.9d2bcf6d → 0.0.1-commit.9d619b6c6

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