@aztec/wallet-sdk 0.0.1-commit.e6bd8901 → 0.0.1-commit.ec7ac5448

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 +74 -35
  2. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  3. package/dest/base-wallet/base_wallet.js +209 -69
  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 +293 -123
  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,30 +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
- BatchResults,
9
- BatchedMethod,
10
- PrivateEvent,
11
- PrivateEventFilter,
12
- ProfileOptions,
13
- SendOptions,
14
- SimulateOptions,
15
- Wallet,
16
- } from '@aztec/aztec.js/wallet';
17
12
  import {
18
- GAS_ESTIMATION_DA_GAS_LIMIT,
19
- GAS_ESTIMATION_L2_GAS_LIMIT,
20
- GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT,
21
- GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT,
22
- } 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';
23
28
  import { AccountFeePaymentMethodOptions, type DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
29
+ import { DefaultEntrypoint } from '@aztec/entrypoints/default';
24
30
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
25
31
  import { Fr } from '@aztec/foundation/curves/bn254';
26
32
  import { createLogger } from '@aztec/foundation/log';
27
33
  import type { FieldsOf } from '@aztec/foundation/types';
34
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
28
35
  import type { PXE, PackedPrivateEvent } from '@aztec/pxe/server';
29
36
  import {
30
37
  type ContractArtifact,
@@ -33,26 +40,31 @@ import {
33
40
  decodeFromAbi,
34
41
  } from '@aztec/stdlib/abi';
35
42
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
36
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
43
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
37
44
  import {
38
45
  type ContractInstanceWithAddress,
39
46
  computePartialAddress,
40
47
  getContractClassFromArtifact,
41
48
  } from '@aztec/stdlib/contract';
42
49
  import { SimulationError } from '@aztec/stdlib/errors';
43
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
44
- import { siloNullifier } from '@aztec/stdlib/hash';
50
+ import { Gas, GasFees, GasSettings } from '@aztec/stdlib/gas';
51
+ import {
52
+ computeSiloedPrivateInitializationNullifier,
53
+ computeSiloedPublicInitializationNullifier,
54
+ } from '@aztec/stdlib/hash';
45
55
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
46
- import type {
47
- TxExecutionRequest,
48
- TxProfileResult,
49
- TxSimulationResult,
50
- UtilitySimulationResult,
56
+ import {
57
+ BlockHeader,
58
+ type TxExecutionRequest,
59
+ type TxProfileResult,
60
+ type UtilityExecutionResult,
51
61
  } from '@aztec/stdlib/tx';
52
62
  import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
53
63
 
54
64
  import { inspect } from 'util';
55
65
 
66
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
67
+
56
68
  /**
57
69
  * Options to configure fee payment for a transaction
58
70
  */
@@ -63,17 +75,36 @@ export type FeeOptions = {
63
75
  */
64
76
  walletFeePaymentMethod?: FeePaymentMethod;
65
77
  /** Configuration options for the account to properly handle the selected fee payment method */
66
- accountFeePaymentMethodOptions: AccountFeePaymentMethodOptions;
78
+ accountFeePaymentMethodOptions?: AccountFeePaymentMethodOptions;
67
79
  /** The gas settings to use for the transaction */
68
80
  gasSettings: GasSettings;
69
81
  };
70
82
 
83
+ /** Options for `simulateViaEntrypoint`. */
84
+ export type SimulateViaEntrypointOptions = Pick<
85
+ SimulateOptions,
86
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement'
87
+ > & {
88
+ /** Fee options for the entrypoint */
89
+ feeOptions: FeeOptions;
90
+ };
91
+
92
+ /** Options for `completeFeeOptions`. */
93
+ export type CompleteFeeOptionsConfig = {
94
+ /** The address where the transaction is being sent from. */
95
+ from: AztecAddress | NoFrom;
96
+ /** The address paying for fees (if any fee payment method is embedded in the execution payload). */
97
+ feePayer?: AztecAddress;
98
+ /** User-provided partial gas settings. */
99
+ gasSettings?: Partial<FieldsOf<GasSettings>>;
100
+ /** If true, returns gas settings with high gas limits for estimation. If false, uses fallback limits. */
101
+ forEstimation?: boolean;
102
+ };
103
+
71
104
  /**
72
105
  * A base class for Wallet implementations
73
106
  */
74
107
  export abstract class BaseWallet implements Wallet {
75
- protected log = createLogger('wallet-sdk:base_wallet');
76
-
77
108
  protected minFeePadding = 0.5;
78
109
  protected cancellableTransactions = false;
79
110
 
@@ -81,8 +112,15 @@ export abstract class BaseWallet implements Wallet {
81
112
  protected constructor(
82
113
  protected readonly pxe: PXE,
83
114
  protected readonly aztecNode: AztecNode,
115
+ protected log = createLogger('wallet-sdk:base_wallet'),
84
116
  ) {}
85
117
 
118
+ protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
119
+ const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
120
+ const scopeSet = new Set(allScopes.map(address => address.toString()));
121
+ return [...scopeSet].map(AztecAddress.fromString);
122
+ }
123
+
86
124
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
87
125
 
88
126
  abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
@@ -106,26 +144,33 @@ export abstract class BaseWallet implements Wallet {
106
144
 
107
145
  protected async createTxExecutionRequestFromPayloadAndFee(
108
146
  executionPayload: ExecutionPayload,
109
- from: AztecAddress,
147
+ from: AztecAddress | NoFrom,
110
148
  feeOptions: FeeOptions,
111
149
  ): Promise<TxExecutionRequest> {
112
150
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
113
- const executionOptions: DefaultAccountEntrypointOptions = {
114
- txNonce: Fr.random(),
115
- cancellable: this.cancellableTransactions,
116
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
117
- };
118
151
  const finalExecutionPayload = feeExecutionPayload
119
152
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
120
153
  : executionPayload;
121
- const fromAccount = await this.getAccountFromAddress(from);
122
154
  const chainInfo = await this.getChainInfo();
123
- return fromAccount.createTxExecutionRequest(
124
- finalExecutionPayload,
125
- feeOptions.gasSettings,
126
- chainInfo,
127
- executionOptions,
128
- );
155
+
156
+ if (from === NO_FROM) {
157
+ const entrypoint = new DefaultEntrypoint();
158
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
159
+ } else {
160
+ const fromAccount = await this.getAccountFromAddress(from);
161
+ const executionOptions: DefaultAccountEntrypointOptions = {
162
+ txNonce: Fr.random(),
163
+ cancellable: this.cancellableTransactions,
164
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
165
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
166
+ };
167
+ return fromAccount.createTxExecutionRequest(
168
+ finalExecutionPayload,
169
+ feeOptions.gasSettings,
170
+ chainInfo,
171
+ executionOptions,
172
+ );
173
+ }
129
174
  }
130
175
 
131
176
  public async createAuthWit(
@@ -137,6 +182,23 @@ export abstract class BaseWallet implements Wallet {
137
182
  return account.createAuthWit(messageHashOrIntent, chainInfo);
138
183
  }
139
184
 
185
+ /**
186
+ * Request capabilities from the wallet.
187
+ *
188
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
189
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
190
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
191
+ * friction by allowing apps to request permissions upfront.
192
+ *
193
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
194
+ * while the feature stabilizes.
195
+ *
196
+ * @param _manifest - Application capability manifest declaring what operations the app needs
197
+ */
198
+ public requestCapabilities(_manifest: AppCapabilities): Promise<WalletCapabilities> {
199
+ throw new Error('Not implemented');
200
+ }
201
+
140
202
  public async batch<const T extends readonly BatchedMethod[]>(methods: T): Promise<BatchResults<T>> {
141
203
  const results: any[] = [];
142
204
  for (const method of methods) {
@@ -157,31 +219,39 @@ export abstract class BaseWallet implements Wallet {
157
219
 
158
220
  /**
159
221
  * 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
222
+ * @param config - Fee completion config.
164
223
  */
165
- protected async completeFeeOptions(
166
- from: AztecAddress,
167
- feePayer?: AztecAddress,
168
- gasSettings?: Partial<FieldsOf<GasSettings>>,
169
- ): Promise<FeeOptions> {
224
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
225
+ const { from, feePayer, gasSettings, forEstimation } = config;
170
226
  const maxFeesPerGas =
171
227
  gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
172
228
  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;
229
+ // If from is an address, we need to determine the appropriate fee payment method options for the
230
+ // account contract entrypoint to use
231
+ if (from !== NO_FROM) {
232
+ if (!feePayer) {
233
+ // The transaction does not include a fee payment method, so we set the flag
234
+ // for the account to use its fee juice balance
235
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
236
+ } else {
237
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
238
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
239
+ accountFeePaymentMethodOptions = from.equals(feePayer)
240
+ ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
241
+ : AccountFeePaymentMethodOptions.EXTERNAL;
242
+ }
183
243
  }
184
- const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
244
+ const gasSettingsOverrides = {
245
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
246
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
247
+ maxFeesPerGas,
248
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty(),
249
+ };
250
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
251
+ // When sending for real, use protocol max limits that the network will actually accept.
252
+ const fullGasSettings = forEstimation
253
+ ? GasSettings.forEstimation(gasSettingsOverrides)
254
+ : GasSettings.fallback(gasSettingsOverrides);
185
255
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
186
256
  return {
187
257
  gasSettings: fullGasSettings,
@@ -190,37 +260,6 @@ export abstract class BaseWallet implements Wallet {
190
260
  };
191
261
  }
192
262
 
193
- /**
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
200
- */
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
- };
222
- }
223
-
224
263
  registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
225
264
  return this.pxe.registerSender(address);
226
265
  }
@@ -263,32 +302,129 @@ export abstract class BaseWallet implements Wallet {
263
302
  return instance;
264
303
  }
265
304
 
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,
305
+ /**
306
+ * Simulates calls through the standard PXE path (account entrypoint).
307
+ * @param executionPayload - The execution payload to simulate.
308
+ * @param opts - Simulation options.
309
+ */
310
+ protected async simulateViaEntrypoint(executionPayload: ExecutionPayload, opts: SimulateViaEntrypointOptions) {
311
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(
312
+ executionPayload,
313
+ opts.from,
314
+ opts.feeOptions,
276
315
  );
316
+ const result = await this.pxe.simulateTx(txRequest, {
317
+ simulatePublic: true,
318
+ skipTxValidation: opts.skipTxValidation,
319
+ skipFeeEnforcement: opts.skipFeeEnforcement,
320
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
321
+ });
322
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
323
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
324
+ }
325
+
326
+ /**
327
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
328
+ * calls, N+1 = app).
329
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
330
+ * @param feeOptions - Fee options containing the wallet fee payment method.
331
+ */
332
+ protected async computeAppCallOffset(from: AztecAddress | NoFrom, feeOptions: FeeOptions): Promise<number> {
333
+ if (from === NO_FROM) {
334
+ return 0;
335
+ }
336
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
337
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
338
+ }
339
+
340
+ /**
341
+ * Simulates a transaction, optimizing leading public static calls by running them directly
342
+ * on the node while sending the remaining calls through the standard PXE path.
343
+ * Return values from both paths are merged back in original call order.
344
+ * @param executionPayload - The execution payload to simulate.
345
+ * @param opts - Simulation options (from address, fee settings, etc.).
346
+ * @returns The merged simulation result.
347
+ */
348
+ async simulateTx(
349
+ executionPayload: ExecutionPayload,
350
+ opts: SimulateOptions,
351
+ ): Promise<TxSimulationResultWithAppOffset> {
352
+ const feeOptions = await this.completeFeeOptions({
353
+ from: opts.from,
354
+ feePayer: executionPayload.feePayer,
355
+ gasSettings: opts.fee?.gasSettings,
356
+ forEstimation: true,
357
+ });
358
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
359
+ const remainingPayload = { ...executionPayload, calls: remainingCalls };
360
+
361
+ const chainInfo = await this.getChainInfo();
362
+ let blockHeader: BlockHeader;
363
+ // PXE might not be synced yet, so we pull the latest header from the node
364
+ // To keep things consistent, we'll always try with PXE first
365
+ try {
366
+ blockHeader = await this.pxe.getSyncedBlockHeader();
367
+ } catch {
368
+ blockHeader = (await this.aztecNode.getBlockHeader())!;
369
+ }
370
+
371
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
372
+ const [optimizedResults, normalResult] = await Promise.all([
373
+ optimizableCalls.length > 0
374
+ ? simulateViaNode(
375
+ this.aztecNode,
376
+ optimizableCalls,
377
+ simulationOrigin,
378
+ chainInfo,
379
+ feeOptions.gasSettings,
380
+ blockHeader,
381
+ opts.skipFeeEnforcement ?? true,
382
+ this.getContractName.bind(this),
383
+ )
384
+ : Promise.resolve([]),
385
+ remainingCalls.length > 0
386
+ ? this.simulateViaEntrypoint(remainingPayload, {
387
+ from: opts.from,
388
+ feeOptions,
389
+ additionalScopes: opts.additionalScopes,
390
+ skipTxValidation: opts.skipTxValidation,
391
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
392
+ })
393
+ : Promise.resolve(null),
394
+ ]);
395
+
396
+ return buildMergedSimulationResult(optimizedResults, normalResult);
277
397
  }
278
398
 
279
399
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
280
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
400
+ const feeOptions = await this.completeFeeOptions({
401
+ from: opts.from,
402
+ feePayer: executionPayload.feePayer,
403
+ gasSettings: opts.fee?.gasSettings,
404
+ });
281
405
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
282
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
406
+ return this.pxe.profileTx(txRequest, {
407
+ profileMode: opts.profileMode,
408
+ skipProofGeneration: opts.skipProofGeneration ?? true,
409
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
410
+ });
283
411
  }
284
412
 
285
413
  public async sendTx<W extends InteractionWaitOptions = undefined>(
286
414
  executionPayload: ExecutionPayload,
287
415
  opts: SendOptions<W>,
288
416
  ): Promise<SendReturn<W>> {
289
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
417
+ const feeOptions = await this.completeFeeOptions({
418
+ from: opts.from,
419
+ feePayer: executionPayload.feePayer,
420
+ gasSettings: opts.fee?.gasSettings,
421
+ });
290
422
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
291
- const provenTx = await this.pxe.proveTx(txRequest);
423
+ const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
424
+ const offchainOutput = extractOffchainOutput(
425
+ provenTx.getOffchainEffects(),
426
+ provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
427
+ );
292
428
  const tx = await provenTx.toTx();
293
429
  const txHash = tx.getTxHash();
294
430
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -302,12 +438,32 @@ export abstract class BaseWallet implements Wallet {
302
438
 
303
439
  // If wait is NO_WAIT, return txHash immediately
304
440
  if (opts.wait === NO_WAIT) {
305
- return txHash as SendReturn<W>;
441
+ return { txHash, ...offchainOutput } as SendReturn<W>;
306
442
  }
307
443
 
308
444
  // Otherwise, wait for the full receipt (default behavior on wait: undefined)
309
445
  const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
310
- return (await waitForTx(this.aztecNode, txHash, waitOpts)) as SendReturn<W>;
446
+ const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
447
+
448
+ // Display debug logs from public execution if present (served in test mode only)
449
+ if (receipt.debugLogs?.length) {
450
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
451
+ }
452
+
453
+ return { receipt, ...offchainOutput } as SendReturn<W>;
454
+ }
455
+
456
+ /**
457
+ * Resolves a contract address to a human-readable name via PXE, if available.
458
+ * @param address - The contract address to resolve.
459
+ */
460
+ protected async getContractName(address: AztecAddress): Promise<string | undefined> {
461
+ const instance = await this.pxe.getContractInstance(address);
462
+ if (!instance) {
463
+ return undefined;
464
+ }
465
+ const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
466
+ return artifact?.name;
311
467
  }
312
468
 
313
469
  protected contextualizeError(err: Error, ...context: string[]): Error {
@@ -324,8 +480,8 @@ export abstract class BaseWallet implements Wallet {
324
480
  return err;
325
481
  }
326
482
 
327
- simulateUtility(call: FunctionCall, authwits?: AuthWitness[]): Promise<UtilitySimulationResult> {
328
- return this.pxe.simulateUtility(call, authwits);
483
+ executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
484
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: opts.scopes });
329
485
  }
330
486
 
331
487
  async getPrivateEvents<T>(
@@ -348,26 +504,40 @@ export abstract class BaseWallet implements Wallet {
348
504
  return decodedEvents;
349
505
  }
350
506
 
507
+ /**
508
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
509
+ * @param address - The contract address to query.
510
+ */
351
511
  async getContractMetadata(address: AztecAddress) {
352
512
  const instance = await this.pxe.getContractInstance(address);
353
- const initNullifier = await siloNullifier(address, address.toField());
354
- const publiclyRegisteredContract = await this.aztecNode.getContract(address);
355
- const [initNullifierMembershipWitness, publiclyRegisteredContractClass] = await Promise.all([
356
- this.aztecNode.getNullifierMembershipWitness('latest', initNullifier),
357
- publiclyRegisteredContract
358
- ? this.aztecNode.getContractClass(
359
- publiclyRegisteredContract.currentContractClassId || instance?.currentContractClassId,
360
- )
361
- : undefined,
362
- ]);
513
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
514
+
515
+ let initializationStatus: ContractInitializationStatus;
516
+ if (instance) {
517
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
518
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
519
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
520
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
521
+ initializationStatus = witness
522
+ ? ContractInitializationStatus.INITIALIZED
523
+ : ContractInitializationStatus.UNINITIALIZED;
524
+ } else {
525
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
526
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
527
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
528
+ // uninitialized.
529
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
530
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
531
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
532
+ }
533
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
363
534
  const isContractUpdated =
364
535
  publiclyRegisteredContract &&
365
536
  !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
366
537
  return {
367
538
  instance: instance ?? undefined,
368
- isContractInitialized: !!initNullifierMembershipWitness,
539
+ initializationStatus,
369
540
  isContractPublished: !!publiclyRegisteredContract,
370
- isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass,
371
541
  isContractUpdated: !!isContractUpdated,
372
542
  updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined,
373
543
  };
@@ -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';