@aztec/wallet-sdk 0.0.1-commit.7b86788 → 0.0.1-commit.7cbc774

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 (70) hide show
  1. package/dest/base-wallet/base_wallet.d.ts +60 -39
  2. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  3. package/dest/base-wallet/base_wallet.js +175 -76
  4. package/dest/base-wallet/index.d.ts +2 -2
  5. package/dest/base-wallet/index.d.ts.map +1 -1
  6. package/dest/base-wallet/utils.d.ts +7 -4
  7. package/dest/base-wallet/utils.d.ts.map +1 -1
  8. package/dest/base-wallet/utils.js +11 -5
  9. package/dest/crypto.d.ts +39 -1
  10. package/dest/crypto.d.ts.map +1 -1
  11. package/dest/crypto.js +88 -0
  12. package/dest/extension/handlers/background_connection_handler.d.ts +12 -2
  13. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -1
  14. package/dest/extension/handlers/background_connection_handler.js +44 -8
  15. package/dest/extension/handlers/content_script_connection_handler.d.ts +2 -1
  16. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -1
  17. package/dest/extension/handlers/content_script_connection_handler.js +19 -0
  18. package/dest/extension/handlers/internal_message_types.d.ts +3 -1
  19. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -1
  20. package/dest/extension/handlers/internal_message_types.js +3 -1
  21. package/dest/extension/provider/extension_wallet.d.ts +26 -6
  22. package/dest/extension/provider/extension_wallet.d.ts.map +1 -1
  23. package/dest/extension/provider/extension_wallet.js +80 -9
  24. package/dest/extension/provider/index.d.ts +2 -2
  25. package/dest/extension/provider/index.d.ts.map +1 -1
  26. package/dest/iframe/handlers/iframe_connection_handler.d.ts +122 -0
  27. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -0
  28. package/dest/iframe/handlers/iframe_connection_handler.js +239 -0
  29. package/dest/iframe/handlers/index.d.ts +2 -0
  30. package/dest/iframe/handlers/index.d.ts.map +1 -0
  31. package/dest/iframe/handlers/index.js +1 -0
  32. package/dest/iframe/provider/iframe_discovery.d.ts +25 -0
  33. package/dest/iframe/provider/iframe_discovery.d.ts.map +1 -0
  34. package/dest/iframe/provider/iframe_discovery.js +167 -0
  35. package/dest/iframe/provider/iframe_provider.d.ts +65 -0
  36. package/dest/iframe/provider/iframe_provider.d.ts.map +1 -0
  37. package/dest/iframe/provider/iframe_provider.js +257 -0
  38. package/dest/iframe/provider/iframe_wallet.d.ts +85 -0
  39. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -0
  40. package/dest/iframe/provider/iframe_wallet.js +269 -0
  41. package/dest/iframe/provider/index.d.ts +4 -0
  42. package/dest/iframe/provider/index.d.ts.map +1 -0
  43. package/dest/iframe/provider/index.js +3 -0
  44. package/dest/manager/types.d.ts +3 -2
  45. package/dest/manager/types.d.ts.map +1 -1
  46. package/dest/manager/wallet_manager.d.ts +1 -1
  47. package/dest/manager/wallet_manager.d.ts.map +1 -1
  48. package/dest/manager/wallet_manager.js +46 -16
  49. package/dest/types.d.ts +64 -2
  50. package/dest/types.d.ts.map +1 -1
  51. package/dest/types.js +29 -0
  52. package/package.json +12 -8
  53. package/src/base-wallet/base_wallet.ts +255 -129
  54. package/src/base-wallet/index.ts +6 -1
  55. package/src/base-wallet/utils.ts +15 -5
  56. package/src/crypto.ts +104 -0
  57. package/src/extension/handlers/background_connection_handler.ts +42 -9
  58. package/src/extension/handlers/content_script_connection_handler.ts +18 -0
  59. package/src/extension/handlers/internal_message_types.ts +2 -0
  60. package/src/extension/provider/extension_wallet.ts +94 -13
  61. package/src/extension/provider/index.ts +1 -1
  62. package/src/iframe/handlers/iframe_connection_handler.ts +341 -0
  63. package/src/iframe/handlers/index.ts +7 -0
  64. package/src/iframe/provider/iframe_discovery.ts +185 -0
  65. package/src/iframe/provider/iframe_provider.ts +331 -0
  66. package/src/iframe/provider/iframe_wallet.ts +323 -0
  67. package/src/iframe/provider/index.ts +3 -0
  68. package/src/manager/types.ts +2 -1
  69. package/src/manager/wallet_manager.ts +48 -14
  70. package/src/types.ts +72 -0
