@aztec/wallet-sdk 0.0.1-commit.b64cb54f6 → 0.0.1-commit.b9865e97

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/README.md +125 -0
  2. package/dest/base-wallet/base_wallet.d.ts +60 -39
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +167 -75
  5. package/dest/base-wallet/index.d.ts +2 -2
  6. package/dest/base-wallet/index.d.ts.map +1 -1
  7. package/dest/base-wallet/utils.d.ts +7 -4
  8. package/dest/base-wallet/utils.d.ts.map +1 -1
  9. package/dest/base-wallet/utils.js +11 -5
  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 +26 -6
  23. package/dest/extension/provider/extension_wallet.d.ts.map +1 -1
  24. package/dest/extension/provider/extension_wallet.js +80 -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 +239 -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 +3 -2
  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 +46 -16
  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 +12 -8
  54. package/src/base-wallet/base_wallet.ts +245 -128
  55. package/src/base-wallet/index.ts +6 -1
  56. package/src/base-wallet/utils.ts +15 -5
  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 +94 -13
  62. package/src/extension/provider/index.ts +1 -1
  63. package/src/iframe/handlers/iframe_connection_handler.ts +341 -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 +2 -1
  70. package/src/manager/wallet_manager.ts +48 -14
  71. package/src/types.ts +72 -0
