@aztec/wallets 0.0.1-commit.03b9a845c → 0.0.1-commit.04d373f

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 (32) hide show
  1. package/dest/embedded/account-contract-providers/bundle.d.ts +5 -8
  2. package/dest/embedded/account-contract-providers/bundle.d.ts.map +1 -1
  3. package/dest/embedded/account-contract-providers/bundle.js +6 -9
  4. package/dest/embedded/account-contract-providers/lazy.d.ts +5 -8
  5. package/dest/embedded/account-contract-providers/lazy.d.ts.map +1 -1
  6. package/dest/embedded/account-contract-providers/lazy.js +16 -10
  7. package/dest/embedded/account-contract-providers/types.d.ts +5 -8
  8. package/dest/embedded/account-contract-providers/types.d.ts.map +1 -1
  9. package/dest/embedded/embedded_wallet.d.ts +53 -8
  10. package/dest/embedded/embedded_wallet.d.ts.map +1 -1
  11. package/dest/embedded/embedded_wallet.js +142 -41
  12. package/dest/embedded/entrypoints/browser.d.ts +2 -2
  13. package/dest/embedded/entrypoints/browser.d.ts.map +1 -1
  14. package/dest/embedded/entrypoints/browser.js +37 -10
  15. package/dest/embedded/entrypoints/node.d.ts +2 -2
  16. package/dest/embedded/entrypoints/node.d.ts.map +1 -1
  17. package/dest/embedded/entrypoints/node.js +31 -10
  18. package/dest/embedded/store_encryption.d.ts +67 -0
  19. package/dest/embedded/store_encryption.d.ts.map +1 -0
  20. package/dest/embedded/store_encryption.js +71 -0
  21. package/dest/embedded/wallet_db.d.ts +5 -4
  22. package/dest/embedded/wallet_db.d.ts.map +1 -1
  23. package/dest/embedded/wallet_db.js +9 -9
  24. package/package.json +12 -10
  25. package/src/embedded/account-contract-providers/bundle.ts +8 -11
  26. package/src/embedded/account-contract-providers/lazy.ts +18 -12
  27. package/src/embedded/account-contract-providers/types.ts +5 -4
  28. package/src/embedded/embedded_wallet.ts +201 -43
  29. package/src/embedded/entrypoints/browser.ts +42 -20
  30. package/src/embedded/entrypoints/node.ts +41 -26
  31. package/src/embedded/store_encryption.ts +107 -0
  32. package/src/embedded/wallet_db.ts +12 -9
@@ -1,24 +1,37 @@
1
1
  import { type Account, NO_FROM } from '@aztec/aztec.js/account';
2
2
  import { CallAuthorizationRequest } from '@aztec/aztec.js/authorization';
