@aztec/wallets 0.0.1-commit.e304674f1 → 0.0.1-commit.e57c76e

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 +32 -5
  10. package/dest/embedded/embedded_wallet.d.ts.map +1 -1
  11. package/dest/embedded/embedded_wallet.js +102 -33
  12. package/dest/embedded/entrypoints/browser.d.ts +1 -1
  13. package/dest/embedded/entrypoints/browser.d.ts.map +1 -1
  14. package/dest/embedded/entrypoints/browser.js +22 -5
  15. package/dest/embedded/entrypoints/node.d.ts +1 -1
  16. package/dest/embedded/entrypoints/node.d.ts.map +1 -1
  17. package/dest/embedded/entrypoints/node.js +16 -5
  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 +149 -36
  29. package/src/embedded/entrypoints/browser.ts +31 -14
  30. package/src/embedded/entrypoints/node.ts +30 -20
  31. package/src/embedded/store_encryption.ts +107 -0
  32. package/src/embedded/wallet_db.ts +12 -9
@@ -1,16 +1,32 @@
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, type WaitOpts, 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 {
4
+ type InteractionWaitOptions,
5
+ NO_WAIT,
6
+ type SendReturn,
7
+ type WaitOpts,
8
+ getGasLimits,
9
+ } from '@aztec/aztec.js/contracts';
10
+ import type {
11
+ Aliased,
12
+ ExecuteUtilityOptions,
13
+ PrivateEvent,
14
+ PrivateEventFilter,
15
+ ProfileOptions,
16
+ SendOptions,
17
+ SimulateOptions,
18
+ } from '@aztec/aztec.js/wallet';
19
+ import { AccountManager, TxSimulationResultWithAppOffset } from '@aztec/aztec.js/wallet';
6
20
  import type { DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
7
21
  import { DefaultEntrypoint } from '@aztec/entrypoints/default';
8
22
  import { Fq, Fr } from '@aztec/foundation/curves/bn254';
9
23
  import type { Logger } from '@aztec/foundation/log';
24
+ import type { AztecAsyncKVStore } from '@aztec/kv-store';
10
25
  import type { PXEConfig, PXECreationOptions } from '@aztec/pxe/client/lazy';
11
26
  import type { PXE } from '@aztec/pxe/server';
27
+ import type { ContractArtifact, EventMetadataDefinition, FunctionCall } from '@aztec/stdlib/abi';
12
28
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
13
- import { getContractInstanceFromInstantiationParams } from '@aztec/stdlib/contract';
29
+ import { type ContractInstanceWithAddress, getContractClassFromArtifact } from '@aztec/stdlib/contract';
14
30
  import { GasSettings } from '@aztec/stdlib/gas';
15
31
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
16
32
  import { deriveSigningKey } from '@aztec/stdlib/keys';
@@ -19,8 +35,9 @@ import {
19
35
  ExecutionPayload,
20
36
  SimulationOverrides,
21
37
  type TxExecutionRequest,
22
- type TxSimulationResult,
38
+ type TxProfileResult,
23
39
  TxStatus,
40
+ type UtilityExecutionResult,
24
41
  collectOffchainEffects,
25
42
  mergeExecutionPayloads,
26
43
  } from '@aztec/stdlib/tx';
@@ -40,10 +57,20 @@ export function splitPxeOptions(pxe?: EmbeddedWalletPXEOptions): {
40
57
  if (!pxe) {
41
58
  return { config: {}, creation: {} };
42
59
  }
43
- const { loggers, loggerActorLabel, proverOrOptions, store, simulator, ...config } = pxe;
44
- return { config, creation: { loggers, loggerActorLabel, proverOrOptions, store, simulator } };
60
+ const { loggers, loggerActorLabel, proverOrOptions, store, simulator, hooks, preloadedContractsProvider, ...config } =
61
+ pxe;
62
+ return {
63
+ config,
64
+ creation: { loggers, loggerActorLabel, proverOrOptions, store, simulator, hooks, preloadedContractsProvider },
65
+ };
45
66
  }
46
67
 
68
+ /** Options for the EmbeddedWallet's own DB (accounts, senders — distinct from PXE state). */
69
+ export type EmbeddedWalletDBOptions = {
70
+ /** Override the wallet DB backend. If omitted, an IndexedDB (browser) / LMDB (node) store is created. */
71
+ store?: AztecAsyncKVStore;
72
+ };
73
+
47
74
  export type EmbeddedWalletOptions = {
48
75
  /** Parent logger. Child loggers are derived via createChild() for each subsystem. */
49
76
  logger?: Logger;
@@ -51,6 +78,8 @@ export type EmbeddedWalletOptions = {
51
78
  ephemeral?: boolean;
52
79
  /** PXE configuration and dependency overrides (custom store, prover, simulator). */
53
80
  pxe?: EmbeddedWalletPXEOptions;
81
+ /** Wallet DB dependency overrides (custom store). */
82
+ walletDb?: EmbeddedWalletDBOptions;
54
83
  /**
55
84
  * Override PXE configuration.
56
85
  * @deprecated Use `pxe` instead.
@@ -68,6 +97,10 @@ const DEFAULT_ESTIMATED_GAS_PADDING = 0.1;
68
97
  export class EmbeddedWallet extends BaseWallet {
69
98
  protected estimatedGasPadding = DEFAULT_ESTIMATED_GAS_PADDING;
70
99
 
100
+ // Stub class ids, populated on wallet startup
101
+ // to avoid redundant work per simulation
102
+ protected stubClassIds = new Map<AccountType, Fr>();
103
+
71
104
  constructor(
72
105
  pxe: PXE,
73
106
  aztecNode: AztecNode,
@@ -119,6 +152,9 @@ export class EmbeddedWallet extends BaseWallet {
119
152
  executionPayload: ExecutionPayload,
120
153
  opts: SendOptions<W>,
121
154
  ): Promise<SendReturn<W>> {
155
+ // PXE has autoSync disabled by the embedded wallet entrypoints, so we sync once here to cover
156
+ // both the inner simulateTx (via simulateViaEntrypoint) and the proveTx that super.sendTx
157
+ await this.pxe.sync();
122
158
  const feeOptions = await this.completeFeeOptions({
123
159
  from: opts.from,
124
160
  feePayer: executionPayload.feePayer,
@@ -131,8 +167,9 @@ export class EmbeddedWallet extends BaseWallet {
131
167
  const simulationResult = await this.simulateViaEntrypoint(executionPayload, {
132
168
  from: opts.from,
133
169
  feeOptions,
134
- scopes: this.scopesFrom(opts.from, opts.additionalScopes),
170
+ additionalScopes: opts.additionalScopes,
135
171
  skipTxValidation: true,
172
+ sendMessagesAs: opts.sendMessagesAs,
136
173
  });
137
174
 
138
175
  const offchainEffects = collectOffchainEffects(simulationResult.privateExecutionResult);
@@ -165,37 +202,112 @@ export class EmbeddedWallet extends BaseWallet {
165
202
  gasLimits: opts.fee?.gasSettings?.gasLimits ?? estimated.gasLimits,
166
203
  teardownGasLimits: opts.fee?.gasSettings?.teardownGasLimits ?? estimated.teardownGasLimits,
167
204
  });
168
- const waitOpts: WaitOpts = typeof opts.wait === 'object' ? opts.wait : {};
169
-
170
- if (!waitOpts?.waitForStatus) {
171
- // Default to PROPOSED so the wait returns as soon as the tx lands in a proposed L2 block,
172
- // rather than waiting until the end of the slot for the checkpoint to be published to L1.
173
- // This is what makes MBPS (Multiple Blocks Per Slot) actually improve UX: with CHECKPOINTED
174
- // we'd block until L1 inclusion regardless of how early in the slot the tx was sequenced.
175
- // The tradeoff is a weaker guarantee a proposed block only becomes canonical once it (or
176
- // a later block in the same slot) is checkpointed, so a tx could be re-orged out if the
177
- // proposer fails to publish to L1 (which should be rare, since they'd get slashed for it).
178
- waitOpts!.waitForStatus = TxStatus.PROPOSED;
205
+ let wait: InteractionWaitOptions = opts.wait;
206
+ if (wait !== NO_WAIT) {
207
+ const callerWaitOpts: WaitOpts = typeof wait === 'object' ? wait : {};
208
+ wait = {
209
+ ...callerWaitOpts,
210
+ // Default to PROPOSED so the wait returns as soon as the tx lands in a proposed L2 block,
211
+ // rather than waiting until the end of the slot for the checkpoint to be published to L1.
212
+ // This is what makes MBPS (Multiple Blocks Per Slot) actually improve UX: with CHECKPOINTED
213
+ // we'd block until L1 inclusion regardless of how early in the slot the tx was sequenced.
214
+ // The tradeoff is a weaker guarantee a proposed block only becomes canonical once it (or
215
+ // a later block in the same slot) is checkpointed, so a tx could be re-orged out if the
216
+ // proposer fails to publish to L1 (which should be rare, since they'd get slashed for it).
217
+ waitForStatus: callerWaitOpts.waitForStatus ?? TxStatus.PROPOSED,
218
+ };
179
219
  }
180
220
  return super.sendTx(executionPayload, {
181
221
  ...opts,
222
+ wait: wait as W,
182
223
  fee: { ...opts.fee, gasSettings },
183
224
  });
184
225
  }
185
226
 
227
+ /**
228
+ * Overrides the base simulateTx to drive PXE syncing explicitly. The PXE created by the embedded
229
+ * wallet has autoSync disabled (so we can share one sync across simulate+send in sendTx); for
230
+ * standalone simulations we still need a fresh anchor block, which we provide here.
231
+ */
232
+ public override async simulateTx(
233
+ executionPayload: ExecutionPayload,
234
+ opts: SimulateOptions,
235
+ ): Promise<TxSimulationResultWithAppOffset> {
236
+ await this.pxe.sync();
237
+ return super.simulateTx(executionPayload, opts);
238
+ }
239
+
240
+ public override async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
241
+ await this.pxe.sync();
242
+ return super.profileTx(executionPayload, opts);
243
+ }
244
+
245
+ public override async executeUtility(
246
+ call: FunctionCall,
247
+ opts: ExecuteUtilityOptions,
248
+ ): Promise<UtilityExecutionResult> {
249
+ await this.pxe.sync();
250
+ return super.executeUtility(call, opts);
251
+ }
252
+
253
+ public override async getPrivateEvents<T>(
254
+ eventDef: EventMetadataDefinition,
255
+ eventFilter: PrivateEventFilter,
256
+ ): Promise<PrivateEvent<T>[]> {
257
+ await this.pxe.sync();
258
+ return super.getPrivateEvents<T>(eventDef, eventFilter);
259
+ }
260
+
261
+ public override async registerContract(
262
+ instance: ContractInstanceWithAddress,
263
+ artifact?: ContractArtifact,
264
+ secretKey?: Fr,
265
+ ): Promise<ContractInstanceWithAddress> {
266
+ // registerContract may call pxe.updateContract under the hood, which depends on a fresh anchor
267
+ // block to verify the current class id from the node.
268
+ await this.pxe.sync();
269
+ return super.registerContract(instance, artifact, secretKey);
270
+ }
271
+
272
+ /**
273
+ * Hashes and registers the stub class for every supported account type with PXE, populating
274
+ * stubClassIds. Called on wallet initialization.
275
+ */
276
+ async initStubClasses(): Promise<void> {
277
+ const schnorrArtifact = await this.accountContracts.getStubAccountContractArtifact('schnorr');
278
+ const { id: schnorrClassId } = await getContractClassFromArtifact(schnorrArtifact);
279
+ await this.pxe.registerContractClass(schnorrArtifact);
280
+
281
+ // ecdsa stubs share the same class id
282
+ const ecdsaArtifact = await this.accountContracts.getStubAccountContractArtifact('ecdsasecp256r1');
283
+ const { id: ecdsaClassId } = await getContractClassFromArtifact(ecdsaArtifact);
284
+ await this.pxe.registerContractClass(ecdsaArtifact);
285
+
286
+ this.stubClassIds.set('schnorr', schnorrClassId);
287
+ this.stubClassIds.set('ecdsasecp256k1', ecdsaClassId);
288
+ this.stubClassIds.set('ecdsasecp256r1', ecdsaClassId);
289
+ }
290
+
186
291
  /**
187
292
  * Builds contract overrides for all provided addresses by replacing their account contracts with stub implementations.
293
+ * Uses a type-specific stub artifact so that the stub's constructor selector matches the real account's constructor.
188
294
  */
189
295
  protected async buildAccountOverrides(addresses: AztecAddress[]): Promise<ContractOverrides> {
190
296
  const accounts = await this.getAccounts();
191
297
  const contracts: ContractOverrides = {};
192
298
 
193
- const stubArtifact = await this.accountContracts.getStubAccountContractArtifact();
194
-
195
299
  const filtered = accounts.filter(acc => addresses.some(addr => addr.equals(acc.item)));
196
300
 
197
301
  for (const account of filtered) {
198
302
  const address = account.item;
303
+ const { type } = await this.walletDB.retrieveAccount(address);
304
+ const stubClassId = this.stubClassIds.get(type);
305
+ if (!stubClassId) {
306
+ throw new Error(
307
+ `Stub class for account type '${type}' was not registered at wallet init. This is a bug — initStubClasses should cover every supported AccountType.`,
308
+ );
309
+ }
310
+
199
311
  const originalAccount = await this.getAccountFromAddress(address);
200
312
  const completeAddress = originalAccount.getCompleteAddress();
201
313
  const contractInstance = await this.pxe.getContractInstance(completeAddress.address);
@@ -205,13 +317,8 @@ export class EmbeddedWallet extends BaseWallet {
205
317
  );
206
318
  }
207
319
 
208
- const stubInstance = await getContractInstanceFromInstantiationParams(stubArtifact, {
209
- salt: Fr.random(),
210
- });
211
-
212
320
  contracts[address.toString()] = {
213
- instance: stubInstance,
214
- artifact: stubArtifact,
321
+ instance: { ...contractInstance, currentContractClassId: stubClassId },
215
322
  };
216
323
  }
217
324
 
@@ -226,8 +333,9 @@ export class EmbeddedWallet extends BaseWallet {
226
333
  protected override async simulateViaEntrypoint(
227
334
  executionPayload: ExecutionPayload,
228
335
  opts: SimulateViaEntrypointOptions,
229
- ): Promise<TxSimulationResult> {
230
- const { from, feeOptions, scopes, skipTxValidation, skipFeeEnforcement } = opts;
336
+ ): Promise<TxSimulationResultWithAppOffset> {
337
+ const { from, feeOptions, additionalScopes, skipTxValidation, skipFeeEnforcement, sendMessagesAs } = opts;
338
+ const scopes = this.scopesFrom(from, additionalScopes);
231
339
 
232
340
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
233
341
  const finalExecutionPayload = feeExecutionPayload
@@ -235,17 +343,18 @@ export class EmbeddedWallet extends BaseWallet {
235
343
  : executionPayload;
236
344
  const chainInfo = await this.getChainInfo();
237
345
 
238
- const accountOverrides = await this.buildAccountOverrides(this.scopesFrom(from, opts.additionalScopes));
239
- const overrides = new SimulationOverrides(accountOverrides);
346
+ const accountOverrides = await this.buildAccountOverrides(scopes);
347
+ const overrides = new SimulationOverrides({ contracts: accountOverrides });
240
348
 
241
349
  let txRequest: TxExecutionRequest;
242
350
  if (from === NO_FROM) {
243
351
  const entrypoint = new DefaultEntrypoint();
244
352
  txRequest = await entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
245
353
  } else {
354
+ const { type } = await this.walletDB.retrieveAccount(from);
246
355
  const originalAccount = await this.getAccountFromAddress(from);
247
356
  const completeAddress = originalAccount.getCompleteAddress();
248
- const account = await this.accountContracts.createStubAccount(completeAddress);
357
+ const account = await this.accountContracts.createStubAccount(completeAddress, type);
249
358
  const executionOptions: DefaultAccountEntrypointOptions = {
250
359
  txNonce: Fr.random(),
251
360
  cancellable: this.cancellableTransactions,
@@ -260,13 +369,16 @@ export class EmbeddedWallet extends BaseWallet {
260
369
  );
261
370
  }
262
371
 
263
- return this.pxe.simulateTx(txRequest, {
372
+ const result = await this.pxe.simulateTx(txRequest, {
264
373
  simulatePublic: true,
265
374
  skipFeeEnforcement,
266
375
  skipTxValidation,
267
376
  overrides,
268
377
  scopes,
378
+ senderForTags: this.senderForTagsFrom(from, sendMessagesAs),
269
379
  });
380
+ const appCallOffset = await this.computeAppCallOffset(from, feeOptions);
381
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
270
382
  }
271
383
 
272
384
  protected async createAccountInternal(
@@ -294,7 +406,7 @@ export class EmbeddedWallet extends BaseWallet {
294
406
  }
295
407
  }
296
408
 
297
- const accountManager = await AccountManager.create(this, secret, contract, salt);
409
+ const accountManager = await AccountManager.create(this, secret, contract, { salt });
298
410
 
299
411
  const instance = accountManager.getInstance();
300
412
  const existingInstance = await this.pxe.getContractInstance(instance.address);
@@ -342,7 +454,8 @@ export class EmbeddedWallet extends BaseWallet {
342
454
  this.estimatedGasPadding = value ?? DEFAULT_ESTIMATED_GAS_PADDING;
343
455
  }
344
456
 
345
- stop() {
346
- return this.pxe.stop();
457
+ async stop(): Promise<void> {
458
+ await this.pxe.stop();
459
+ await this.walletDB.close();
347
460
  }
348
461
  }
@@ -3,6 +3,8 @@ 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';
@@ -34,6 +36,7 @@ export class BrowserEmbeddedWallet extends EmbeddedWallet {
34
36
  const pxeConfig: PXEConfig = Object.assign(getPXEConfig(), {
35
37
  proverEnabled: mergedConfigOverrides.proverEnabled ?? false,
36
38
  dataDirectory: `pxe_data_${l1Contracts.rollupAddress}`,
39
+ autoSync: false,
37
40
  ...mergedConfigOverrides,
38
41
  });
39
42
 
@@ -43,6 +46,9 @@ export class BrowserEmbeddedWallet extends EmbeddedWallet {
43
46
 
44
47
  const pxeOptions: PXECreationOptions = {
45
48
  ...mergedCreationOverrides,
49
+ preloadedContractsProvider: mergedCreationOverrides.preloadedContractsProvider ?? {
50
+ getPreloadedContracts: async () => [await getStandardMultiCallEntrypoint(), await getStandardAuthRegistry()],
51
+ },
46
52
  loggers: {
47
53
  store: rootLogger.createChild('pxe:data'),
48
54
  pxe: rootLogger.createChild('pxe:service'),
@@ -53,21 +59,25 @@ export class BrowserEmbeddedWallet extends EmbeddedWallet {
53
59
 
54
60
  const pxe = await createPXE(aztecNode, pxeConfig, pxeOptions);
55
61
 
56
- const walletDBStore = options.ephemeral
57
- ? await openTmpStore(true)
58
- : await createStore(
59
- 'wallet_data',
60
- {
61
- dataDirectory: `wallet_data_${l1Contracts.rollupAddress}`,
62
- dataStoreMapSizeKb: pxeConfig.dataStoreMapSizeKb,
63
- l1Contracts,
64
- },
65
- 1,
66
- rootLogger.createChild('wallet:data'),
67
- );
68
- 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);
69
77
 
70
- 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;
71
81
  }
72
82
  }
73
83
 
@@ -75,3 +85,10 @@ export { BrowserEmbeddedWallet as EmbeddedWallet };
75
85
  export type { EmbeddedWalletOptions, EmbeddedWalletPXEOptions } from '../embedded_wallet.js';
76
86
  export { WalletDB } from '../wallet_db.js';
77
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,6 +3,8 @@ 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';
@@ -35,6 +37,7 @@ export class NodeEmbeddedWallet extends EmbeddedWallet {
35
37
  const pxeConfig: PXEConfig = Object.assign(getPXEConfig(), {
36
38
  proverEnabled: mergedConfigOverrides.proverEnabled ?? false,
37
39
  dataDirectory: `pxe_data_${l1Contracts.rollupAddress}`,
40
+ autoSync: false,
38
41
  ...mergedConfigOverrides,
39
42
  });
40
43
 
@@ -44,6 +47,9 @@ export class NodeEmbeddedWallet extends EmbeddedWallet {
44
47
 
45
48
  const pxeOptions: PXECreationOptions = {
46
49
  ...mergedCreationOverrides,
50
+ preloadedContractsProvider: mergedCreationOverrides.preloadedContractsProvider ?? {
51
+ getPreloadedContracts: async () => [await getStandardMultiCallEntrypoint(), await getStandardAuthRegistry()],
52
+ },
47
53
  loggers: {
48
54
  store: rootLogger.createChild('pxe:data'),
49
55
  pxe: rootLogger.createChild('pxe:service'),
@@ -54,27 +60,31 @@ export class NodeEmbeddedWallet extends EmbeddedWallet {
54
60
 
55
61
  const pxe = await createPXE(aztecNode, pxeConfig, pxeOptions);
56
62
 
57
- const walletDBStore = options.ephemeral
58
- ? await openTmpStore(
59
- `wallet_data_${l1Contracts.rollupAddress}`,
60
- true,
61
- undefined,
62
- undefined,
63
- rootLogger.createChild('wallet:data').getBindings(),
64
- )
65
- : await createStore(
66
- 'wallet_data',
67
- 1,
68
- {
69
- dataDirectory: `wallet_data_${l1Contracts.rollupAddress}`,
70
- dataStoreMapSizeKb: pxeConfig.dataStoreMapSizeKb,
71
- l1Contracts,
72
- },
73
- rootLogger.createChild('wallet:data').getBindings(),
74
- );
75
- 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);
76
84
 
77
- 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;
78
88
  }
79
89
  }
80
90
 
@@ -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
+ }
@@ -12,16 +12,15 @@ function accountKey(field: string, address: AztecAddress | string): string {
12
12
  }
13
13
 
14
14
  export class WalletDB {
15
- private constructor(
16
- private accounts: AztecAsyncMap<string, Buffer>,
17
- private aliases: AztecAsyncMap<string, Buffer>,
18
- private userLog: LogFn,
19
- ) {}
15
+ private accounts: AztecAsyncMap<string, Buffer>;
16
+ private aliases: AztecAsyncMap<string, Buffer>;
20
17
 
21
- static init(store: AztecAsyncKVStore, userLog: LogFn) {
22
- const accounts = store.openMap<string, Buffer>('accounts');
23
- const aliases = store.openMap<string, Buffer>('aliases');
24
- return new WalletDB(accounts, aliases, userLog);
18
+ constructor(
19
+ private store: AztecAsyncKVStore,
20
+ private userLog: LogFn,
21
+ ) {
22
+ this.accounts = store.openMap<string, Buffer>('accounts');
23
+ this.aliases = store.openMap<string, Buffer>('aliases');
25
24
  }
26
25
 
27
26
  async storeAccount(
@@ -131,4 +130,8 @@ export class WalletDB {
131
130
  await this.aliases.delete(`accounts:${alias}`);
132
131
  }
133
132
  }
133
+
134
+ async close() {
135
+ await this.store.close();
136
+ }
134
137
  }