@aztec/wallet-sdk 0.0.1-commit.ffe5b04ea → 0.0.1-commit.fff30aa

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 +41 -39
  2. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  3. package/dest/base-wallet/base_wallet.js +121 -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 +192 -127
  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,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,18 +43,21 @@ 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 } 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,
57
59
  type TxExecutionRequest,
58
60
  type TxProfileResult,
59
- TxSimulationResult,
60
61
  type UtilityExecutionResult,
61
62
  } from '@aztec/stdlib/tx';
62
63
  import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
@@ -75,17 +76,41 @@ export type FeeOptions = {
75
76
  */
76
77
  walletFeePaymentMethod?: FeePaymentMethod;
77
78
  /** Configuration options for the account to properly handle the selected fee payment method */
78
- accountFeePaymentMethodOptions: AccountFeePaymentMethodOptions;
79
+ accountFeePaymentMethodOptions?: AccountFeePaymentMethodOptions;
79
80
  /** The gas settings to use for the transaction */
80
81
  gasSettings: GasSettings;
81
82
  };
82
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
+
83
105
  /**
84
106
  * A base class for Wallet implementations
85
107
  */
86
108
  export abstract class BaseWallet implements Wallet {
87
109
  protected minFeePadding = 0.5;
88
110
  protected cancellableTransactions = false;
111
+ // A wallet is instantiated for a particular chain, so chain info never changes during its lifetime.
112
+ // We cache it here because getChainInfo is called frequently (every tx simulation, send, auth wit, etc.).
113
+ private nodeInfoPromise: Promise<NodeInfo> | undefined;
89
114
 
90
115
  // Protected because we want to force wallets to instantiate their own PXE.
91
116
  protected constructor(
@@ -94,8 +119,8 @@ export abstract class BaseWallet implements Wallet {
94
119
  protected log = createLogger('wallet-sdk:base_wallet'),
95
120
  ) {}
96
121
 
97
- protected scopesFrom(from: AztecAddress, additionalScopes: AztecAddress[] = []): AztecAddress[] {
98
- const allScopes = from.isZero() ? additionalScopes : [from, ...additionalScopes];
122
+ protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
123
+ const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
99
124
  const scopeSet = new Set(allScopes.map(address => address.toString()));
100
125
  return [...scopeSet].map(AztecAddress.fromString);
101
126
  }
@@ -117,32 +142,42 @@ export abstract class BaseWallet implements Wallet {
117
142
  }
118
143
 
119
144
  async getChainInfo(): Promise<ChainInfo> {
120
- const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
145
+ if (!this.nodeInfoPromise) {
146
+ this.nodeInfoPromise = this.aztecNode.getNodeInfo();
147
+ }
148
+ const { l1ChainId, rollupVersion } = await this.nodeInfoPromise;
121
149
  return { chainId: new Fr(l1ChainId), version: new Fr(rollupVersion) };
122
150
  }
123
151
 
124
152
  protected async createTxExecutionRequestFromPayloadAndFee(
125
153
  executionPayload: ExecutionPayload,
126
- from: AztecAddress,
154
+ from: AztecAddress | NoFrom,
127
155
  feeOptions: FeeOptions,
128
156
  ): Promise<TxExecutionRequest> {
129
157
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
130
- const executionOptions: DefaultAccountEntrypointOptions = {
131
- txNonce: Fr.random(),
132
- cancellable: this.cancellableTransactions,
133
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
134
- };
135
158
  const finalExecutionPayload = feeExecutionPayload
136
159
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
137
160
  : executionPayload;
138
- const fromAccount = await this.getAccountFromAddress(from);
139
161
  const chainInfo = await this.getChainInfo();
140
- return fromAccount.createTxExecutionRequest(
141
- finalExecutionPayload,
142
- feeOptions.gasSettings,
143
- chainInfo,
144
- executionOptions,
145
- );
162
+
163
+ if (from === NO_FROM) {
164
+ const entrypoint = new DefaultEntrypoint();
165
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
166
+ } else {
167
+ const fromAccount = await this.getAccountFromAddress(from);
168
+ const executionOptions: DefaultAccountEntrypointOptions = {
169
+ txNonce: Fr.random(),
170
+ cancellable: this.cancellableTransactions,
171
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
172
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
173
+ };
174
+ return fromAccount.createTxExecutionRequest(
175
+ finalExecutionPayload,
176
+ feeOptions.gasSettings,
177
+ chainInfo,
178
+ executionOptions,
179
+ );
180
+ }
146
181
  }
147
182
 
148
183
  public async createAuthWit(
@@ -191,31 +226,39 @@ export abstract class BaseWallet implements Wallet {
191
226
 
192
227
  /**
193
228
  * 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
229
+ * @param config - Fee completion config.
198
230
  */
199
- protected async completeFeeOptions(
200
- from: AztecAddress,
201
- feePayer?: AztecAddress,
202
- gasSettings?: Partial<FieldsOf<GasSettings>>,
203
- ): Promise<FeeOptions> {
231
+ protected async completeFeeOptions(config: CompleteFeeOptionsConfig): Promise<FeeOptions> {
232
+ const { from, feePayer, gasSettings, forEstimation } = config;
204
233
  const maxFeesPerGas =
205
234
  gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
206
235
  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;
236
+ // If from is an address, we need to determine the appropriate fee payment method options for the
237
+ // account contract entrypoint to use
238
+ if (from !== NO_FROM) {
239
+ if (!feePayer) {
240
+ // The transaction does not include a fee payment method, so we set the flag
241
+ // for the account to use its fee juice balance
242
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
243
+ } else {
244
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
245
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
246
+ accountFeePaymentMethodOptions = from.equals(feePayer)
247
+ ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
248
+ : AccountFeePaymentMethodOptions.EXTERNAL;
249
+ }
217
250
  }
218
- const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
251
+ const gasSettingsOverrides = {
252
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
253
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
254
+ maxFeesPerGas,
255
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty(),
256
+ };
257
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
258
+ // When sending for real, use protocol max limits that the network will actually accept.
259
+ const fullGasSettings = forEstimation
260
+ ? GasSettings.forEstimation(gasSettingsOverrides)
261
+ : GasSettings.fallback(gasSettingsOverrides);
219
262
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
220
263
  return {
221
264
  gasSettings: fullGasSettings,
@@ -224,37 +267,6 @@ export abstract class BaseWallet implements Wallet {
224
267
  };
225
268
  }
226
269
 
227
- /**
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
234
- */
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
- };
256
- }
257
-
258
270
  registerSender(address: AztecAddress, _alias: string = ''): Promise<AztecAddress> {
259
271
  return this.pxe.registerSender(address);
260
272
  }
@@ -300,22 +312,36 @@ export abstract class BaseWallet implements Wallet {
300
312
  /**
301
313
  * Simulates calls through the standard PXE path (account entrypoint).
302
314
  * @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.
315
+ * @param opts - Simulation options.
308
316
  */
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 });
317
+ protected async simulateViaEntrypoint(executionPayload: ExecutionPayload, opts: SimulateViaEntrypointOptions) {
318
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(
319
+ executionPayload,
320
+ opts.from,
321
+ opts.feeOptions,
322
+ );
323
+ const result = await this.pxe.simulateTx(txRequest, {
324
+ simulatePublic: true,
325
+ skipTxValidation: opts.skipTxValidation,
326
+ skipFeeEnforcement: opts.skipFeeEnforcement,
327
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
328
+ });
329
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
330
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
331
+ }
332
+
333
+ /**
334
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
335
+ * calls, N+1 = app).
336
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
337
+ * @param feeOptions - Fee options containing the wallet fee payment method.
338
+ */
339
+ protected async computeAppCallOffset(from: AztecAddress | NoFrom, feeOptions: FeeOptions): Promise<number> {
340
+ if (from === NO_FROM) {
341
+ return 0;
342
+ }
343
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
344
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
319
345
  }
320
346
 
321
347
  /**
@@ -326,10 +352,16 @@ export abstract class BaseWallet implements Wallet {
326
352
  * @param opts - Simulation options (from address, fee settings, etc.).
327
353
  * @returns The merged simulation result.
328
354
  */
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);
355
+ async simulateTx(
356
+ executionPayload: ExecutionPayload,
357
+ opts: SimulateOptions,
358
+ ): Promise<TxSimulationResultWithAppOffset> {
359
+ const feeOptions = await this.completeFeeOptions({
360
+ from: opts.from,
361
+ feePayer: executionPayload.feePayer,
362
+ gasSettings: opts.fee?.gasSettings,
363
+ forEstimation: true,
364
+ });
333
365
  const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
334
366
  const remainingPayload = { ...executionPayload, calls: remainingCalls };
335
367
 
@@ -343,12 +375,13 @@ export abstract class BaseWallet implements Wallet {
343
375
  blockHeader = (await this.aztecNode.getBlockHeader())!;
344
376
  }
345
377
 
378
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
346
379
  const [optimizedResults, normalResult] = await Promise.all([
347
380
  optimizableCalls.length > 0
348
381
  ? simulateViaNode(
349
382
  this.aztecNode,
350
383
  optimizableCalls,
351
- opts.from,
384
+ simulationOrigin,
352
385
  chainInfo,
353
386
  feeOptions.gasSettings,
354
387
  blockHeader,
@@ -357,14 +390,13 @@ export abstract class BaseWallet implements Wallet {
357
390
  )
358
391
  : Promise.resolve([]),
359
392
  remainingCalls.length > 0
360
- ? this.simulateViaEntrypoint(
361
- remainingPayload,
362
- opts.from,
393
+ ? this.simulateViaEntrypoint(remainingPayload, {
394
+ from: opts.from,
363
395
  feeOptions,
364
- this.scopesFrom(opts.from, opts.additionalScopes),
365
- opts.skipTxValidation,
366
- opts.skipFeeEnforcement ?? true,
367
- )
396
+ additionalScopes: opts.additionalScopes,
397
+ skipTxValidation: opts.skipTxValidation,
398
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
399
+ })
368
400
  : Promise.resolve(null),
369
401
  ]);
370
402
 
@@ -372,7 +404,11 @@ export abstract class BaseWallet implements Wallet {
372
404
  }
373
405
 
374
406
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
375
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
407
+ const feeOptions = await this.completeFeeOptions({
408
+ from: opts.from,
409
+ feePayer: executionPayload.feePayer,
410
+ gasSettings: opts.fee?.gasSettings,
411
+ });
376
412
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
377
413
  return this.pxe.profileTx(txRequest, {
378
414
  profileMode: opts.profileMode,
@@ -385,10 +421,17 @@ export abstract class BaseWallet implements Wallet {
385
421
  executionPayload: ExecutionPayload,
386
422
  opts: SendOptions<W>,
387
423
  ): Promise<SendReturn<W>> {
388
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
424
+ const feeOptions = await this.completeFeeOptions({
425
+ from: opts.from,
426
+ feePayer: executionPayload.feePayer,
427
+ gasSettings: opts.fee?.gasSettings,
428
+ });
389
429
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
390
430
  const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
391
- const offchainOutput = extractOffchainOutput(provenTx.getOffchainEffects());
431
+ const offchainOutput = extractOffchainOutput(
432
+ provenTx.getOffchainEffects(),
433
+ provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
434
+ );
392
435
  const tx = await provenTx.toTx();
393
436
  const txHash = tx.getTxHash();
394
437
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -445,7 +488,7 @@ export abstract class BaseWallet implements Wallet {
445
488
  }
446
489
 
447
490
  executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
448
- return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: [opts.scope] });
491
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: opts.scopes });
449
492
  }
450
493
 
451
494
  async getPrivateEvents<T>(
@@ -468,17 +511,39 @@ export abstract class BaseWallet implements Wallet {
468
511
  return decodedEvents;
469
512
  }
470
513
 
514
+ /**
515
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
516
+ * @param address - The contract address to query.
517
+ */
471
518
  async getContractMetadata(address: AztecAddress) {
472
519
  const instance = await this.pxe.getContractInstance(address);
473
- const initNullifier = await siloNullifier(address, address.toField());
474
- const publiclyRegisteredContract = await this.aztecNode.getContract(address);
475
- const initNullifierMembershipWitness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
520
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
521
+
522
+ let initializationStatus: ContractInitializationStatus;
523
+ if (instance) {
524
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
525
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
526
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
527
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
528
+ initializationStatus = witness
529
+ ? ContractInitializationStatus.INITIALIZED
530
+ : ContractInitializationStatus.UNINITIALIZED;
531
+ } else {
532
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
533
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
534
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
535
+ // uninitialized.
536
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
537
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
538
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
539
+ }
540
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
476
541
  const isContractUpdated =
477
542
  publiclyRegisteredContract &&
478
543
  !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
479
544
  return {
480
545
  instance: instance ?? undefined,
481
- isContractInitialized: !!initNullifierMembershipWitness,
546
+ initializationStatus,
482
547
  isContractPublished: !!publiclyRegisteredContract,
483
548
  isContractUpdated: !!isContractUpdated,
484
549
  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
+ }
@@ -6,7 +6,7 @@ import { schemaHasMethod } from '@aztec/foundation/schemas';
6
6
  import type { FunctionsOf } from '@aztec/foundation/types';
7
7
 
8
8
  import { type EncryptedPayload, decrypt, encrypt } from '../../crypto.js';
9
- import { type WalletMessage, WalletMessageType, type WalletResponse } from '../../types.js';
9
+ import { type DisconnectCallback, type WalletMessage, WalletMessageType, type WalletResponse } from '../../types.js';
10
10
 
11
11
  /**
12
12
  * Internal type representing a wallet method call before encryption.
@@ -19,11 +19,6 @@ type WalletMethodCall = {
19
19
  args: unknown[];
20
20
  };
21
21
 
22
- /**
23
- * Callback type for wallet disconnect events.
24
- */
25
- export type DisconnectCallback = () => void;
26
-
27
22
  /**
28
23
  * A wallet implementation that communicates with browser extension wallets
29
24
  * using an encrypted MessageChannel.
@@ -1,4 +1,4 @@
1
- export { ExtensionWallet, type DisconnectCallback } from './extension_wallet.js';
1
+ export { ExtensionWallet } from './extension_wallet.js';
2
2
  export {
3
3
  ExtensionProvider,
4
4
  type DiscoveredWallet,