@aztec/wallet-sdk 0.0.1-commit.fffb133c → 0.0.1-dev

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 (71) hide show
  1. package/dest/base-wallet/base_wallet.d.ts +83 -35
  2. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  3. package/dest/base-wallet/base_wallet.js +231 -70
  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/handlers/background_connection_handler.d.ts +12 -2
  14. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -1
  15. package/dest/extension/handlers/background_connection_handler.js +44 -8
  16. package/dest/extension/handlers/content_script_connection_handler.d.ts +2 -1
  17. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -1
  18. package/dest/extension/handlers/content_script_connection_handler.js +19 -0
  19. package/dest/extension/handlers/internal_message_types.d.ts +3 -1
  20. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -1
  21. package/dest/extension/handlers/internal_message_types.js +3 -1
  22. package/dest/extension/provider/extension_wallet.d.ts +27 -6
  23. package/dest/extension/provider/extension_wallet.d.ts.map +1 -1
  24. package/dest/extension/provider/extension_wallet.js +87 -9
  25. package/dest/extension/provider/index.d.ts +2 -2
  26. package/dest/extension/provider/index.d.ts.map +1 -1
  27. package/dest/iframe/handlers/iframe_connection_handler.d.ts +122 -0
  28. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -0
  29. package/dest/iframe/handlers/iframe_connection_handler.js +240 -0
  30. package/dest/iframe/handlers/index.d.ts +2 -0
  31. package/dest/iframe/handlers/index.d.ts.map +1 -0
  32. package/dest/iframe/handlers/index.js +1 -0
  33. package/dest/iframe/provider/iframe_discovery.d.ts +25 -0
  34. package/dest/iframe/provider/iframe_discovery.d.ts.map +1 -0
  35. package/dest/iframe/provider/iframe_discovery.js +167 -0
  36. package/dest/iframe/provider/iframe_provider.d.ts +65 -0
  37. package/dest/iframe/provider/iframe_provider.d.ts.map +1 -0
  38. package/dest/iframe/provider/iframe_provider.js +257 -0
  39. package/dest/iframe/provider/iframe_wallet.d.ts +85 -0
  40. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -0
  41. package/dest/iframe/provider/iframe_wallet.js +269 -0
  42. package/dest/iframe/provider/index.d.ts +4 -0
  43. package/dest/iframe/provider/index.d.ts.map +1 -0
  44. package/dest/iframe/provider/index.js +3 -0
  45. package/dest/manager/types.d.ts +6 -5
  46. package/dest/manager/types.d.ts.map +1 -1
  47. package/dest/manager/wallet_manager.d.ts +1 -1
  48. package/dest/manager/wallet_manager.d.ts.map +1 -1
  49. package/dest/manager/wallet_manager.js +48 -18
  50. package/dest/types.d.ts +64 -2
  51. package/dest/types.d.ts.map +1 -1
  52. package/dest/types.js +29 -0
  53. package/package.json +19 -9
  54. package/src/base-wallet/base_wallet.ts +318 -124
  55. package/src/base-wallet/index.ts +7 -1
  56. package/src/base-wallet/utils.ts +240 -0
  57. package/src/crypto.ts +104 -0
  58. package/src/extension/handlers/background_connection_handler.ts +42 -9
  59. package/src/extension/handlers/content_script_connection_handler.ts +18 -0
  60. package/src/extension/handlers/internal_message_types.ts +2 -0
  61. package/src/extension/provider/extension_wallet.ts +104 -15
  62. package/src/extension/provider/index.ts +1 -1
  63. package/src/iframe/handlers/iframe_connection_handler.ts +342 -0
  64. package/src/iframe/handlers/index.ts +7 -0
  65. package/src/iframe/provider/iframe_discovery.ts +185 -0
  66. package/src/iframe/provider/iframe_provider.ts +331 -0
  67. package/src/iframe/provider/iframe_wallet.ts +323 -0
  68. package/src/iframe/provider/index.ts +3 -0
  69. package/src/manager/types.ts +5 -4
  70. package/src/manager/wallet_manager.ts +55 -23
  71. package/src/types.ts +72 -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,32 @@ 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,