@@ -1,34 +1,37 @@
1
- import type { Account } from '@aztec/aztec.js/account';
1
+ import type { Account, NoFrom } from '@aztec/aztec.js/account';
2
+ import { NO_FROM } from '@aztec/aztec.js/account';
2
3
  import type { CallIntent, IntentInnerHash } from '@aztec/aztec.js/authorization';
3
- import { type InteractionWaitOptions, NO_WAIT, type SendReturn } from '@aztec/aztec.js/contracts';
4
+ import {
5
+ type InteractionWaitOptions,
6
+ NO_WAIT,
7
+ type SendReturn,
8
+ extractOffchainOutput,
9
+ } from '@aztec/aztec.js/contracts';
4
10
  import type { FeePaymentMethod } from '@aztec/aztec.js/fee';
5
11
  import { waitForTx } from '@aztec/aztec.js/node';
6
- import type {
7
- Aliased,
8
- AppCapabilities,
9
- BatchResults,
10
- BatchedMethod,
11
- ExecuteUtilityOptions,
12
- PrivateEvent,
13
- PrivateEventFilter,
14
- ProfileOptions,
15
- SendOptions,
16
- SimulateOptions,
17
- Wallet,
18
- WalletCapabilities,
19
- } from '@aztec/aztec.js/wallet';
20
12
  import {
21
- GAS_ESTIMATION_DA_GAS_LIMIT,
22
- GAS_ESTIMATION_L2_GAS_LIMIT,
23
- GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT,
24
- GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT,
25
- } 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';
26
28
  import { AccountFeePaymentMethodOptions, type DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
29
+ import { DefaultEntrypoint } from '@aztec/entrypoints/default';
27
30
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
28
31
  import { Fr } from '@aztec/foundation/curves/bn254';
29
32
  import { createLogger } from '@aztec/foundation/log';
30
33
  import type { FieldsOf } from '@aztec/foundation/types';
31
- import { type AccessScopes, displayDebugLogs } from '@aztec/pxe/client/lazy';
34
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
32
35
  import type { PXE, PackedPrivateEvent } from '@aztec/pxe/server';
33
36
  import {
34
37
  type ContractArtifact,
@@ -40,21 +43,25 @@ import type { AuthWitness } from '@aztec/stdlib/auth-witness';
40
43
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
41
44
  import {
42
45
  type ContractInstanceWithAddress,
46
+ type NodeInfo,
43
47
  computePartialAddress,
44
48
  getContractClassFromArtifact,
45
49
  } from '@aztec/stdlib/contract';
46
50
  import { SimulationError } from '@aztec/stdlib/errors';
47
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
48
- 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';
49
56
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
50
57
  import {
51
58
  BlockHeader,
59
+ ExecutionPayload,
52
60
  type TxExecutionRequest,
53
61
  type TxProfileResult,
54
- TxSimulationResult,
55
62
  type UtilityExecutionResult,
63
+ mergeExecutionPayloads,
56
64
  } from '@aztec/stdlib/tx';
57
- import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
58
65
 
59
66
  import { inspect } from 'util';
60
67
 
@@ -70,17 +77,46 @@ export type FeeOptions = {
70
77
  */
71
78
  walletFeePaymentMethod?: FeePaymentMethod;
72
79
  /** Configuration options for the account to properly handle the selected fee payment method */
73
- accountFeePaymentMethodOptions: AccountFeePaymentMethodOptions;
80
+ accountFeePaymentMethodOptions?: AccountFeePaymentMethodOptions;
74
81
  /** The gas settings to use for the transaction */
75
82
  gasSettings: GasSettings;
76
83
  };
77
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
+
78
111
  /**
79
112
  * A base class for Wallet implementations
80
113
  */
81
114
  export abstract class BaseWallet implements Wallet {
82
115
  protected minFeePadding = 0.5;
83
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;
84
120
 
85
121
  // Protected because we want to force wallets to instantiate their own PXE.
86
122
  protected constructor(
@@ -89,12 +125,23 @@ export abstract class BaseWallet implements Wallet {
89
125
  protected log = createLogger('wallet-sdk:base_wallet'),
90
126
  ) {}
91
127
 
92
- protected scopesFrom(from: AztecAddress, additionalScopes: AztecAddress[] = []): AztecAddress[] {
93
- 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];
94
130
  const scopeSet = new Set(allScopes.map(address => address.toString()));
95
131
  return [...scopeSet].map(AztecAddress.fromString);
96
132
  }
97
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
+
98
145
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
99
146
 
100
147
  abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
@@ -112,32 +159,42 @@ export abstract class BaseWallet implements Wallet {
112
159
  }
113
160
 
114
161
  async getChainInfo(): Promise<ChainInfo> {
115
- 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;
116
166
  return { chainId: new Fr(l1ChainId), version: new Fr(rollupVersion) };
117
167
  }
118
168
 
119
169
  protected async createTxExecutionRequestFromPayloadAndFee(
120
170
  executionPayload: ExecutionPayload,
121
- from: AztecAddress,
171
+ from: AztecAddress | NoFrom,
122
172
  feeOptions: FeeOptions,
123
173
  ): Promise<TxExecutionRequest> {
124
174
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
125
- const executionOptions: DefaultAccountEntrypointOptions = {
126
- txNonce: Fr.random(),
127
- cancellable: this.cancellableTransactions,
128
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
129
- };
130
175
  const finalExecutionPayload = feeExecutionPayload
131
176
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
132
177
  : executionPayload;
133
- const fromAccount = await this.getAccountFromAddress(from);
134
178
  const chainInfo = await this.getChainInfo();
135
- return fromAccount.createTxExecutionRequest(
136
- finalExecutionPayload,
137
- feeOptions.gasSettings,
138
- chainInfo,
139
- executionOptions,
140
- );
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
+ }
141
198
  }
142
199
 
143
200
  public async createAuthWit(
@@ -186,31 +243,39 @@ export abstract class BaseWallet implements Wallet {
186
243
 
187
244
  /**
188
245
  * Completes partial user-provided fee options with wallet defaults.
189
- * @param from - The address where the transaction is being sent from
190
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
191
- * @param gasSettings - User-provided partial gas settings
192
- * @returns - Complete fee options that can be used to create a transaction execution request
246
+ * @param config - Fee completion config.
193
247
  */
194
- protected async completeFeeOptions(
195
- from: AztecAddress,
196
- feePayer?: AztecAddress,
197
- gasSettings?: Partial<FieldsOf<GasSettings>>,
198
- ): Promise<FeeOptions> {
248
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
249
+ const { from, feePayer, gasSettings, forEstimation, congestionEstimate } = config;
199
250
  const maxFeesPerGas =
200
- gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
251
+ gasSettings?.maxFeesPerGas ?? (await this.getMinFees(congestionEstimate)).mul(1 + this.minFeePadding);
201
252
  let accountFeePaymentMethodOptions;
202
- // The transaction does not include a fee payment method, so we set the flag
203
- // for the account to use its fee juice balance
204
- if (!feePayer) {
205
- accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
206
- } else {
207
- // The transaction includes fee payment method, so we check if we are the fee payer for it
208
- // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
209
- accountFeePaymentMethodOptions = from.equals(feePayer)
210
- ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
211
- : 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
+ }
212
267
  }
213
- 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);
214
279
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
215
280
  return {
216
281
  gasSettings: fullGasSettings,
@@ -220,34 +285,25 @@ export abstract class BaseWallet implements Wallet {
220
285
  }
221
286
 
222
287
  /**
223
- * Completes partial user-provided fee options with unreasonably high gas limits
224
- * for gas estimation. Uses the same logic as completeFeeOptions but sets high limits
225
- * to avoid running out of gas during estimation.
226
- * @param from - The address where the transaction is being sent from
227
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
228
- * @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.
229
291
  */
230
- protected async completeFeeOptionsForEstimation(
231
- from: AztecAddress,
232
- feePayer?: AztecAddress,
233
- gasSettings?: Partial<FieldsOf<GasSettings>>,
234
- ) {
235
- const defaultFeeOptions = await this.completeFeeOptions(from, feePayer, gasSettings);
236
- const {
237
- gasSettings: { maxFeesPerGas, maxPriorityFeesPerGas },
238
- } = defaultFeeOptions;
239
- // Use unrealistically high gas limits for estimation to avoid running out of gas.
240
- // They will be tuned down after the simulation.
241
- const gasSettingsForEstimation = new GasSettings(
242
- new Gas(GAS_ESTIMATION_DA_GAS_LIMIT, GAS_ESTIMATION_L2_GAS_LIMIT),
243
- new Gas(GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT),
244
- maxFeesPerGas,
245
- maxPriorityFeesPerGas,
246
- );
247
- return {
248
- ...defaultFeeOptions,
249
- gasSettings: gasSettingsForEstimation,
250
- };
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
+ }
251
307
  }
252
308
 
253
309
  registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
@@ -292,25 +348,45 @@ export abstract class BaseWallet implements Wallet {
292
348
  return instance;
293
349
  }
294
350
 
351
+ registerContractClass(artifact: ContractArtifact): Promise<void> {
352
+ return this.pxe.registerContractClass(artifact);
353
+ }
354
+
295
355
  /**
296
356
  * Simulates calls through the standard PXE path (account entrypoint).
297
357
  * @param executionPayload - The execution payload to simulate.
298
- * @param from - The sender address.
299
- * @param feeOptions - Fee options for the transaction.
300
- * @param skipTxValidation - Whether to skip tx validation.
301
- * @param skipFeeEnforcement - Whether to skip fee enforcement.
302
- * @param scopes - The scopes to use for the simulation.
358
+ * @param opts - Simulation options.
303
359
  */
304
- protected async simulateViaEntrypoint(
305
- executionPayload: ExecutionPayload,
306
- from: AztecAddress,
307
- feeOptions: FeeOptions,
308
- scopes: AccessScopes,
309
- skipTxValidation?: boolean,
310
- skipFeeEnforcement?: boolean,
311
- ) {
312
- const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, from, feeOptions);
313
- 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
314
390
  }
315
391
 
316
392
  /**
@@ -321,10 +397,17 @@ export abstract class BaseWallet implements Wallet {
321
397
  * @param opts - Simulation options (from address, fee settings, etc.).
322
398
  * @returns The merged simulation result.
323
399
  */
324
- async simulateTx(executionPayload: ExecutionPayload, opts: SimulateOptions): Promise<TxSimulationResult> {
325
- const feeOptions = opts.fee?.estimateGas
326
- ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings)
327
- : 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
+ });
328
411
  const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