@@ -1,4 +1,5 @@
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
4
  import {
4
5
  type InteractionWaitOptions,
@@ -8,32 +9,29 @@ import {
8
9
  } from '@aztec/aztec.js/contracts';
9
10
  import type { FeePaymentMethod } from '@aztec/aztec.js/fee';
10
11
  import { waitForTx } from '@aztec/aztec.js/node';
11
- import type {
12
- Aliased,
13
- AppCapabilities,
14
- BatchResults,
15
- BatchedMethod,
16
- ExecuteUtilityOptions,
17
- PrivateEvent,
18
- PrivateEventFilter,
19
- ProfileOptions,
20
- SendOptions,
21
- SimulateOptions,
22
- Wallet,
23
- WalletCapabilities,
24
- } from '@aztec/aztec.js/wallet';
25
12
  import {
26
- GAS_ESTIMATION_DA_GAS_LIMIT,
27
- GAS_ESTIMATION_L2_GAS_LIMIT,
28
- GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT,
29
- GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT,
30
- } 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';
31
28
  import { AccountFeePaymentMethodOptions, type DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
29
+ import { DefaultEntrypoint } from '@aztec/entrypoints/default';
32
30
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
33
31
  import { Fr } from '@aztec/foundation/curves/bn254';
34
32
  import { createLogger } from '@aztec/foundation/log';
35
33
  import type { FieldsOf } from '@aztec/foundation/types';
36
- import { type AccessScopes, displayDebugLogs } from '@aztec/pxe/client/lazy';
34
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
37
35
  import type { PXE, PackedPrivateEvent } from '@aztec/pxe/server';
38
36
  import {
39
37
  type ContractArtifact,
@@ -45,21 +43,25 @@ import type { AuthWitness } from '@aztec/stdlib/auth-witness';
45
43
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
46
44
  import {
47
45
  type ContractInstanceWithAddress,
46
+ type NodeInfo,
48
47
  computePartialAddress,
49
48
  getContractClassFromArtifact,
50
49
  } from '@aztec/stdlib/contract';
51
50
  import { SimulationError } from '@aztec/stdlib/errors';
52
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
53
- 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';
54
56
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
55
57
  import {
56
58
  BlockHeader,
59
+ ExecutionPayload,
57
60
  type TxExecutionRequest,
58
61
  type TxProfileResult,
59
- TxSimulationResult,
60
62
  type UtilityExecutionResult,
63
+ mergeExecutionPayloads,
61
64
  } from '@aztec/stdlib/tx';
62
- import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
63
65
 
64
66
  import { inspect } from 'util';
65
67
 
@@ -75,17 +77,46 @@ export type FeeOptions = {
75
77
  */
76
78
  walletFeePaymentMethod?: FeePaymentMethod;
77
79
  /** Configuration options for the account to properly handle the selected fee payment method */
78
- accountFeePaymentMethodOptions: AccountFeePaymentMethodOptions;
80
+ accountFeePaymentMethodOptions?: AccountFeePaymentMethodOptions;
79
81
  /** The gas settings to use for the transaction */
80
82
  gasSettings: GasSettings;
81
83
  };
82
84
 
85
+ /** Options for `simulateViaEntrypoint`. */
86
+ export type SimulateViaEntrypointOptions = Pick<
87
+ SimulateOptions,
88
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement' | 'sendMessagesAs' | 'overrides'
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
+
83
111
  /**
84
112
  * A base class for Wallet implementations
85
113
  */
86
114
  export abstract class BaseWallet implements Wallet {
87
115
  protected minFeePadding = 0.5;
88
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;
89
120
 
90
121
  // Protected because we want to force wallets to instantiate their own PXE.
91
122
  protected constructor(
@@ -94,12 +125,23 @@ export abstract class BaseWallet implements Wallet {
94
125
  protected log = createLogger('wallet-sdk:base_wallet'),
95
126
  ) {}
96
127
 
97
- protected scopesFrom(from: AztecAddress, additionalScopes: AztecAddress[] = []): AztecAddress[] {
98
- const allScopes = from.isZero() ? additionalScopes : [from, ...additionalScopes];
128
+ protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
129
+ const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
99
130
  const scopeSet = new Set(allScopes.map(address => address.toString()));
100
131
  return [...scopeSet].map(AztecAddress.fromString);
101
132
  }
102
133
 
134
+ /**
135
+ * Picks the sender address PXE should tag private messages with. Returns `undefined` when there is no signing
136
+ * account (`from === NO_FROM`) and no explicit override; in that case any private log emitted by the tx using
137
+ * the wallet-supplied default sender will fail the "Sender for tags is not set" assertion.
138
+ * @param from - Tx sender, or `NO_FROM`.
139
+ * @param sendMessagesAs - Explicit override.
140
+ */
141
+ protected senderForTagsFrom(from: AztecAddress | NoFrom, sendMessagesAs?: AztecAddress): AztecAddress | undefined {
142
+ return sendMessagesAs ?? (from === NO_FROM ? undefined : from);
143
+ }
144
+
103
145
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
104
146
 
105
147
  abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
@@ -117,32 +159,42 @@ export abstract class BaseWallet implements Wallet {
117
159
  }
118
160
 
119
161
  async getChainInfo(): Promise<ChainInfo> {
120
- const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
162
+ if (!this.nodeInfoPromise) {
163
+ this.nodeInfoPromise = this.aztecNode.getNodeInfo();
164
+ }
165
+ const { l1ChainId, rollupVersion } = await this.nodeInfoPromise;
121
166
  return { chainId: new Fr(l1ChainId), version: new Fr(rollupVersion) };
122
167
  }
123
168
 
124
169
  protected async createTxExecutionRequestFromPayloadAndFee(
125
170
  executionPayload: ExecutionPayload,
126
- from: AztecAddress,
171
+ from: AztecAddress | NoFrom,
127
172
  feeOptions: FeeOptions,
128
173
  ): Promise<TxExecutionRequest> {
129
174
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
130
- const executionOptions: DefaultAccountEntrypointOptions = {
131
- txNonce: Fr.random(),
132
- cancellable: this.cancellableTransactions,
133
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
134
- };
135
175
  const finalExecutionPayload = feeExecutionPayload
136
176
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
137
177
  : executionPayload;
138
- const fromAccount = await this.getAccountFromAddress(from);
139
178
  const chainInfo = await this.getChainInfo();
140
- return fromAccount.createTxExecutionRequest(
141
- finalExecutionPayload,
142
- feeOptions.gasSettings,
143
- chainInfo,
144
- executionOptions,
145
- );
179
+
180
+ if (from === NO_FROM) {
181
+ const entrypoint = new DefaultEntrypoint();
182
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
183
+ } else {
184
+ const fromAccount = await this.getAccountFromAddress(from);
185
+ const executionOptions: DefaultAccountEntrypointOptions = {
186
+ txNonce: Fr.random(),
187
+ cancellable: this.cancellableTransactions,
188
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
189
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
190
+ };
191
+ return fromAccount.createTxExecutionRequest(
192
+ finalExecutionPayload,
193
+ feeOptions.gasSettings,
194
+ chainInfo,
195
+ executionOptions,
196
+ );
197
+ }
146
198
  }
147
199
 
148
200
  public async createAuthWit(
@@ -191,31 +243,39 @@ export abstract class BaseWallet implements Wallet {
191
243
 
192
244
  /**
193
245
  * Completes partial user-provided fee options with wallet defaults.
194
- * @param from - The address where the transaction is being sent from
195
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
196
- * @param gasSettings - User-provided partial gas settings
197
- * @returns - Complete fee options that can be used to create a transaction execution request
246
+ * @param config - Fee completion config.
198
247
  */
199
- protected async completeFeeOptions(
200
- from: AztecAddress,
201
- feePayer?: AztecAddress,
202
- gasSettings?: Partial<FieldsOf<GasSettings>>,
203
- ): Promise<FeeOptions> {
248
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
249
+ const { from, feePayer, gasSettings, forEstimation, congestionEstimate } = config;
204
250
  const maxFeesPerGas =
205
- gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
251
+ gasSettings?.maxFeesPerGas ?? (await this.getMinFees(congestionEstimate)).mul(1 + this.minFeePadding);
206
252
  let accountFeePaymentMethodOptions;
207
- // The transaction does not include a fee payment method, so we set the flag
208
- // for the account to use its fee juice balance
209
- if (!feePayer) {
210
- accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
211
- } else {
212
- // The transaction includes fee payment method, so we check if we are the fee payer for it
213
- // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
214
- accountFeePaymentMethodOptions = from.equals(feePayer)
215
- ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
216
- : AccountFeePaymentMethodOptions.EXTERNAL;
253
+ // If from is an address, we need to determine the appropriate fee payment method options for the
254
+ // account contract entrypoint to use
255
+ if (from !== NO_FROM) {
256
+ if (!feePayer) {
257
+ // The transaction does not include a fee payment method, so we set the flag
258
+ // for the account to use its fee juice balance
259
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
260
+ } else {
261
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
262
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
263
+ accountFeePaymentMethodOptions = from.equals(feePayer)
264
+ ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
265
+ : AccountFeePaymentMethodOptions.EXTERNAL;
266
+ }
217
267
  }
218
- const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
268
+ const gasSettingsOverrides = {
269
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
270
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
271
+ maxFeesPerGas,
272
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty(),
273
+ };
274
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
275
+ // When sending for real, use protocol max limits that the network will actually accept.
276
+ const fullGasSettings = forEstimation
277
+ ? GasSettings.forEstimation(gasSettingsOverrides)
278
+ : GasSettings.fallback(gasSettingsOverrides);
219
279
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
220
280
  return {
221
281
  gasSettings: fullGasSettings,
@@ -225,34 +285,25 @@ export abstract class BaseWallet implements Wallet {
225
285
  }
226
286
 
227
287
  /**
228
- * Completes partial user-provided fee options with unreasonably high gas limits
229
- * for gas estimation. Uses the same logic as completeFeeOptions but sets high limits
230
- * to avoid running out of gas during estimation.
231
- * @param from - The address where the transaction is being sent from
232
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
233
- * @param gasSettings - User-provided partial gas settings
288
+ * Returns the worst-case min fee across predicted future slots.
289
+ * Falls back to getCurrentMinFees if the node doesn't support getPredictedMinFees.
290
+ * @param estimate - The mana usage estimate to use for fee prediction. Defaults to Limit for conservative estimation.
234
291
  */
235
- protected async completeFeeOptionsForEstimation(
236
- from: AztecAddress,
237
- feePayer?: AztecAddress,
238
- gasSettings?: Partial<FieldsOf<GasSettings>>,
239
- ) {
240
- const defaultFeeOptions = await this.completeFeeOptions(from, feePayer, gasSettings);
241
- const {
242
- gasSettings: { maxFeesPerGas, maxPriorityFeesPerGas },
243
- } = defaultFeeOptions;
244
- // Use unrealistically high gas limits for estimation to avoid running out of gas.
245
- // They will be tuned down after the simulation.
246
- const gasSettingsForEstimation = new GasSettings(
247
- new Gas(GAS_ESTIMATION_DA_GAS_LIMIT, GAS_ESTIMATION_L2_GAS_LIMIT),
248
- new Gas(GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT),
249
- maxFeesPerGas,
250
- maxPriorityFeesPerGas,
251
- );
252
- return {
253
- ...defaultFeeOptions,
254
- gasSettings: gasSettingsForEstimation,
255
- };
292
+ protected async getMinFees(estimate: ManaUsageEstimate = ManaUsageEstimate.Limit): Promise<GasFees> {
293
+ try {
294
+ const predicted = await this.aztecNode.getPredictedMinFees(estimate);
295
+ if (predicted.length === 0) {
296
+ return this.aztecNode.getCurrentMinFees();
297
+ }
298
+ return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
299
+ } catch (err: any) {
300
+ // Fallback for old nodes that don't support getPredictedMinFees.
301
+ // Only fall back on method-not-found errors (JSON-RPC code -32601); rethrow others.
302
+ if (err?.cause?.code === -32601 || err?.message?.includes('Method not found')) {
303
+ return this.aztecNode.getCurrentMinFees();
304
+ }
305
+ throw err;
306
+ }
256
307
  }
257
308
 
258
309
  registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
@@ -297,25 +348,45 @@ export abstract class BaseWallet implements Wallet {
297
348
  return instance;
298
349
  }
299
350
 
351
+ registerContractClass(artifact: ContractArtifact): Promise<void> {
352
+ return this.pxe.registerContractClass(artifact);
353
+ }
354
+
300
355
  /**
301
356
  * Simulates calls through the standard PXE path (account entrypoint).
302
357
  * @param executionPayload - The execution payload to simulate.
303
- * @param from - The sender address.
304
- * @param feeOptions - Fee options for the transaction.
305
- * @param skipTxValidation - Whether to skip tx validation.
306
- * @param skipFeeEnforcement - Whether to skip fee enforcement.
307
- * @param scopes - The scopes to use for the simulation.
358
+ * @param opts - Simulation options.
308
359
  */
309
- protected async simulateViaEntrypoint(
310
- executionPayload: ExecutionPayload,
311
- from: AztecAddress,
312
- feeOptions: FeeOptions,
313
- scopes: AccessScopes,
314
- skipTxValidation?: boolean,
315
- skipFeeEnforcement?: boolean,
316
- ) {
317
- const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, from, feeOptions);
318
- return this.pxe.simulateTx(txRequest, { simulatePublic: true, skipTxValidation, skipFeeEnforcement, scopes });
360
+ protected async simulateViaEntrypoint(executionPayload: ExecutionPayload, opts: SimulateViaEntrypointOptions) {
361
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(
362
+ executionPayload,
363
+ opts.from,
364
+ opts.feeOptions,
365
+ );
366
+ const result = await this.pxe.simulateTx(txRequest, {
367
+ simulatePublic: true,
368
+ skipTxValidation: opts.skipTxValidation,
369
+ skipFeeEnforcement: opts.skipFeeEnforcement,
370
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
371
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
372
+ overrides: opts.overrides,
373
+ });
374
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
375
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
376
+ }
377
+
378
+ /**
379
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
380
+ * calls, N+1 = app).
381
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
382
+ * @param feeOptions - Fee options containing the wallet fee payment method.
383
+ */
384
+ protected async computeAppCallOffset(from: AztecAddress | NoFrom, feeOptions: FeeOptions): Promise<number> {
385
+ if (from === NO_FROM) {
386
+ return 0;
387
+ }
388
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
389
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
319
390
  }
320
391
 
321
392
  /**
@@ -326,10 +397,17 @@ export abstract class BaseWallet implements Wallet {
326
397
  * @param opts - Simulation options (from address, fee settings, etc.).
327
398
  * @returns The merged simulation result.
328
399
  */
329
- async simulateTx(executionPayload: ExecutionPayload, opts: SimulateOptions): Promise<TxSimulationResult> {
330
- const feeOptions = opts.fee?.estimateGas
331
- ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings)
332
- : await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
400
+ async simulateTx(
401
+ executionPayload: ExecutionPayload,
402
+ opts: SimulateOptions,
403
+ ): Promise<TxSimulationResultWithAppOffset> {
404
+ const feeOptions = await this.completeFeeOptions({
405
+ from: opts.from,
406
+ feePayer: executionPayload.feePayer,
407
+ gasSettings: opts.fee?.gasSettings,
408
+ forEstimation: true,
409
+ congestionEstimate: opts.fee?.congestionEstimate,
410
+ });
333
411
  const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
334
412
  const remainingPayload = { ...executionPayload, calls: remainingCalls };
335
413
 
@@ -340,31 +418,34 @@ export abstract class BaseWallet implements Wallet {
340
418
  try {
341
419
  blockHeader = await this.pxe.getSyncedBlockHeader();
342
420
  } catch {
343
- blockHeader = (await this.aztecNode.getBlockHeader())!;
421
+ blockHeader = (await this.aztecNode.getBlockData('latest'))!.header;
344
422
  }
345
423
 
424
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
346
425
  const [optimizedResults, normalResult] = await Promise.all([
347
426
  optimizableCalls.length > 0
348
427
  ? simulateViaNode(
349
428
  this.aztecNode,
350
429
  optimizableCalls,
351
- opts.from,
430
+ simulationOrigin,
352
431
  chainInfo,
353
432
  feeOptions.gasSettings,
354
433
  blockHeader,
355
434
  opts.skipFeeEnforcement ?? true,
356
435
  this.getContractName.bind(this),
436
+ opts.overrides,
357
437
  )
358
438
  : Promise.resolve([]),
359
439
  remainingCalls.length > 0
360
- ? this.simulateViaEntrypoint(
361
- remainingPayload,
362
- opts.from,
440
+ ? this.simulateViaEntrypoint(remainingPayload, {
441
+ from: opts.from,
363
442
  feeOptions,
364
- this.scopesFrom(opts.from, opts.additionalScopes),
365
- opts.skipTxValidation,
366
- opts.skipFeeEnforcement ?? true,
367
- )
443
+ additionalScopes: opts.additionalScopes,
444
+ skipTxValidation: opts.skipTxValidation,
445
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
446
+ sendMessagesAs: opts.sendMessagesAs,
447
+ overrides: opts.overrides,
448
+ })
368
449
  : Promise.resolve(null),
369
450
  ]);
370
451
 
@@ -372,12 +453,18 @@ export abstract class BaseWallet implements Wallet {
372
453
  }
373
454
 
374
455
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
375
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
456
+ const feeOptions = await this.completeFeeOptions({
457
+ from: opts.from,
458
+ feePayer: executionPayload.feePayer,
459
+ gasSettings: opts.fee?.gasSettings,
460
+ congestionEstimate: opts.fee?.congestionEstimate,
461
+ });
376
462
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
377
463
  return this.pxe.profileTx(txRequest, {
378
464
  profileMode: opts.profileMode,
379
465
  skipProofGeneration: opts.skipProofGeneration ?? true,
380
466
  scopes: this.scopesFrom(opts.from, opts.additionalScopes),
467
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
381
468
  });
382
469
  }
383
470
 
@@ -385,16 +472,24 @@ export abstract class BaseWallet implements Wallet {
385
472
  executionPayload: ExecutionPayload,
386
473
  opts: SendOptions<W>,
387
474
  ): Promise<SendReturn<W>> {
388
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
475
+ const feeOptions = await this.completeFeeOptions({
476
+ from: opts.from,
477
+ feePayer: executionPayload.feePayer,
478
+ gasSettings: opts.fee?.gasSettings,
479
+ congestionEstimate: opts.fee?.congestionEstimate,
480
+ });
389
481
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
390
- const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
482
+ const provenTx = await this.pxe.proveTx(txRequest, {
483
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
484
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
485
+ });
391
486
  const offchainOutput = extractOffchainOutput(
392
487
  provenTx.getOffchainEffects(),
393
488
  provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
394
489
  );
395
490
  const tx = await provenTx.toTx();
396
491
  const txHash = tx.getTxHash();
397
- if (await this.aztecNode.getTxEffect(txHash)) {
492
+ if ((await this.aztecNode.getTxReceipt(txHash)).isMined()) {
398
493
  throw new Error(`A settled tx with equal hash ${txHash.toString()} exists.`);
399
494
  }
400
495
  this.log.debug(`Sending transaction ${txHash}`);
@@ -413,7 +508,7 @@ export abstract class BaseWallet implements Wallet {
413
508
  const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
414
509
 
415
510
  // Display debug logs from public execution if present (served in test mode only)
416
- if (receipt.debugLogs?.length) {
511
+ if (receipt.isMined() && receipt.debugLogs?.length) {
417
512
  await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
418
513
  }
419
514
 
@@ -448,7 +543,7 @@ export abstract class BaseWallet implements Wallet {
448
543
  }
449
544
 
450
545
  executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
451
- return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: [opts.scope] });
546
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: opts.scopes });
452
547
  }
453
548
 
454
549
  async getPrivateEvents<T>(
@@ -471,17 +566,39 @@ export abstract class BaseWallet implements Wallet {
471
566
  return decodedEvents;
472
567
  }
473
568
 
569
+ /**
570
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
571
+ * @param address - The contract address to query.
572
+ */
474
573
  async getContractMetadata(address: AztecAddress) {
475
574
  const instance = await this.pxe.getContractInstance(address);
476
- const initNullifier = await siloNullifier(address, address.toField());
477
- const publiclyRegisteredContract = await this.aztecNode.getContract(address);
478
- const initNullifierMembershipWitness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
575
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
576
+
577
+ let initializationStatus: ContractInitializationStatus;
578
+ if (instance) {
579
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
580
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
581
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
582
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
583
+ initializationStatus = witness
584
+ ? ContractInitializationStatus.INITIALIZED
585
+ : ContractInitializationStatus.UNINITIALIZED;
586
+ } else {
587
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
588
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
589
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
590
+ // uninitialized.
591
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
592
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
593
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
594
+ }
595
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
479
596
  const isContractUpdated =
480
597
  publiclyRegisteredContract &&
481
598
  !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
482
599
  return {
483
600
  instance: instance ?? undefined,
484
- isContractInitialized: !!initNullifierMembershipWitness,
601
+ initializationStatus,
485
602
  isContractPublished: !!publiclyRegisteredContract,
486
603
  isContractUpdated: !!isContractUpdated,
487
604
  updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined,
@@ -1,2 +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';
2
7
  export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';
@@ -1,4 +1,5 @@
1
1
  import type { AztecNode } from '@aztec/aztec.js/node';
2
+ import { TxSimulationResultWithAppOffset } from '@aztec/aztec.js/wallet';
2
3
  import { MAX_ENQUEUED_CALLS_PER_CALL } from '@aztec/constants';
3
4
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
4
5
  import { makeTuple } from '@aztec/foundation/array';
@@ -24,6 +25,7 @@ import {
24
25
  PrivateCallExecutionResult,
25
26
  PrivateExecutionResult,
26
27
  PublicSimulationOutput,
28
+ type SimulationOverrides,
27
29
  Tx,
28
30
  TxContext,
29
31
  TxSimulationResult,
@@ -64,6 +66,8 @@ export function extractOptimizablePublicStaticCalls(payload: ExecutionPayload):
64
66
  * @param gasSettings - Gas settings for the transaction.
65
67
  * @param blockHeader - Block header to use as anchor.
66
68
  * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
69
+ * @param getContractName - Resolver for contract names (used for debug log display).
70
+ * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
67
71
  * @returns TxSimulationResult with public return values.
68
72
  */
69
73
  async function simulateBatchViaNode(
@@ -75,6 +79,7 @@ async function simulateBatchViaNode(
75
79
  blockHeader: BlockHeader,
76
80
  skipFeeEnforcement: boolean,
77
81
  getContractName: ContractNameResolver,
82
+ overrides?: SimulationOverrides,
78
83
  ): Promise<TxSimulationResult> {
79
84
  const txContext = new TxContext(chainInfo.chainId, chainInfo.version, gasSettings);
80
85
 
@@ -142,7 +147,7 @@ async function simulateBatchViaNode(
142
147
  publicFunctionCalldata: publicFunctionCalldata,
143
148
  });
144
149
 
145
- const publicOutput = await node.simulatePublicCalls(tx, skipFeeEnforcement);
150
+ const publicOutput = await node.simulatePublicCalls(tx, skipFeeEnforcement, overrides);
146
151
 
147
152
  if (publicOutput.revertReason) {
148
153
  throw publicOutput.revertReason;
@@ -165,6 +170,8 @@ async function simulateBatchViaNode(
165
170
  * @param gasSettings - Gas settings for the transaction.
166
171
  * @param blockHeader - Block header to use as anchor.
167
172
  * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
173
+ * @param getContractName - Resolver for contract names (used for debug log display).
174
+ * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
168
175
  * @returns Array of TxSimulationResult, one per batch.
169
176
  */
170
177
  export async function simulateViaNode(
@@ -176,6 +183,7 @@ export async function simulateViaNode(
176
183
  blockHeader: BlockHeader,
177
184
  skipFeeEnforcement: boolean = true,
178
185
  getContractName: ContractNameResolver,
186
+ overrides?: SimulationOverrides,
179
187
  ): Promise<TxSimulationResult[]> {
180
188
  const batches: FunctionCall[][] = [];
181
189
 
@@ -195,6 +203,7 @@ export async function simulateViaNode(
195
203
  blockHeader,
196
204
  skipFeeEnforcement,
197
205
  getContractName,
206
+ overrides,
198
207
  );
199
208
  results.push(result);
200
209
  }
@@ -214,13 +223,13 @@ export async function simulateViaNode(
214
223
  */
215
224
  export function buildMergedSimulationResult(
216
225
  optimizedResults: TxSimulationResult[],
217
- normalResult: TxSimulationResult | null,
218
- ): TxSimulationResult {
226
+ normalResult: TxSimulationResultWithAppOffset | null,
227
+ ): TxSimulationResultWithAppOffset {
219
228
  const optimizedReturnValues = optimizedResults.flatMap(r => r.publicOutput?.publicReturnValues ?? []);
220
229
  const normalReturnValues = normalResult?.publicOutput?.publicReturnValues ?? [];
221
230
  const allReturnValues = [...optimizedReturnValues, ...normalReturnValues];
222
231
 
223
- const baseResult = normalResult ?? optimizedResults[0];
232
+ const baseResult: TxSimulationResult = normalResult ?? optimizedResults[0];
224
233
 
225
234
  const mergedPublicOutput: PublicSimulationOutput | undefined = baseResult.publicOutput
226
235
  ? {
@@ -229,10 +238,11 @@ export function buildMergedSimulationResult(
229
238
  }
230
239
  : undefined;
231
240
 
232
- return new TxSimulationResult(
241
+ const merged = new TxSimulationResult(
233
242
  baseResult.privateExecutionResult,
234
243
  baseResult.publicInputs,
235
244
  mergedPublicOutput,
236
245
  normalResult?.stats,
237
246
  );
247
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(merged, normalResult?.appCallOffset ?? 0);
238
248
  }