3
- import { type InteractionWaitOptions, type SendReturn, getGasLimits } from '@aztec/aztec.js/contracts';
4
- import type { Aliased, SendOptions } from '@aztec/aztec.js/wallet';
5
- import { AccountManager } from '@aztec/aztec.js/wallet';
3
+ import { type InteractionWaitOptions, type SendReturn, type WaitOpts, getGasLimits } from '@aztec/aztec.js/contracts';
4
+ import type {
5
+ Aliased,
6
+ ExecuteUtilityOptions,
7
+ PrivateEvent,
8
+ PrivateEventFilter,
9
+ ProfileOptions,
10
+ SendOptions,
11
+ SimulateOptions,
12
+ } from '@aztec/aztec.js/wallet';
13
+ import { AccountManager, TxSimulationResultWithAppOffset } from '@aztec/aztec.js/wallet';
6
14
  import type { DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
7
15
  import { DefaultEntrypoint } from '@aztec/entrypoints/default';
8
16
  import { Fq, Fr } from '@aztec/foundation/curves/bn254';
9
17
  import type { Logger } from '@aztec/foundation/log';
18
+ import type { AztecAsyncKVStore } from '@aztec/kv-store';
10
19
  import type { PXEConfig, PXECreationOptions } from '@aztec/pxe/client/lazy';
11
20
  import type { PXE } from '@aztec/pxe/server';
21
+ import type { ContractArtifact, EventMetadataDefinition, FunctionCall } from '@aztec/stdlib/abi';
12
22
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
13
- import { getContractInstanceFromInstantiationParams } from '@aztec/stdlib/contract';
23
+ import { type ContractInstanceWithAddress, getContractClassFromArtifact } from '@aztec/stdlib/contract';
14
24
  import { GasSettings } from '@aztec/stdlib/gas';
15
25
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
16
26
  import { deriveSigningKey } from '@aztec/stdlib/keys';
17
27
  import {
28
+ type ContractOverrides,
18
29
  ExecutionPayload,
19
30
  SimulationOverrides,
20
31
  type TxExecutionRequest,
21
- type TxSimulationResult,
32
+ type TxProfileResult,
33
+ TxStatus,
34
+ type UtilityExecutionResult,
22
35
  collectOffchainEffects,
23
36
  mergeExecutionPayloads,
24
37
  } from '@aztec/stdlib/tx';
@@ -27,14 +40,49 @@ import { BaseWallet, type SimulateViaEntrypointOptions } from '@aztec/wallet-sdk
27
40
  import type { AccountContractsProvider } from './account-contract-providers/types.js';
28
41
  import { type AccountType, WalletDB } from './wallet_db.js';
29
42
 
43
+ /** Options for the PXE instance created by the EmbeddedWallet. */
44
+ export type EmbeddedWalletPXEOptions = Partial<PXEConfig> & PXECreationOptions;
45
+
46
+ /** Splits a unified EmbeddedWalletPXEOptions into PXEConfig overrides and PXECreationOptions. */
47
+ export function splitPxeOptions(pxe?: EmbeddedWalletPXEOptions): {
48
+ config: Partial<PXEConfig>;
49
+ creation: PXECreationOptions;
50
+ } {
51
+ if (!pxe) {
52
+ return { config: {}, creation: {} };
53
+ }
54
+ const { loggers, loggerActorLabel, proverOrOptions, store, simulator, hooks, preloadedContractsProvider, ...config } =
55
+ pxe;
56
+ return {
57
+ config,
58
+ creation: { loggers, loggerActorLabel, proverOrOptions, store, simulator, hooks, preloadedContractsProvider },
59
+ };
60
+ }
61
+
62
+ /** Options for the EmbeddedWallet's own DB (accounts, senders — distinct from PXE state). */
63
+ export type EmbeddedWalletDBOptions = {
64
+ /** Override the wallet DB backend. If omitted, an IndexedDB (browser) / LMDB (node) store is created. */
65
+ store?: AztecAsyncKVStore;
66
+ };
67
+
30
68
  export type EmbeddedWalletOptions = {
31
69
  /** Parent logger. Child loggers are derived via createChild() for each subsystem. */
32
70
  logger?: Logger;
33
71
  /** Use ephemeral (in-memory) stores. Data will not persist across sessions. */
34
72
  ephemeral?: boolean;
35
- /** Override PXE configuration. */
73
+ /** PXE configuration and dependency overrides (custom store, prover, simulator). */
74
+ pxe?: EmbeddedWalletPXEOptions;
75
+ /** Wallet DB dependency overrides (custom store). */
76
+ walletDb?: EmbeddedWalletDBOptions;
77
+ /**
78
+ * Override PXE configuration.
79
+ * @deprecated Use `pxe` instead.
80
+ */
36
81
  pxeConfig?: Partial<PXEConfig>;
37
- /** Advanced PXE creation options (custom store, prover, simulator). */
82
+ /**
83
+ * Advanced PXE creation options (custom store, prover, simulator).
84
+ * @deprecated Use `pxe` instead.
85
+ */
38
86
  pxeOptions?: PXECreationOptions;
39
87
  };
40
88
 
@@ -43,6 +91,10 @@ const DEFAULT_ESTIMATED_GAS_PADDING = 0.1;
43
91
  export class EmbeddedWallet extends BaseWallet {
44
92
  protected estimatedGasPadding = DEFAULT_ESTIMATED_GAS_PADDING;
45
93
 
94
+ // Stub class ids, populated on wallet startup
95
+ // to avoid redundant work per simulation
96
+ protected stubClassIds = new Map<AccountType, Fr>();
97
+
46
98
  constructor(
47
99
  pxe: PXE,
48
100
  aztecNode: AztecNode,
@@ -94,19 +146,24 @@ export class EmbeddedWallet extends BaseWallet {
94
146
  executionPayload: ExecutionPayload,
95
147
  opts: SendOptions<W>,
96
148
  ): Promise<SendReturn<W>> {
97
- const feeOptions = await this.completeFeeOptionsForEstimation(
98
- opts.from,
99
- executionPayload.feePayer,
100
- opts.fee?.gasSettings,
101
- );
149
+ // PXE has autoSync disabled by the embedded wallet entrypoints, so we sync once here to cover
150
+ // both the inner simulateTx (via simulateViaEntrypoint) and the proveTx that super.sendTx
151
+ await this.pxe.sync();
152
+ const feeOptions = await this.completeFeeOptions({
153
+ from: opts.from,
154
+ feePayer: executionPayload.feePayer,
155
+ gasSettings: opts.fee?.gasSettings,
156
+ forEstimation: true,
157
+ });
102
158
 
103
159
  // Simulate the transaction first to estimate gas and capture required
104
160
  // private authwitnesses based on offchain effects.
105
161
  const simulationResult = await this.simulateViaEntrypoint(executionPayload, {
106
162
  from: opts.from,
107
163
  feeOptions,
108
- scopes: this.scopesFrom(opts.from, opts.additionalScopes),
164
+ additionalScopes: opts.additionalScopes,
109
165
  skipTxValidation: true,
166
+ sendMessagesAs: opts.sendMessagesAs,
110
167
  });
111
168
 
112
169
  const offchainEffects = collectOffchainEffects(simulationResult.privateExecutionResult);
@@ -139,12 +196,125 @@ export class EmbeddedWallet extends BaseWallet {
139
196
  gasLimits: opts.fee?.gasSettings?.gasLimits ?? estimated.gasLimits,
140
197
  teardownGasLimits: opts.fee?.gasSettings?.teardownGasLimits ?? estimated.teardownGasLimits,
141
198
  });
199
+ const waitOpts: WaitOpts = typeof opts.wait === 'object' ? opts.wait : {};
200
+
201
+ if (!waitOpts?.waitForStatus) {
202
+ // Default to PROPOSED so the wait returns as soon as the tx lands in a proposed L2 block,
203
+ // rather than waiting until the end of the slot for the checkpoint to be published to L1.
204
+ // This is what makes MBPS (Multiple Blocks Per Slot) actually improve UX: with CHECKPOINTED
205
+ // we'd block until L1 inclusion regardless of how early in the slot the tx was sequenced.
206
+ // The tradeoff is a weaker guarantee — a proposed block only becomes canonical once it (or
207
+ // a later block in the same slot) is checkpointed, so a tx could be re-orged out if the
208
+ // proposer fails to publish to L1 (which should be rare, since they'd get slashed for it).
209
+ waitOpts!.waitForStatus = TxStatus.PROPOSED;
210
+ }
142
211
  return super.sendTx(executionPayload, {
143
212
  ...opts,
144
213
  fee: { ...opts.fee, gasSettings },
145
214
  });
146
215
  }
147
216
 
217
+ /**
218
+ * Overrides the base simulateTx to drive PXE syncing explicitly. The PXE created by the embedded
219
+ * wallet has autoSync disabled (so we can share one sync across simulate+send in sendTx); for
220
+ * standalone simulations we still need a fresh anchor block, which we provide here.
221
+ */
222
+ public override async simulateTx(
223
+ executionPayload: ExecutionPayload,
224
+ opts: SimulateOptions,
225
+ ): Promise<TxSimulationResultWithAppOffset> {
226
+ await this.pxe.sync();
227
+ return super.simulateTx(executionPayload, opts);
228
+ }
229
+
230
+ public override async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
231
+ await this.pxe.sync();
232
+ return super.profileTx(executionPayload, opts);
233
+ }
234
+
235
+ public override async executeUtility(
236
+ call: FunctionCall,
237
+ opts: ExecuteUtilityOptions,
238
+ ): Promise<UtilityExecutionResult> {
239
+ await this.pxe.sync();
240
+ return super.executeUtility(call, opts);
241
+ }
242
+
243
+ public override async getPrivateEvents<T>(
244
+ eventDef: EventMetadataDefinition,
245
+ eventFilter: PrivateEventFilter,
246
+ ): Promise<PrivateEvent<T>[]> {
247
+ await this.pxe.sync();
248
+ return super.getPrivateEvents<T>(eventDef, eventFilter);
249
+ }
250
+
251
+ public override async registerContract(
252
+ instance: ContractInstanceWithAddress,
253
+ artifact?: ContractArtifact,
254
+ secretKey?: Fr,
255
+ ): Promise<ContractInstanceWithAddress> {
256
+ // registerContract may call pxe.updateContract under the hood, which depends on a fresh anchor
257
+ // block to verify the current class id from the node.
258
+ await this.pxe.sync();
259
+ return super.registerContract(instance, artifact, secretKey);
260
+ }
261
+
262
+ /**
263
+ * Hashes and registers the stub class for every supported account type with PXE, populating
264
+ * stubClassIds. Called on wallet initialization.
265
+ */
266
+ async initStubClasses(): Promise<void> {
267
+ const schnorrArtifact = await this.accountContracts.getStubAccountContractArtifact('schnorr');
268
+ const { id: schnorrClassId } = await getContractClassFromArtifact(schnorrArtifact);
269
+ await this.pxe.registerContractClass(schnorrArtifact);
270
+
271
+ // ecdsa stubs share the same class id
272
+ const ecdsaArtifact = await this.accountContracts.getStubAccountContractArtifact('ecdsasecp256r1');
273
+ const { id: ecdsaClassId } = await getContractClassFromArtifact(ecdsaArtifact);
274
+ await this.pxe.registerContractClass(ecdsaArtifact);
275
+
276
+ this.stubClassIds.set('schnorr', schnorrClassId);
277
+ this.stubClassIds.set('ecdsasecp256k1', ecdsaClassId);
278
+ this.stubClassIds.set('ecdsasecp256r1', ecdsaClassId);
279
+ }
280
+
281
+ /**
282
+ * Builds contract overrides for all provided addresses by replacing their account contracts with stub implementations.
283
+ * Uses a type-specific stub artifact so that the stub's constructor selector matches the real account's constructor.
284
+ */
285
+ protected async buildAccountOverrides(addresses: AztecAddress[]): Promise<ContractOverrides> {
286
+ const accounts = await this.getAccounts();
287
+ const contracts: ContractOverrides = {};
288
+
289
+ const filtered = accounts.filter(acc => addresses.some(addr => addr.equals(acc.item)));
290
+
291
+ for (const account of filtered) {
292
+ const address = account.item;
293
+ const { type } = await this.walletDB.retrieveAccount(address);
294
+ const stubClassId = this.stubClassIds.get(type);
295
+ if (!stubClassId) {
296
+ throw new Error(
297
+ `Stub class for account type '${type}' was not registered at wallet init. This is a bug — initStubClasses should cover every supported AccountType.`,
298
+ );
299
+ }
300
+
301
+ const originalAccount = await this.getAccountFromAddress(address);
302
+ const completeAddress = originalAccount.getCompleteAddress();
303
+ const contractInstance = await this.pxe.getContractInstance(completeAddress.address);
304
+ if (!contractInstance) {
305
+ throw new Error(
306
+ `No contract instance found for address: ${completeAddress.address} during account override building. This is a bug!`,
307
+ );
308
+ }
309
+
310
+ contracts[address.toString()] = {
311
+ instance: { ...contractInstance, currentContractClassId: stubClassId },
312
+ };
313
+ }
314
+
315
+ return contracts;
316
+ }
317
+
148
318
  /**
149
319
  * Simulates calls via a stub account entrypoint, bypassing real account authorization.
150
320
  * This allows kernelless simulation with contract overrides, skipping expensive
@@ -153,8 +323,9 @@ export class EmbeddedWallet extends BaseWallet {
153
323
  protected override async simulateViaEntrypoint(
154
324
  executionPayload: ExecutionPayload,
155
325
  opts: SimulateViaEntrypointOptions,
156
- ): Promise<TxSimulationResult> {
157
- const { from, feeOptions, scopes, skipTxValidation, skipFeeEnforcement } = opts;
326
+ ): Promise<TxSimulationResultWithAppOffset> {
327
+ const { from, feeOptions, additionalScopes, skipTxValidation, skipFeeEnforcement, sendMessagesAs } = opts;
328
+ const scopes = this.scopesFrom(from, additionalScopes);
158
329
 
159
330
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
160
331
  const finalExecutionPayload = feeExecutionPayload
@@ -162,16 +333,18 @@ export class EmbeddedWallet extends BaseWallet {
162
333
  : executionPayload;
163
334
  const chainInfo = await this.getChainInfo();
164
335
 
165
- let overrides: SimulationOverrides | undefined;
336
+ const accountOverrides = await this.buildAccountOverrides(scopes);
337
+ const overrides = new SimulationOverrides({ contracts: accountOverrides });
338
+
166
339
  let txRequest: TxExecutionRequest;
167
340
  if (from === NO_FROM) {
168
341
  const entrypoint = new DefaultEntrypoint();
169
342
  txRequest = await entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
170
343
  } else {
171
- const { account, instance, artifact } = await this.getFakeAccountDataFor(from);
172
- overrides = {
173
- contracts: { [from.toString()]: { instance, artifact } },
174
- };
344
+ const { type } = await this.walletDB.retrieveAccount(from);
345
+ const originalAccount = await this.getAccountFromAddress(from);
346
+ const completeAddress = originalAccount.getCompleteAddress();
347
+ const account = await this.accountContracts.createStubAccount(completeAddress, type);
175
348
  const executionOptions: DefaultAccountEntrypointOptions = {
176
349
  txNonce: Fr.random(),
177
350
  cancellable: this.cancellableTransactions,
@@ -186,32 +359,16 @@ export class EmbeddedWallet extends BaseWallet {
186
359
  );
187
360
  }
188
361
 
189
- return this.pxe.simulateTx(txRequest, {
362
+ const result = await this.pxe.simulateTx(txRequest, {
190
363
  simulatePublic: true,
191
364
  skipFeeEnforcement,
192
365
  skipTxValidation,
193
366
  overrides,
194
367
  scopes,
368
+ senderForTags: this.senderForTagsFrom(from, sendMessagesAs),
195
369
  });
196
- }
197
-
198
- private async getFakeAccountDataFor(address: AztecAddress) {
199
- const originalAccount = await this.getAccountFromAddress(address);
200
- const originalAddress = originalAccount.getCompleteAddress();
201
- const contractInstance = await this.pxe.getContractInstance(originalAddress.address);
202
- if (!contractInstance) {
203
- throw new Error(`No contract instance found for address: ${originalAddress.address}`);
204
- }
205
- const stubAccount = await this.accountContracts.createStubAccount(originalAddress);
206
- const stubArtifact = await this.accountContracts.getStubAccountContractArtifact();
207
- const instance = await getContractInstanceFromInstantiationParams(stubArtifact, {
208
- salt: Fr.random(),
209
- });
210
- return {
211
- account: stubAccount,
212
- instance,
213
- artifact: stubArtifact,
214
- };
370
+ const appCallOffset = await this.computeAppCallOffset(from, feeOptions);
371
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
215
372
  }
216
373
 
217
374
  protected async createAccountInternal(
@@ -239,7 +396,7 @@ export class EmbeddedWallet extends BaseWallet {
239
396
  }
240
397
  }
241
398
 
242
- const accountManager = await AccountManager.create(this, secret, contract, salt);
399
+ const accountManager = await AccountManager.create(this, secret, contract, { salt });
243
400
 
244
401
  const instance = accountManager.getInstance();
245
402
  const existingInstance = await this.pxe.getContractInstance(instance.address);
@@ -287,7 +444,8 @@ export class EmbeddedWallet extends BaseWallet {
287
444
  this.estimatedGasPadding = value ?? DEFAULT_ESTIMATED_GAS_PADDING;
288
445
  }
289
446
 
290
- stop() {
291
- return this.pxe.stop();
447
+ async stop(): Promise<void> {
448
+ await this.pxe.stop();
449
+ await this.walletDB.close();
292
450
  }
293
451
  }
@@ -3,10 +3,12 @@ import { type Logger, createLogger } from '@aztec/foundation/log';
3
3
  import { createStore, openTmpStore } from '@aztec/kv-store/indexeddb';
4
4
  import { type PXE, type PXECreationOptions, createPXE } from '@aztec/pxe/client/lazy';
5
5
  import { type PXEConfig, getPXEConfig } from '@aztec/pxe/config';
6
+ import { getStandardAuthRegistry } from '@aztec/standard-contracts/auth-registry/lazy';
7
+ import { getStandardMultiCallEntrypoint } from '@aztec/standard-contracts/multi-call-entrypoint/lazy';
6
8
 
7
9
  import { LazyAccountContractsProvider } from '../account-contract-providers/lazy.js';
8
10
  import type { AccountContractsProvider } from '../account-contract-providers/types.js';
9
- import { EmbeddedWallet, type EmbeddedWalletOptions } from '../embedded_wallet.js';
11
+ import { EmbeddedWallet, type EmbeddedWalletOptions, splitPxeOptions } from '../embedded_wallet.js';
10
12
  import { WalletDB } from '../wallet_db.js';
11
13
 
12
14
  export class BrowserEmbeddedWallet extends EmbeddedWallet {
@@ -26,10 +28,16 @@ export class BrowserEmbeddedWallet extends EmbeddedWallet {
26
28
  const aztecNode = typeof nodeOrUrl === 'string' ? createAztecNodeClient(nodeOrUrl) : nodeOrUrl;
27
29
  const l1Contracts = await aztecNode.getL1ContractAddresses();
28
30
 
31
+ // Support both the new unified `pxe` option and the deprecated `pxeConfig`/`pxeOptions`.
32
+ const { config: pxeConfigFromPxe, creation: pxeCreationFromPxe } = splitPxeOptions(options.pxe);
33
+ const mergedConfigOverrides = { ...options.pxeConfig, ...pxeConfigFromPxe };
34
+ const mergedCreationOverrides: PXECreationOptions = { ...options.pxeOptions, ...pxeCreationFromPxe };
35
+
29
36
  const pxeConfig: PXEConfig = Object.assign(getPXEConfig(), {
30
- proverEnabled: options.pxeConfig?.proverEnabled ?? false,
37
+ proverEnabled: mergedConfigOverrides.proverEnabled ?? false,
31
38
  dataDirectory: `pxe_data_${l1Contracts.rollupAddress}`,
32
- ...options.pxeConfig,
39
+ autoSync: false,
40
+ ...mergedConfigOverrides,
33
41
  });
34
42
 
35
43
  if (options.ephemeral) {
@@ -37,36 +45,50 @@ export class BrowserEmbeddedWallet extends EmbeddedWallet {
37
45
  }
38
46
 
39
47
  const pxeOptions: PXECreationOptions = {
40
- ...options.pxeOptions,
48
+ ...mergedCreationOverrides,
49
+ preloadedContractsProvider: mergedCreationOverrides.preloadedContractsProvider ?? {
50
+ getPreloadedContracts: async () => [await getStandardMultiCallEntrypoint(), await getStandardAuthRegistry()],
51
+ },
41
52
  loggers: {
42
53
  store: rootLogger.createChild('pxe:data'),
43
54
  pxe: rootLogger.createChild('pxe:service'),
44
55
  prover: rootLogger.createChild('pxe:prover'),
45
- ...options.pxeOptions?.loggers,
56
+ ...mergedCreationOverrides.loggers,
46
57
  },
47
58
  };
48
59
 
49
60
  const pxe = await createPXE(aztecNode, pxeConfig, pxeOptions);
50
61
 
51
- const walletDBStore = options.ephemeral
52
- ? await openTmpStore(true)
53
- : await createStore(
54
- 'wallet_data',
55
- {
56
- dataDirectory: `wallet_data_${l1Contracts.rollupAddress}`,
57
- dataStoreMapSizeKb: pxeConfig.dataStoreMapSizeKb,
58
- l1Contracts,
59
- },
60
- 1,
61
- rootLogger.createChild('wallet:data'),
62
- );
63
- const walletDB = WalletDB.init(walletDBStore, rootLogger.createChild('wallet:db').info);
62
+ const walletDBStore =
63
+ options.walletDb?.store ??
64
+ (options.ephemeral
65
+ ? await openTmpStore(true)
66
+ : await createStore(
67
+ 'wallet_data',
68
+ {
69
+ dataDirectory: `wallet_data_${l1Contracts.rollupAddress}`,
70
+ dataStoreMapSizeKb: pxeConfig.dataStoreMapSizeKb,
71
+ rollupAddress: l1Contracts.rollupAddress,
72
+ },
73
+ 1,
74
+ rootLogger.createChild('wallet:data'),
75
+ ));
76
+ const walletDB = new WalletDB(walletDBStore, rootLogger.createChild('wallet:db').info);
64
77
 
65
- return new this(pxe, aztecNode, walletDB, new LazyAccountContractsProvider(), rootLogger) as T;
78
+ const wallet = new this(pxe, aztecNode, walletDB, new LazyAccountContractsProvider(), rootLogger) as T;
79
+ await wallet.initStubClasses();
80
+ return wallet;
66
81
  }
67
82
  }
68
83
 
69
84
  export { BrowserEmbeddedWallet as EmbeddedWallet };
70
- export type { EmbeddedWalletOptions } from '../embedded_wallet.js';
85
+ export type { EmbeddedWalletOptions, EmbeddedWalletPXEOptions } from '../embedded_wallet.js';
71
86
  export { WalletDB } from '../wallet_db.js';
72
87
  export type { AccountType } from '../wallet_db.js';
88
+
89
+ // At-rest encryption helpers are intentionally NOT re-exported here. They live
90
+ // on the `@aztec/wallets/embedded/store-encryption` sub-path so consumers
91
+ // (and bundlers) of this entrypoint don't transitively pull in
92
+ // `@aztec/kv-store/sqlite-opfs` and its `new Worker(new URL('./worker.js'))`
93
+ // chain into `@aztec/sqlite3mc-wasm`. Apps that don't use encryption-at-rest
94
+ // (e.g. the playground) should never see sqlite-opfs in their bundle.
@@ -3,11 +3,13 @@ import { type Logger, createLogger } from '@aztec/foundation/log';
3
3
  import { createStore, openTmpStore } from '@aztec/kv-store/lmdb-v2';
4
4
  import { type PXEConfig, getPXEConfig } from '@aztec/pxe/config';
5
5
  import { type PXE, type PXECreationOptions, createPXE } from '@aztec/pxe/server';
6
+ import { getStandardAuthRegistry } from '@aztec/standard-contracts/auth-registry';
7
+ import { getStandardMultiCallEntrypoint } from '@aztec/standard-contracts/multi-call-entrypoint';
6
8
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
7
9
 
8
10
  import { BundleAccountContractsProvider } from '../account-contract-providers/bundle.js';
9
11
  import type { AccountContractsProvider } from '../account-contract-providers/types.js';
10
- import { EmbeddedWallet, type EmbeddedWalletOptions } from '../embedded_wallet.js';
12
+ import { EmbeddedWallet, type EmbeddedWalletOptions, splitPxeOptions } from '../embedded_wallet.js';
11
13
  import { WalletDB } from '../wallet_db.js';
12
14
 
13
15
  export class NodeEmbeddedWallet extends EmbeddedWallet {
@@ -27,10 +29,16 @@ export class NodeEmbeddedWallet extends EmbeddedWallet {
27
29
  const aztecNode = typeof nodeOrUrl === 'string' ? createAztecNodeClient(nodeOrUrl) : nodeOrUrl;
28
30
  const l1Contracts = await aztecNode.getL1ContractAddresses();
29
31
 
32
+ // Support both the new unified `pxe` option and the deprecated `pxeConfig`/`pxeOptions`.
33
+ const { config: pxeConfigFromPxe, creation: pxeCreationFromPxe } = splitPxeOptions(options.pxe);
34
+ const mergedConfigOverrides = { ...options.pxeConfig, ...pxeConfigFromPxe };
35
+ const mergedCreationOverrides: PXECreationOptions = { ...options.pxeOptions, ...pxeCreationFromPxe };
36
+
30
37
  const pxeConfig: PXEConfig = Object.assign(getPXEConfig(), {
31
- proverEnabled: options.pxeConfig?.proverEnabled ?? false,
38
+ proverEnabled: mergedConfigOverrides.proverEnabled ?? false,
32
39
  dataDirectory: `pxe_data_${l1Contracts.rollupAddress}`,
33
- ...options.pxeConfig,
40
+ autoSync: false,
41
+ ...mergedConfigOverrides,
34
42
  });
35
43
 
36
44
  if (options.ephemeral) {
@@ -38,42 +46,49 @@ export class NodeEmbeddedWallet extends EmbeddedWallet {
38
46
  }
39
47
 
40
48
  const pxeOptions: PXECreationOptions = {
41
- ...options.pxeOptions,
49
+ ...mergedCreationOverrides,
50
+ preloadedContractsProvider: mergedCreationOverrides.preloadedContractsProvider ?? {
51
+ getPreloadedContracts: async () => [await getStandardMultiCallEntrypoint(), await getStandardAuthRegistry()],
52
+ },
42
53
  loggers: {
43
54
  store: rootLogger.createChild('pxe:data'),
44
55
  pxe: rootLogger.createChild('pxe:service'),
45
56
  prover: rootLogger.createChild('pxe:prover'),
46
- ...options.pxeOptions?.loggers,
57
+ ...mergedCreationOverrides.loggers,
47
58
  },
48
59
  };
49
60
 
50
61
  const pxe = await createPXE(aztecNode, pxeConfig, pxeOptions);
51
62
 
52
- const walletDBStore = options.ephemeral
53
- ? await openTmpStore(
54
- `wallet_data_${l1Contracts.rollupAddress}`,
55
- true,
56
- undefined,
57
- undefined,
58
- rootLogger.createChild('wallet:data').getBindings(),
59
- )
60
- : await createStore(
61
- 'wallet_data',
62
- 1,
63
- {
64
- dataDirectory: `wallet_data_${l1Contracts.rollupAddress}`,
65
- dataStoreMapSizeKb: pxeConfig.dataStoreMapSizeKb,
66
- l1Contracts,
67
- },
68
- rootLogger.createChild('wallet:data').getBindings(),
69
- );
70
- const walletDB = WalletDB.init(walletDBStore, rootLogger.createChild('wallet:db').info);
63
+ const walletDBStore =
64
+ options.walletDb?.store ??
65
+ (options.ephemeral
66
+ ? await openTmpStore(
67
+ `wallet_data_${l1Contracts.rollupAddress}`,
68
+ true,
69
+ undefined,
70
+ undefined,
71
+ rootLogger.createChild('wallet:data').getBindings(),
72
+ )
73
+ : await createStore(
74
+ 'wallet_data',
75
+ 1,
76
+ {
77
+ dataDirectory: `wallet_data_${l1Contracts.rollupAddress}`,
78
+ dataStoreMapSizeKb: pxeConfig.dataStoreMapSizeKb,
79
+ rollupAddress: l1Contracts.rollupAddress,
80
+ },
81
+ rootLogger.createChild('wallet:data').getBindings(),
82
+ ));
83
+ const walletDB = new WalletDB(walletDBStore, rootLogger.createChild('wallet:db').info);
71
84
 
72
- return new this(pxe, aztecNode, walletDB, new BundleAccountContractsProvider(), rootLogger) as T;
85
+ const wallet = new this(pxe, aztecNode, walletDB, new BundleAccountContractsProvider(), rootLogger) as T;
86
+ await wallet.initStubClasses();
87
+ return wallet;
73
88
  }
74
89
  }
75
90
 
76
91
  export { NodeEmbeddedWallet as EmbeddedWallet };
77
- export type { EmbeddedWalletOptions } from '../embedded_wallet.js';
92
+ export type { EmbeddedWalletOptions, EmbeddedWalletPXEOptions } from '../embedded_wallet.js';
78
93
  export { WalletDB } from '../wallet_db.js';
79
94
  export type { AccountType } from '../wallet_db.js';
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Wallet-layer helpers for opening the embedded wallet's two encrypted stores (PXE + walletDB) as a cohesive unit.
3
+ *
4
+ * Sits on top of `@aztec/kv-store/sqlite-opfs`'s typed `SqliteEncryptionError` and adds:
5
+ *
6
+ * - `storeName: 'pxe' | 'wallet'`, telling callers WHICH store failed.
7
+ * - Cleanup: when the wallet store fails to open, ensures the already-opened PXE store is closed before the error
8
+ * surfaces, so callers don't leak the SAH Pool's OPFS lock.
9
+ */
10
+ import type { Logger } from '@aztec/foundation/log';
11
+ import { AztecSQLiteOPFSStore, SqliteEncryptionError } from '@aztec/kv-store/sqlite-opfs';
12
+
13
+ /** Which of the embedded wallet's two stores failed to open. */
14
+ export type EmbeddedStoreName = 'pxe' | 'wallet';
15
+
16
+ /**
17
+ * Thrown by {@link openEncryptedEmbeddedStores} when one of the two stores cannot be decrypted with the supplied
18
+ * key. The original {@link SqliteEncryptionError} is preserved as `cause`.
19
+ */
20
+ export class EmbeddedWalletEncryptionError extends Error {
21
+ readonly storeName: EmbeddedStoreName;
22
+
23
+ constructor(storeName: EmbeddedStoreName, opts: { cause: SqliteEncryptionError }) {
24
+ super(`Embedded wallet '${storeName}' store could not be decrypted with the provided key`, { cause: opts.cause });
25
+ this.name = 'EmbeddedWalletEncryptionError';
26
+ this.storeName = storeName;
27
+ }
28
+ }
29
+
30
+ /** Configuration for {@link openEncryptedEmbeddedStores}. */
31
+ export interface OpenEncryptedEmbeddedStoresOptions {
32
+ pxe: { name: string; poolDirectory?: string };
33
+ wallet: { name: string; poolDirectory?: string };
34
+ }
35
+
36
+ /**
37
+ * Internal seam for tests to inject a fake store opener. Defaults to `AztecSQLiteOPFSStore.open`. Not part of the
38
+ * public API.
39
+ *
40
+ * @internal
41
+ */
42
+ export type OpenSqliteEncryptedStoreFn = (
43
+ log: Logger,
44
+ name: string,
45
+ poolDirectory: string | undefined,
46
+ encryptionKey: Uint8Array,
47
+ ) => Promise<AztecSQLiteOPFSStore>;
48
+
49
+ const defaultOpenStore: OpenSqliteEncryptedStoreFn = (log, name, poolDirectory, encryptionKey) =>
50
+ AztecSQLiteOPFSStore.open(log, name, false, poolDirectory, encryptionKey);
51
+
52
+ /**
53
+ * Opens the PXE and wallet stores in sequence, both encrypted with keys obtained from `getEncryptionKey`.
54
+ *
55
+ * The callback is invoked once per store (twice total per call) because `AztecSQLiteOPFSStore.open` *transfers*
56
+ * the key buffer to its worker. A single buffer would detach between the two opens.
57
+ *
58
+ * Failure modes:
59
+ *
60
+ * - PXE store fails to decrypt → throws `EmbeddedWalletEncryptionError({ storeName: 'pxe', cause })`. No cleanup
61
+ * needed (nothing was opened).
62
+ * - Wallet store fails to decrypt → closes the already-opened PXE store then throws
63
+ * `EmbeddedWalletEncryptionError({ storeName: 'wallet', cause })`.
64
+ * - Any non-decrypt error during the wallet open → still closes PXE, then re-throws the original error unwrapped
65
+ * (preserves callers' existing untyped error handling for non-encryption faults).
66
+ *
67
+ * @param config - Per-store name/poolDirectory.
68
+ * @param getEncryptionKey - Returns a fresh 32-byte key per call (the buffer
69
+ * detaches on transfer, so each call must allocate).
70
+ * @param log - Logger for both stores.
71
+ * @param openStore - Internal test seam. Do not pass in production code.
72
+ */
73
+ export async function openEncryptedEmbeddedStores(
74
+ config: OpenEncryptedEmbeddedStoresOptions,
75
+ getEncryptionKey: () => Promise<Uint8Array>,
76
+ log: Logger,
77
+ openStore: OpenSqliteEncryptedStoreFn = defaultOpenStore,
78
+ ): Promise<{ pxeStore: AztecSQLiteOPFSStore; walletStore: AztecSQLiteOPFSStore }> {
79
+ const pxeStore = await openOneStore('pxe', config.pxe, getEncryptionKey, log, openStore);
80
+ try {
81
+ const walletStore = await openOneStore('wallet', config.wallet, getEncryptionKey, log, openStore);
82
+ return { pxeStore, walletStore };
83
+ } catch (err) {
84
+ // Cleanup is best-effort — if close() itself throws (e.g. worker already dead), swallow it so the original error
85
+ // surfaces unobstructed.
86
+ await pxeStore.close().catch(() => {});
87
+ throw err;
88
+ }
89
+ }
90
+
91
+ async function openOneStore(
92
+ storeName: EmbeddedStoreName,
93
+ { name, poolDirectory }: { name: string; poolDirectory?: string },
94
+ getEncryptionKey: () => Promise<Uint8Array>,
95
+ log: Logger,
96
+ openStore: OpenSqliteEncryptedStoreFn,
97
+ ): Promise<AztecSQLiteOPFSStore> {
98
+ const key = await getEncryptionKey();
99
+ try {
100
+ return await openStore(log, name, poolDirectory, key);
101
+ } catch (err) {
102
+ if (err instanceof SqliteEncryptionError && err.code === 'decrypt_failed') {
103
+ throw new EmbeddedWalletEncryptionError(storeName, { cause: err });
104
+ }
105
+ throw err;
106
+ }
107
+ }