329
412
  const remainingPayload = { ...executionPayload, calls: remainingCalls };
330
413
 
@@ -335,31 +418,34 @@ export abstract class BaseWallet implements Wallet {
335
418
  try {
336
419
  blockHeader = await this.pxe.getSyncedBlockHeader();
337
420
  } catch {
338
- blockHeader = (await this.aztecNode.getBlockHeader())!;
421
+ blockHeader = (await this.aztecNode.getBlockData('latest'))!.header;
339
422
  }
340
423
 
424
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
341
425
  const [optimizedResults, normalResult] = await Promise.all([
342
426
  optimizableCalls.length > 0
343
427
  ? simulateViaNode(
344
428
  this.aztecNode,
345
429
  optimizableCalls,
346
- opts.from,
430
+ simulationOrigin,
347
431
  chainInfo,
348
432
  feeOptions.gasSettings,
349
433
  blockHeader,
350
434
  opts.skipFeeEnforcement ?? true,
351
435
  this.getContractName.bind(this),
436
+ opts.overrides,
352
437
  )
353
438
  : Promise.resolve([]),
354
439
  remainingCalls.length > 0
355
- ? this.simulateViaEntrypoint(
356
- remainingPayload,
357
- opts.from,
440
+ ? this.simulateViaEntrypoint(remainingPayload, {
441
+ from: opts.from,
358
442
  feeOptions,
359
- this.scopesFrom(opts.from, opts.additionalScopes),
360
- opts.skipTxValidation,
361
- opts.skipFeeEnforcement ?? true,
362
- )
443
+ additionalScopes: opts.additionalScopes,
444
+ skipTxValidation: opts.skipTxValidation,
445
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
446
+ sendMessagesAs: opts.sendMessagesAs,
447
+ overrides: opts.overrides,
448
+ })
363
449
  : Promise.resolve(null),
364
450
  ]);
365
451
 
@@ -367,12 +453,18 @@ export abstract class BaseWallet implements Wallet {
367
453
  }
368
454
 
369
455
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
370
- 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
+ });
371
462
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
372
463
  return this.pxe.profileTx(txRequest, {
373
464
  profileMode: opts.profileMode,
374
465
  skipProofGeneration: opts.skipProofGeneration ?? true,
375
466
  scopes: this.scopesFrom(opts.from, opts.additionalScopes),
467
+ senderForTags: this.senderForTagsFrom(opts.from, opts.sendMessagesAs),
376
468
  });