46
+ type NodeInfo,
39
47
  computePartialAddress,
40
48
  getContractClassFromArtifact,
41
49
  } from '@aztec/stdlib/contract';
42
50
  import { SimulationError } from '@aztec/stdlib/errors';
43
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
44
- import { siloNullifier } from '@aztec/stdlib/hash';
51
+ import { Gas, GasFees, GasSettings } from '@aztec/stdlib/gas';
52
+ import {
53
+ computeSiloedPrivateInitializationNullifier,
54
+ computeSiloedPublicInitializationNullifier,
55
+ } from '@aztec/stdlib/hash';
45
56
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
46
- import type {
47
- TxExecutionRequest,
48
- TxProfileResult,
49
- TxSimulationResult,
50
- UtilitySimulationResult,
57
+ import {
58
+ BlockHeader,
59
+ type TxExecutionRequest,
60
+ type TxProfileResult,
61
+ type UtilityExecutionResult,
51
62
  } from '@aztec/stdlib/tx';
52
63
  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,26 +76,66 @@ 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' | 'sendMessagesAs'
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
+
71
105
  /**
72
106
  * A base class for Wallet implementations
73
107
  */
74
108
  export abstract class BaseWallet implements Wallet {
75
- protected log = createLogger('wallet-sdk:base_wallet');
76
-
77
109
  protected minFeePadding = 0.5;
78
110
  protected cancellableTransactions = false;
111
+ // A wallet is instantiated for a particular chain, so chain info never changes during its lifetime.
112
+ // We cache it here because getChainInfo is called frequently (every tx simulation, send, auth wit, etc.).
113
+ private nodeInfoPromise: Promise<NodeInfo> | undefined;
79
114
 
80
115
  // Protected because we want to force wallets to instantiate their own PXE.
81
116
  protected constructor(
82
117
  protected readonly pxe: PXE,
83
118
  protected readonly aztecNode: AztecNode,
119
+ protected log = createLogger('wallet-sdk:base_wallet'),
84
120
  ) {}
85
121
 
122
+ protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
123
+ const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
124
+ const scopeSet = new Set(allScopes.map(address => address.toString()));
125
+ return [...scopeSet].map(AztecAddress.fromString);
126
+ }
127
+
128
+ /**
129
+ * Picks the sender address PXE should tag private messages with. Returns `undefined` when there is no signing
130
+ * account (`from === NO_FROM`) and no explicit override; in that case any private log emitted by the tx will fail
131
+ * the contract-side `Sender for tags is not set` assertion unless `set_sender_for_tags` is called first.
132
+ * @param from - Tx sender, or `NO_FROM`.
133
+ * @param sendMessagesAs - Explicit override.
134
+ */
135
+ protected senderForTagsFrom(from: AztecAddress | NoFrom, sendMessagesAs?: AztecAddress): AztecAddress | undefined {
136
+ return sendMessagesAs ?? (from === NO_FROM ? undefined : from);
137
+ }
138
+
86
139
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
87
140
 
88
141
  abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
@@ -100,32 +153,42 @@ export abstract class BaseWallet implements Wallet {
100
153
  }
101
154
 
102
155
  async getChainInfo(): Promise<ChainInfo> {
103
- const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
156
+ if (!this.nodeInfoPromise) {
157
+ this.nodeInfoPromise = this.aztecNode.getNodeInfo();
158
+ }
159
+ const { l1ChainId, rollupVersion } = await this.nodeInfoPromise;
104
160
  return { chainId: new Fr(l1ChainId), version: new Fr(rollupVersion) };
105
161
  }
106
162
 
107
163
  protected async createTxExecutionRequestFromPayloadAndFee(
108
164
  executionPayload: ExecutionPayload,
109
- from: AztecAddress,
165
+ from: AztecAddress | NoFrom,
110
166
  feeOptions: FeeOptions,
111
167
  ): Promise<TxExecutionRequest> {
112
168
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
113
- const executionOptions: DefaultAccountEntrypointOptions = {
114
- txNonce: Fr.random(),
115
- cancellable: this.cancellableTransactions,
116
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
117
- };
118
169
  const finalExecutionPayload = feeExecutionPayload
119
170
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
120
171
  : executionPayload;
121
- const fromAccount = await this.getAccountFromAddress(from);
122
172
  const chainInfo = await this.getChainInfo();
123
- return fromAccount.createTxExecutionRequest(
124
- finalExecutionPayload,
125
- feeOptions.gasSettings,
126
- chainInfo,
127
- executionOptions,
128
- );
173
+
174
+ if (from === NO_FROM) {
175
+ const entrypoint = new DefaultEntrypoint();
176
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
177
+ } else {
178
+ const fromAccount = await this.getAccountFromAddress(from);
179
+ const executionOptions: DefaultAccountEntrypointOptions = {
180
+ txNonce: Fr.random(),
181
+ cancellable: this.cancellableTransactions,
182
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
183
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
184
+ };
185
+ return fromAccount.createTxExecutionRequest(
186
+ finalExecutionPayload,
187
+ feeOptions.gasSettings,
188
+ chainInfo,
189
+ executionOptions,
190
+ );
191
+ }
129
192
  }
130
193
 
131
194
  public async createAuthWit(
@@ -137,6 +200,23 @@ export abstract class BaseWallet implements Wallet {
137
200
  return account.createAuthWit(messageHashOrIntent, chainInfo);
138
201
  }
139
202
 
203
+ /**
204
+ * Request capabilities from the wallet.
205
+ *
206
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
207
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
208
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
209
+ * friction by allowing apps to request permissions upfront.
210
+ *
211
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
212
+ * while the feature stabilizes.
213
+ *
214
+ * @param _manifest - Application capability manifest declaring what operations the app needs
215
+ */
216
+ public requestCapabilities(_manifest: AppCapabilities): Promise<WalletCapabilities> {
217
+ throw new Error('Not implemented');
218
+ }
219
+
140
220
  public async batch<const T extends readonly BatchedMethod[]>(methods: T): Promise<BatchResults<T>> {
141
221
  const results: any[] = [];
142
222
  for (const method of methods) {
@@ -157,31 +237,39 @@ export abstract class BaseWallet implements Wallet {
157
237
 
158
238
  /**
159
239
  * 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
240
+ * @param config - Fee completion config.
164
241
  */
165
- protected async completeFeeOptions(
166
- from: AztecAddress,
167
- feePayer?: AztecAddress,
168
- gasSettings?: Partial<FieldsOf<GasSettings>>,
169
- ): Promise<FeeOptions> {
242
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
243
+ const { from, feePayer, gasSettings, forEstimation } = config;
170
244
  const maxFeesPerGas =
171
245
  gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
172
246
  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;
247
+ // If from is an address, we need to determine the appropriate fee payment method options for the
248
+ // account contract entrypoint to use
249
+ if (from !== NO_FROM) {
250
+ if (!feePayer) {
251
+ // The transaction does not include a fee payment method, so we set the flag
252
+ // for the account to use its fee juice balance
253
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
254
+ } else {
255
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
256
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
257
+ accountFeePaymentMethodOptions = from.equals(feePayer)
258
+ ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
259
+ : AccountFeePaymentMethodOptions.EXTERNAL;
260
+ }
183
261
  }
184
- const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
262
+ const gasSettingsOverrides = {
263
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
264
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
265
+ maxFeesPerGas,
266
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty(),
267
+ };
268
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
269
+ // When sending for real, use protocol max limits that the network will actually accept.
270
+ const fullGasSettings = forEstimation
271
+ ? GasSettings.forEstimation(gasSettingsOverrides)
272
+ : GasSettings.fallback(gasSettingsOverrides);
185
273
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
186
274
  return {
187
275
  gasSettings: fullGasSettings,
@@ -190,37 +278,6 @@ export abstract class BaseWallet implements Wallet {
190
278
  };
191
279
  }
192
280
 
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
281
  registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
225
282
  return this.pxe.registerSender(address);
226
283
  }
@@ -263,32 +320,135 @@ export abstract class BaseWallet implements Wallet {
263
320
  return instance;
264
321
  }
265
322
 
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,
323
+ /**
324
+ * Simulates calls through the standard PXE path (account entrypoint).
325
+ * @param executionPayload - The execution payload to simulate.
326
+ * @param opts - Simulation options.
327
+ */
328
+ protected async simulateViaEntrypoint(executionPayload: ExecutionPayload, opts: SimulateViaEntrypointOptions) {
329
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(
330
+ executionPayload,
331
+ opts.from,
332
+ opts.feeOptions,
276
333
  );
334
+ const result = await this.pxe.simulateTx(txRequest, {
335
+ simulatePublic: true,
336
+ skipTxValidation: opts.skipTxValidation,
337
+ skipFeeEnforcement: opts.skipFeeEnforcement,
338
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
339
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
340
+ });
341
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
342
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
343
+ }
344
+
345
+ /**
346
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
347
+ * calls, N+1 = app).
348
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
349
+ * @param feeOptions - Fee options containing the wallet fee payment method.
350
+ */
351
+ protected async computeAppCallOffset(from: AztecAddress | NoFrom, feeOptions: FeeOptions): Promise<number> {
352
+ if (from === NO_FROM) {
353
+ return 0;
354
+ }
355
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
356
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
357
+ }
358
+
359
+ /**
360
+ * Simulates a transaction, optimizing leading public static calls by running them directly
361
+ * on the node while sending the remaining calls through the standard PXE path.
362
+ * Return values from both paths are merged back in original call order.
363
+ * @param executionPayload - The execution payload to simulate.
364
+ * @param opts - Simulation options (from address, fee settings, etc.).
365
+ * @returns The merged simulation result.
366
+ */
367
+ async simulateTx(
368
+ executionPayload: ExecutionPayload,
369
+ opts: SimulateOptions,
370
+ ): Promise<TxSimulationResultWithAppOffset> {
371
+ const feeOptions = await this.completeFeeOptions({
372
+ from: opts.from,
373
+ feePayer: executionPayload.feePayer,
374
+ gasSettings: opts.fee?.gasSettings,
375
+ forEstimation: true,
376
+ });
377
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
378
+ const remainingPayload = { ...executionPayload, calls: remainingCalls };
379
+
380
+ const chainInfo = await this.getChainInfo();
381
+ let blockHeader: BlockHeader;
382
+ // PXE might not be synced yet, so we pull the latest header from the node
383
+ // To keep things consistent, we'll always try with PXE first
384
+ try {
385
+ blockHeader = await this.pxe.getSyncedBlockHeader();
386
+ } catch {
387
+ blockHeader = (await this.aztecNode.getBlockHeader())!;
388
+ }
389
+
390
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
391
+ const [optimizedResults, normalResult] = await Promise.all([
392
+ optimizableCalls.length > 0
393
+ ? simulateViaNode(
394
+ this.aztecNode,
395
+ optimizableCalls,
396
+ simulationOrigin,
397
+ chainInfo,
398
+ feeOptions.gasSettings,
399
+ blockHeader,
400
+ opts.skipFeeEnforcement ?? true,
401
+ this.getContractName.bind(this),
402
+ )
403
+ : Promise.resolve([]),
404
+ remainingCalls.length > 0
405
+ ? this.simulateViaEntrypoint(remainingPayload, {
406
+ from: opts.from,
407
+ feeOptions,
408
+ additionalScopes: opts.additionalScopes,
409
+ skipTxValidation: opts.skipTxValidation,
410
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
411
+ sendMessagesAs: opts.sendMessagesAs,
412
+ })
413
+ : Promise.resolve(null),
414
+ ]);
415
+
416
+ return buildMergedSimulationResult(optimizedResults, normalResult);
277
417
  }
278
418
 
279
419
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
280
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
420
+ const feeOptions = await this.completeFeeOptions({
421
+ from: opts.from,
422
+ feePayer: executionPayload.feePayer,
423
+ gasSettings: opts.fee?.gasSettings,
424
+ });
281
425
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
282
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
426
+ return this.pxe.profileTx(txRequest, {
427
+ profileMode: opts.profileMode,
428
+ skipProofGeneration: opts.skipProofGeneration ?? true,
429
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
430
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
431
+ });
283
432
  }
284
433
 
285
434
  public async sendTx<W extends InteractionWaitOptions = undefined>(
286
435
  executionPayload: ExecutionPayload,
287
436
  opts: SendOptions<W>,
288
437
  ): Promise<SendReturn<W>> {
289
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
438
+ const feeOptions = await this.completeFeeOptions({
439
+ from: opts.from,
440
+ feePayer: executionPayload.feePayer,
441
+ gasSettings: opts.fee?.gasSettings,
442
+ });
290
443
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
291
- const provenTx = await this.pxe.proveTx(txRequest);
444
+ const provenTx = await this.pxe.proveTx(txRequest, {
445
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
446
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
447
+ });
448
+ const offchainOutput = extractOffchainOutput(
449
+ provenTx.getOffchainEffects(),
450
+ provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
451
+ );
292
452
  const tx = await provenTx.toTx();
293
453
  const txHash = tx.getTxHash();
294
454
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -302,12 +462,32 @@ export abstract class BaseWallet implements Wallet {
302
462
 
303
463
  // If wait is NO_WAIT, return txHash immediately
304
464
  if (opts.wait === NO_WAIT) {
305
- return txHash as SendReturn<W>;
465
+ return { txHash, ...offchainOutput } as SendReturn<W>;
306
466
  }
307
467
 
308
468
  // Otherwise, wait for the full receipt (default behavior on wait: undefined)
309
469
  const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
310
- return (await waitForTx(this.aztecNode, txHash, waitOpts)) as SendReturn<W>;
470
+ const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
471
+
472
+ // Display debug logs from public execution if present (served in test mode only)
473
+ if (receipt.debugLogs?.length) {
474
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
475
+ }
476
+
477
+ return { receipt, ...offchainOutput } as SendReturn<W>;
478
+ }
479
+
480
+ /**
481
+ * Resolves a contract address to a human-readable name via PXE, if available.
482
+ * @param address - The contract address to resolve.
483
+ */
484
+ protected async getContractName(address: AztecAddress): Promise<string | undefined> {
485
+ const instance = await this.pxe.getContractInstance(address);
486
+ if (!instance) {
487
+ return undefined;
488
+ }
489
+ const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
490
+ return artifact?.name;
311
491
  }
312
492
 
313
493
  protected contextualizeError(err: Error, ...context: string[]): Error {
@@ -324,8 +504,8 @@ export abstract class BaseWallet implements Wallet {
324
504
  return err;
325
505
  }
326
506
 
327
- simulateUtility(call: FunctionCall, authwits?: AuthWitness[]): Promise<UtilitySimulationResult> {
328
- return this.pxe.simulateUtility(call, authwits);
507
+ executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
508
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: opts.scopes });
329
509
  }
330
510
 
331
511
  async getPrivateEvents<T>(
@@ -348,26 +528,40 @@ export abstract class BaseWallet implements Wallet {
348
528
  return decodedEvents;
349
529
  }
350
530
 
531
+ /**
532
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
533
+ * @param address - The contract address to query.
534
+ */
351
535
  async getContractMetadata(address: AztecAddress) {
352
536
  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
- ]);
537
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
538
+
539
+ let initializationStatus: ContractInitializationStatus;
540
+ if (instance) {
541
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
542
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
543
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
544
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
545
+ initializationStatus = witness
546
+ ? ContractInitializationStatus.INITIALIZED
547
+ : ContractInitializationStatus.UNINITIALIZED;
548
+ } else {
549
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
550
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
551
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
552
+ // uninitialized.
553
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
554
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
555
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
556
+ }
557
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
363
558
  const isContractUpdated =
364
559
  publiclyRegisteredContract &&
365
560
  !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
366
561
  return {
367
562
  instance: instance ?? undefined,
368
- isContractInitialized: !!initNullifierMembershipWitness,
563
+ initializationStatus,
369
564
  isContractPublished: !!publiclyRegisteredContract,
370
- isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass,
371
565
  isContractUpdated: !!isContractUpdated,
372
566
  updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined,
373
567
  };
@@ -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';