@aztec/wallet-sdk 0.0.1-commit.dbf9cec → 0.0.1-commit.ddcf04837

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 (57) hide show
  1. package/dest/base-wallet/base_wallet.d.ts +50 -39
  2. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  3. package/dest/base-wallet/base_wallet.js +145 -72
  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 +3 -2
  7. package/dest/base-wallet/utils.d.ts.map +1 -1
  8. package/dest/base-wallet/utils.js +3 -1
  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/provider/extension_wallet.d.ts +2 -5
  13. package/dest/extension/provider/extension_wallet.d.ts.map +1 -1
  14. package/dest/extension/provider/index.d.ts +2 -2
  15. package/dest/extension/provider/index.d.ts.map +1 -1
  16. package/dest/iframe/handlers/iframe_connection_handler.d.ts +118 -0
  17. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -0
  18. package/dest/iframe/handlers/iframe_connection_handler.js +228 -0
  19. package/dest/iframe/handlers/index.d.ts +2 -0
  20. package/dest/iframe/handlers/index.d.ts.map +1 -0
  21. package/dest/iframe/handlers/index.js +1 -0
  22. package/dest/iframe/provider/iframe_discovery.d.ts +25 -0
  23. package/dest/iframe/provider/iframe_discovery.d.ts.map +1 -0
  24. package/dest/iframe/provider/iframe_discovery.js +167 -0
  25. package/dest/iframe/provider/iframe_provider.d.ts +65 -0
  26. package/dest/iframe/provider/iframe_provider.d.ts.map +1 -0
  27. package/dest/iframe/provider/iframe_provider.js +257 -0
  28. package/dest/iframe/provider/iframe_wallet.d.ts +68 -0
  29. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -0
  30. package/dest/iframe/provider/iframe_wallet.js +200 -0
  31. package/dest/iframe/provider/index.d.ts +4 -0
  32. package/dest/iframe/provider/index.d.ts.map +1 -0
  33. package/dest/iframe/provider/index.js +3 -0
  34. package/dest/manager/types.d.ts +3 -2
  35. package/dest/manager/types.d.ts.map +1 -1
  36. package/dest/manager/wallet_manager.d.ts +1 -1
  37. package/dest/manager/wallet_manager.d.ts.map +1 -1
  38. package/dest/manager/wallet_manager.js +46 -16
  39. package/dest/types.d.ts +14 -2
  40. package/dest/types.d.ts.map +1 -1
  41. package/dest/types.js +4 -0
  42. package/package.json +12 -8
  43. package/src/base-wallet/base_wallet.ts +221 -126
  44. package/src/base-wallet/index.ts +6 -1
  45. package/src/base-wallet/utils.ts +6 -4
  46. package/src/crypto.ts +104 -0
  47. package/src/extension/provider/extension_wallet.ts +1 -6
  48. package/src/extension/provider/index.ts +1 -1
  49. package/src/iframe/handlers/iframe_connection_handler.ts +328 -0
  50. package/src/iframe/handlers/index.ts +7 -0
  51. package/src/iframe/provider/iframe_discovery.ts +185 -0
  52. package/src/iframe/provider/iframe_provider.ts +331 -0
  53. package/src/iframe/provider/iframe_wallet.ts +229 -0
  54. package/src/iframe/provider/index.ts +3 -0
  55. package/src/manager/types.ts +2 -1
  56. package/src/manager/wallet_manager.ts +48 -14
  57. package/src/types.ts +13 -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,
@@ -44,17 +47,20 @@ import {
44
47
  getContractClassFromArtifact,
45
48
  } from '@aztec/stdlib/contract';
46
49
  import { SimulationError } from '@aztec/stdlib/errors';
47
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
48
- import { siloNullifier } from '@aztec/stdlib/hash';
50
+ import { Gas, GasFees, GasSettings, ManaUsageEstimate } from '@aztec/stdlib/gas';
51
+ import {
52
+ computeSiloedPrivateInitializationNullifier,
53
+ computeSiloedPublicInitializationNullifier,
54
+ } from '@aztec/stdlib/hash';
49
55
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
50
56
  import {
51
57
  BlockHeader,
58
+ ExecutionPayload,
52
59
  type TxExecutionRequest,
53
60
  type TxProfileResult,
54
- TxSimulationResult,
55
61
  type UtilityExecutionResult,
62
+ mergeExecutionPayloads,
56
63
  } from '@aztec/stdlib/tx';