377
469
  }
378
470
 
@@ -380,9 +472,21 @@ export abstract class BaseWallet implements Wallet {
380
472
  executionPayload: ExecutionPayload,
381
473
  opts: SendOptions<W>,
382
474
  ): Promise<SendReturn<W>> {
383
- 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
+ });
384
481
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
385
- 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
+ });
486
+ const offchainOutput = extractOffchainOutput(
487
+ provenTx.getOffchainEffects(),
488
+ provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
489
+ );
386
490
  const tx = await provenTx.toTx();
387
491
  const txHash = tx.getTxHash();
388
492
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -396,7 +500,7 @@ export abstract class BaseWallet implements Wallet {
396
500
 
397
501
  // If wait is NO_WAIT, return txHash immediately
398
502
  if (opts.wait === NO_WAIT) {
399
- return txHash as SendReturn<W>;
503
+ return { txHash, ...offchainOutput } as SendReturn<W>;
400
504
  }
401
505
 
402
506
  // Otherwise, wait for the full receipt (default behavior on wait: undefined)
@@ -408,7 +512,7 @@ export abstract class BaseWallet implements Wallet {
408
512
  await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
409
513
  }
410
514
 
411
- return receipt as SendReturn<W>;
515
+ return { receipt, ...offchainOutput } as SendReturn<W>;
412
516
  }
413
517
 
414
518
  /**
@@ -439,7 +543,7 @@ export abstract class BaseWallet implements Wallet {
439
543
  }
440
544
 
441
545
  executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
442
- return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: [opts.scope] });
546
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: opts.scopes });
443
547
  }
444
548
 
445
549
  async getPrivateEvents<T>(
@@ -462,17 +566,39 @@ export abstract class BaseWallet implements Wallet {
462
566
  return decodedEvents;
463
567
  }
464
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
+ */
465
573
  async getContractMetadata(address: AztecAddress) {
466
574
  const instance = await this.pxe.getContractInstance(address);
467
- const initNullifier = await siloNullifier(address, address.toField());
468
- const publiclyRegisteredContract = await this.aztecNode.getContract(address);
469
- 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;
470
596
  const isContractUpdated =
471
597
  publiclyRegisteredContract &&
472
598
  !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
473
599
  return {
474
600
  instance: instance ?? undefined,
475
- isContractInitialized: !!initNullifierMembershipWitness,
601
+ initializationStatus,
476
602
  isContractPublished: !!publiclyRegisteredContract,
477
603
  isContractUpdated: !!isContractUpdated,
478
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';