57
- import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
58
64
 
59
65
  import { inspect } from 'util';
60
66
 
@@ -70,11 +76,37 @@ export type FeeOptions = {
70
76
  */
71
77
  walletFeePaymentMethod?: FeePaymentMethod;
72
78
  /** Configuration options for the account to properly handle the selected fee payment method */
73
- accountFeePaymentMethodOptions: AccountFeePaymentMethodOptions;
79
+ accountFeePaymentMethodOptions?: AccountFeePaymentMethodOptions;
74
80
  /** The gas settings to use for the transaction */
75
81
  gasSettings: GasSettings;
76
82
  };
77
83
 
84
+ /** Options for `simulateViaEntrypoint`. */
85
+ export type SimulateViaEntrypointOptions = Pick<
86
+ SimulateOptions,
87
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement'
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
+ * Assumed network congestion level for fee prediction. Controls how aggressively the wallet
105
+ * estimates future fees. Defaults to Limit (worst case) when not specified.
106
+ */
107
+ congestionEstimate?: ManaUsageEstimate;
108
+ };
109
+
78
110
  /**
79
111
  * A base class for Wallet implementations
80
112
  */
@@ -89,8 +121,8 @@ export abstract class BaseWallet implements Wallet {
89
121
  protected log = createLogger('wallet-sdk:base_wallet'),
90
122
  ) {}
91
123
 
92
- protected scopesFrom(from: AztecAddress, additionalScopes: AztecAddress[] = []): AztecAddress[] {
93
- const allScopes = from.isZero() ? additionalScopes : [from, ...additionalScopes];
124
+ protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
125
+ const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
94
126
  const scopeSet = new Set(allScopes.map(address => address.toString()));
95
127
  return [...scopeSet].map(AztecAddress.fromString);
96
128
  }
@@ -118,26 +150,33 @@ export abstract class BaseWallet implements Wallet {
118
150
 
119
151
  protected async createTxExecutionRequestFromPayloadAndFee(
120
152
  executionPayload: ExecutionPayload,
121
- from: AztecAddress,
153
+ from: AztecAddress | NoFrom,
122
154
  feeOptions: FeeOptions,
123
155
  ): Promise<TxExecutionRequest> {
124
156
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
125
- const executionOptions: DefaultAccountEntrypointOptions = {
126
- txNonce: Fr.random(),
127
- cancellable: this.cancellableTransactions,
128
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
129
- };
130
157
  const finalExecutionPayload = feeExecutionPayload
131
158
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
132
159
  : executionPayload;
133
- const fromAccount = await this.getAccountFromAddress(from);
134
160
  const chainInfo = await this.getChainInfo();
135
- return fromAccount.createTxExecutionRequest(
136
- finalExecutionPayload,
137
- feeOptions.gasSettings,
138
- chainInfo,
139
- executionOptions,
140
- );
161
+
162
+ if (from === NO_FROM) {
163
+ const entrypoint = new DefaultEntrypoint();
164
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
165
+ } else {
166
+ const fromAccount = await this.getAccountFromAddress(from);
167
+ const executionOptions: DefaultAccountEntrypointOptions = {
168
+ txNonce: Fr.random(),
169
+ cancellable: this.cancellableTransactions,
170
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
171
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
172
+ };
173
+ return fromAccount.createTxExecutionRequest(
174
+ finalExecutionPayload,
175
+ feeOptions.gasSettings,
176
+ chainInfo,
177
+ executionOptions,
178
+ );
179
+ }
141
180
  }
142
181
 
143
182
  public async createAuthWit(
@@ -186,31 +225,39 @@ export abstract class BaseWallet implements Wallet {
186
225
 
187
226
  /**
188
227
  * 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
228
+ * @param config - Fee completion config.
193
229
  */
194
- protected async completeFeeOptions(
195
- from: AztecAddress,
196
- feePayer?: AztecAddress,
197
- gasSettings?: Partial<FieldsOf<GasSettings>>,
198
- ): Promise<FeeOptions> {
230
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
231
+ const { from, feePayer, gasSettings, forEstimation, congestionEstimate } = config;
199
232
  const maxFeesPerGas =
200
- gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
233
+ gasSettings?.maxFeesPerGas ?? (await this.getMinFees(congestionEstimate)).mul(1 + this.minFeePadding);
201
234
  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;
235
+ // If from is an address, we need to determine the appropriate fee payment method options for the
236
+ // account contract entrypoint to use
237
+ if (from !== NO_FROM) {
238
+ if (!feePayer) {
239
+ // The transaction does not include a fee payment method, so we set the flag
240
+ // for the account to use its fee juice balance
241
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
242
+ } else {
243
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
244
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
245
+ accountFeePaymentMethodOptions = from.equals(feePayer)
246
+ ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
247
+ : AccountFeePaymentMethodOptions.EXTERNAL;
248
+ }
212
249
  }
213
- const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
250
+ const gasSettingsOverrides = {
251
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
252
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
253
+ maxFeesPerGas,
254
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty(),
255
+ };
256
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
257
+ // When sending for real, use protocol max limits that the network will actually accept.
258
+ const fullGasSettings = forEstimation
259
+ ? GasSettings.forEstimation(gasSettingsOverrides)
260
+ : GasSettings.fallback(gasSettingsOverrides);
214
261
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
215
262
  return {
216
263
  gasSettings: fullGasSettings,
@@ -220,34 +267,25 @@ export abstract class BaseWallet implements Wallet {
220
267
  }
221
268
 
222
269
  /**
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
270
+ * Returns the worst-case min fee across predicted future slots.
271
+ * Falls back to getCurrentMinFees if the node doesn't support getPredictedMinFees.
272
+ * @param estimate - The mana usage estimate to use for fee prediction. Defaults to Limit for conservative estimation.
229
273
  */
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
- };
274
+ protected async getMinFees(estimate: ManaUsageEstimate = ManaUsageEstimate.Limit): Promise<GasFees> {
275
+ try {
276
+ const predicted = await this.aztecNode.getPredictedMinFees(estimate);
277
+ if (predicted.length === 0) {
278
+ return this.aztecNode.getCurrentMinFees();
279
+ }
280
+ return predicted.reduce((worst, fees) => (fees.feePerL2Gas > worst.feePerL2Gas ? fees : worst));
281
+ } catch (err: any) {
282
+ // Fallback for old nodes that don't support getPredictedMinFees.
283
+ // Only fall back on method-not-found errors (JSON-RPC code -32601); rethrow others.
284
+ if (err?.cause?.code === -32601 || err?.message?.includes('Method not found')) {
285
+ return this.aztecNode.getCurrentMinFees();
286
+ }
287
+ throw err;
288
+ }
251
289
  }
252
290
 
253
291
  registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
@@ -295,22 +333,36 @@ export abstract class BaseWallet implements Wallet {
295
333
  /**
296
334
  * Simulates calls through the standard PXE path (account entrypoint).
297
335
  * @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.
336
+ * @param opts - Simulation options.
303
337
  */
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 });
338
+ protected async simulateViaEntrypoint(executionPayload: ExecutionPayload, opts: SimulateViaEntrypointOptions) {
339
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(
340
+ executionPayload,
341
+ opts.from,
342
+ opts.feeOptions,
343
+ );
344
+ const result = await this.pxe.simulateTx(txRequest, {
345
+ simulatePublic: true,
346
+ skipTxValidation: opts.skipTxValidation,
347
+ skipFeeEnforcement: opts.skipFeeEnforcement,
348
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
349
+ });
350
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
351
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
352
+ }
353
+
354
+ /**
355
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
356
+ * calls, N+1 = app).
357
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
358
+ * @param feeOptions - Fee options containing the wallet fee payment method.
359
+ */
360
+ protected async computeAppCallOffset(from: AztecAddress | NoFrom, feeOptions: FeeOptions): Promise<number> {
361
+ if (from === NO_FROM) {
362
+ return 0;
363
+ }
364
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
365
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
314
366
  }
315
367
 
316
368
  /**
@@ -321,10 +373,17 @@ export abstract class BaseWallet implements Wallet {
321
373
  * @param opts - Simulation options (from address, fee settings, etc.).
322
374
  * @returns The merged simulation result.
323
375
  */
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);
376
+ async simulateTx(
377
+ executionPayload: ExecutionPayload,
378
+ opts: SimulateOptions,
379
+ ): Promise<TxSimulationResultWithAppOffset> {
380
+ const feeOptions = await this.completeFeeOptions({
381
+ from: opts.from,
382
+ feePayer: executionPayload.feePayer,
383
+ gasSettings: opts.fee?.gasSettings,
384
+ forEstimation: true,
385
+ congestionEstimate: opts.fee?.congestionEstimate,
386
+ });
328
387
  const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
329
388
  const remainingPayload = { ...executionPayload, calls: remainingCalls };
330
389
 
@@ -338,12 +397,13 @@ export abstract class BaseWallet implements Wallet {
338
397
  blockHeader = (await this.aztecNode.getBlockHeader())!;
339
398
  }
340
399
 
400
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
341
401
  const [optimizedResults, normalResult] = await Promise.all([
342
402
  optimizableCalls.length > 0
343
403
  ? simulateViaNode(
344
404
  this.aztecNode,
345
405
  optimizableCalls,
346
- opts.from,
406
+ simulationOrigin,
347
407
  chainInfo,
348
408
  feeOptions.gasSettings,
349
409
  blockHeader,
@@ -352,14 +412,13 @@ export abstract class BaseWallet implements Wallet {
352
412
  )
353
413
  : Promise.resolve([]),
354
414
  remainingCalls.length > 0
355
- ? this.simulateViaEntrypoint(
356
- remainingPayload,
357
- opts.from,
415
+ ? this.simulateViaEntrypoint(remainingPayload, {
416
+ from: opts.from,
358
417
  feeOptions,
359
- this.scopesFrom(opts.from, opts.additionalScopes),
360
- opts.skipTxValidation,
361
- opts.skipFeeEnforcement ?? true,
362
- )
418
+ additionalScopes: opts.additionalScopes,
419
+ skipTxValidation: opts.skipTxValidation,
420
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
421
+ })
363
422
  : Promise.resolve(null),
364
423
  ]);
365
424
 
@@ -367,7 +426,12 @@ export abstract class BaseWallet implements Wallet {
367
426
  }
368
427
 
369
428
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
370
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
429
+ const feeOptions = await this.completeFeeOptions({
430
+ from: opts.from,
431
+ feePayer: executionPayload.feePayer,
432
+ gasSettings: opts.fee?.gasSettings,
433
+ congestionEstimate: opts.fee?.congestionEstimate,
434
+ });
371
435
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
372
436
  return this.pxe.profileTx(txRequest, {
373
437
  profileMode: opts.profileMode,
@@ -380,9 +444,18 @@ export abstract class BaseWallet implements Wallet {
380
444
  executionPayload: ExecutionPayload,
381
445
  opts: SendOptions<W>,
382
446
  ): Promise<SendReturn<W>> {
383
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
447
+ const feeOptions = await this.completeFeeOptions({
448
+ from: opts.from,
449
+ feePayer: executionPayload.feePayer,
450
+ gasSettings: opts.fee?.gasSettings,
451
+ congestionEstimate: opts.fee?.congestionEstimate,
452
+ });
384
453
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
385
454
  const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
455
+ const offchainOutput = extractOffchainOutput(
456
+ provenTx.getOffchainEffects(),
457
+ provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
458
+ );
386
459
  const tx = await provenTx.toTx();
387
460
  const txHash = tx.getTxHash();
388
461
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -396,7 +469,7 @@ export abstract class BaseWallet implements Wallet {
396
469
 
397
470
  // If wait is NO_WAIT, return txHash immediately
398
471
  if (opts.wait === NO_WAIT) {
399
- return txHash as SendReturn<W>;
472
+ return { txHash, ...offchainOutput } as SendReturn<W>;
400
473
  }
401
474
 
402
475
  // Otherwise, wait for the full receipt (default behavior on wait: undefined)
@@ -408,7 +481,7 @@ export abstract class BaseWallet implements Wallet {
408
481
  await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
409
482
  }
410
483
 
411
- return receipt as SendReturn<W>;
484
+ return { receipt, ...offchainOutput } as SendReturn<W>;
412
485
  }
413
486
 
414
487
  /**
@@ -439,7 +512,7 @@ export abstract class BaseWallet implements Wallet {
439
512
  }
440
513
 
441
514
  executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
442
- return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: [opts.scope] });
515
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: opts.scopes });
443
516
  }
444
517
 
445
518
  async getPrivateEvents<T>(
@@ -462,17 +535,39 @@ export abstract class BaseWallet implements Wallet {
462
535
  return decodedEvents;
463
536
  }
464
537
 
538
+ /**
539
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
540
+ * @param address - The contract address to query.
541
+ */
465
542
  async getContractMetadata(address: AztecAddress) {
466
543
  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);
544
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
545
+
546
+ let initializationStatus: ContractInitializationStatus;
547
+ if (instance) {
548
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
549
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
550
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
551
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
552
+ initializationStatus = witness
553
+ ? ContractInitializationStatus.INITIALIZED
554
+ : ContractInitializationStatus.UNINITIALIZED;
555
+ } else {
556
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
557
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
558
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
559
+ // uninitialized.
560
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
561
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
562
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
563
+ }
564
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
470
565
  const isContractUpdated =
471
566
  publiclyRegisteredContract &&
472
567
  !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
473
568
  return {
474
569
  instance: instance ?? undefined,
475
- isContractInitialized: !!initNullifierMembershipWitness,
570
+ initializationStatus,
476
571
  isContractPublished: !!publiclyRegisteredContract,
477
572
  isContractUpdated: !!isContractUpdated,
478
573
  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';
@@ -214,13 +215,13 @@ export async function simulateViaNode(
214
215
  */
215
216
  export function buildMergedSimulationResult(
216
217
  optimizedResults: TxSimulationResult[],
217
- normalResult: TxSimulationResult | null,
218
- ): TxSimulationResult {
218
+ normalResult: TxSimulationResultWithAppOffset | null,
219
+ ): TxSimulationResultWithAppOffset {
219
220
  const optimizedReturnValues = optimizedResults.flatMap(r => r.publicOutput?.publicReturnValues ?? []);
220
221
  const normalReturnValues = normalResult?.publicOutput?.publicReturnValues ?? [];
221
222
  const allReturnValues = [...optimizedReturnValues, ...normalReturnValues];
222
223
 
223
- const baseResult = normalResult ?? optimizedResults[0];
224
+ const baseResult: TxSimulationResult = normalResult ?? optimizedResults[0];
224
225
 
225
226
  const mergedPublicOutput: PublicSimulationOutput | undefined = baseResult.publicOutput
226
227
  ? {
@@ -229,10 +230,11 @@ export function buildMergedSimulationResult(
229
230
  }
230
231
  : undefined;
231
232
 
232
- return new TxSimulationResult(
233
+ const merged = new TxSimulationResult(
233
234
  baseResult.privateExecutionResult,
234
235
  baseResult.publicInputs,
235
236
  mergedPublicOutput,
236
237
  normalResult?.stats,
237
238
  );
239
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(merged, normalResult?.appCallOffset ?? 0);
238
240
  }
package/src/crypto.ts CHANGED
@@ -497,3 +497,107 @@ export function hashToEmoji(hash: string, count: number = DEFAULT_EMOJI_GRID_SIZ
497
497
  }
498
498
  return emojis.join('');
499
499
  }
500
+
501
+ // ─── Passphrase-based encryption (PBKDF2 + AES-256-GCM) ───────────────────
502
+
503
+ /** Default PBKDF2 iteration count. High to compensate for short PINs (~1-2s on modern hardware). */
504
+ const DEFAULT_PBKDF2_ITERATIONS = 2_000_000;
505
+ const PBKDF2_SALT_BYTES = 16;
506
+ const PBKDF2_IV_BYTES = 12;
507
+
508
+ /**
509
+ * Derives an AES-256-GCM key from a passphrase using PBKDF2-SHA256.
510
+ *
511
+ * @param passphrase - The user-provided passphrase or PIN
512
+ * @param salt - Random salt bytes
513
+ * @param iterations - PBKDF2 iteration count (default: 2,000,000)
514
+ * @returns An AES-256-GCM CryptoKey
515
+ */
516
+ export async function deriveKeyFromPassphrase(
517
+ passphrase: string,
518
+ salt: Uint8Array,
519
+ iterations: number = DEFAULT_PBKDF2_ITERATIONS,
520
+ ): Promise<CryptoKey> {
521
+ const keyMaterial = await crypto.subtle.importKey('raw', new TextEncoder().encode(passphrase), 'PBKDF2', false, [
522
+ 'deriveKey',
523
+ ]);
524
+ return crypto.subtle.deriveKey(
525
+ { name: 'PBKDF2', salt: salt as BufferSource, iterations, hash: 'SHA-256' },
526
+ keyMaterial,
527
+ { name: 'AES-GCM', length: 256 },
528
+ false,
529
+ ['encrypt', 'decrypt'],
530
+ );
531
+ }
532
+
533
+ /**
534
+ * Encrypts arbitrary bytes with a passphrase using PBKDF2 + AES-256-GCM.
535
+ *
536
+ * Output layout: `[salt (16)] [iv (12)] [ciphertext (...)]`
537
+ *
538
+ * @param plaintext - Data to encrypt
539
+ * @param passphrase - User passphrase or PIN
540
+ * @param iterations - PBKDF2 iteration count (default: 2,000,000)
541
+ * @returns A Uint8Array containing salt + iv + ciphertext
542
+ */
543
+ export async function encryptWithPassphrase(
544
+ plaintext: Uint8Array,
545
+ passphrase: string,
546
+ iterations: number = DEFAULT_PBKDF2_ITERATIONS,
547
+ ): Promise<Uint8Array> {
548
+ const salt = crypto.getRandomValues(new Uint8Array(PBKDF2_SALT_BYTES));
549
+ const iv = crypto.getRandomValues(new Uint8Array(PBKDF2_IV_BYTES));
550
+ const key = await deriveKeyFromPassphrase(passphrase, salt, iterations);
551
+ const ciphertext = new Uint8Array(
552
+ await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintext as BufferSource),
553
+ );
554
+ const result = new Uint8Array(PBKDF2_SALT_BYTES + PBKDF2_IV_BYTES + ciphertext.length);
555
+ result.set(salt, 0);
556
+ result.set(iv, PBKDF2_SALT_BYTES);
557
+ result.set(ciphertext, PBKDF2_SALT_BYTES + PBKDF2_IV_BYTES);
558
+ return result;
559
+ }
560
+
561
+ /**
562
+ * Decrypts data produced by {@link encryptWithPassphrase}.
563
+ *
564
+ * @param data - The encrypted blob (salt + iv + ciphertext)
565
+ * @param passphrase - The passphrase used during encryption
566
+ * @param iterations - PBKDF2 iteration count (must match encryption)
567
+ * @returns The decrypted plaintext bytes
568
+ * @throws On wrong passphrase (AES-GCM auth tag mismatch)
569
+ */
570
+ export async function decryptWithPassphrase(
571
+ data: Uint8Array,
572
+ passphrase: string,
573
+ iterations: number = DEFAULT_PBKDF2_ITERATIONS,
574
+ ): Promise<Uint8Array> {
575
+ const salt = data.slice(0, PBKDF2_SALT_BYTES);
576
+ const iv = data.slice(PBKDF2_SALT_BYTES, PBKDF2_SALT_BYTES + PBKDF2_IV_BYTES);
577
+ const ciphertext = data.slice(PBKDF2_SALT_BYTES + PBKDF2_IV_BYTES);
578
+ const key = await deriveKeyFromPassphrase(passphrase, salt, iterations);
579
+ return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext as BufferSource));
580
+ }
581
+
582
+ /**
583
+ * Converts a Uint8Array to a base64 string.
584
+ */
585
+ export function uint8ToBase64(bytes: Uint8Array): string {
586
+ let binary = '';
587
+ for (const b of bytes) {
588
+ binary += String.fromCharCode(b);
589
+ }
590
+ return btoa(binary);
591
+ }
592
+
593
+ /**
594
+ * Converts a base64 string to a Uint8Array.
595
+ */
596
+ export function base64ToUint8(b64: string): Uint8Array {
597
+ const binary = atob(b64);
598
+ const bytes = new Uint8Array(binary.length);
599
+ for (let i = 0; i < binary.length; i++) {
600
+ bytes[i] = binary.charCodeAt(i);
601
+ }
602
+ return bytes;
603
+ }