@aztec/wallets 0.0.1-commit.2448fdb → 0.0.1-commit.2606882

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 +2 -6
  2. package/dest/embedded/account-contract-providers/bundle.d.ts.map +1 -1
  3. package/dest/embedded/account-contract-providers/bundle.js +0 -4
  4. package/dest/embedded/account-contract-providers/lazy.d.ts +2 -6
  5. package/dest/embedded/account-contract-providers/lazy.d.ts.map +1 -1
  6. package/dest/embedded/account-contract-providers/lazy.js +0 -4
  7. package/dest/embedded/account-contract-providers/types.d.ts +2 -6
  8. package/dest/embedded/account-contract-providers/types.d.ts.map +1 -1
  9. package/dest/embedded/embedded_wallet.d.ts +29 -3
  10. package/dest/embedded/embedded_wallet.d.ts.map +1 -1
  11. package/dest/embedded/embedded_wallet.js +91 -36
  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 +17 -15
  25. package/src/embedded/account-contract-providers/bundle.ts +1 -6
  26. package/src/embedded/account-contract-providers/lazy.ts +1 -6
  27. package/src/embedded/account-contract-providers/types.ts +1 -2
  28. package/src/embedded/embedded_wallet.ts +136 -30
  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';
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';
5
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,7 +35,9 @@ import {
19
35
  ExecutionPayload,
20
36
  SimulationOverrides,
21
37
  type TxExecutionRequest,
38
+ type TxProfileResult,
22
39
  TxStatus,
40
+ type UtilityExecutionResult,
23
41
  collectOffchainEffects,
24
42
  mergeExecutionPayloads,
25
43
  } from '@aztec/stdlib/tx';
@@ -39,10 +57,20 @@ export function splitPxeOptions(pxe?: EmbeddedWalletPXEOptions): {
39
57
  if (!pxe) {
40
58
  return { config: {}, creation: {} };
41
59
  }
42
- const { loggers, loggerActorLabel, proverOrOptions, store, simulator, ...config } = pxe;
43
- 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
+ };
44
66
  }
45
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
+
46
74
  export type EmbeddedWalletOptions = {
47
75
  /** Parent logger. Child loggers are derived via createChild() for each subsystem. */
48
76
  logger?: Logger;
@@ -50,6 +78,8 @@ export type EmbeddedWalletOptions = {
50
78
  ephemeral?: boolean;
51
79
  /** PXE configuration and dependency overrides (custom store, prover, simulator). */
52
80
  pxe?: EmbeddedWalletPXEOptions;
81
+ /** Wallet DB dependency overrides (custom store). */
82
+ walletDb?: EmbeddedWalletDBOptions;
53
83
  /**
54
84
  * Override PXE configuration.
55
85
  * @deprecated Use `pxe` instead.
@@ -67,6 +97,10 @@ const DEFAULT_ESTIMATED_GAS_PADDING = 0.1;
67
97
  export class EmbeddedWallet extends BaseWallet {
68
98
  protected estimatedGasPadding = DEFAULT_ESTIMATED_GAS_PADDING;
69
99
 
100
+ // Stub class ids, populated on wallet startup
101
+ // to avoid redundant work per simulation
102
+ protected stubClassIds = new Map<AccountType, Fr>();
103
+
70
104
  constructor(
71
105
  pxe: PXE,
72
106
  aztecNode: AztecNode,
@@ -118,6 +152,9 @@ export class EmbeddedWallet extends BaseWallet {
118
152
  executionPayload: ExecutionPayload,
119
153
  opts: SendOptions<W>,
120
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();
121
158
  const feeOptions = await this.completeFeeOptions({
122
159
  from: opts.from,
123
160
  feePayer: executionPayload.feePayer,
@@ -132,6 +169,7 @@ export class EmbeddedWallet extends BaseWallet {
132
169
  feeOptions,
133
170
  additionalScopes: opts.additionalScopes,
134
171
  skipTxValidation: true,
172
+ sendMessagesAs: opts.sendMessagesAs,
135
173
  });
136
174
 
137
175
  const offchainEffects = collectOffchainEffects(simulationResult.privateExecutionResult);
@@ -164,24 +202,92 @@ export class EmbeddedWallet extends BaseWallet {
164
202
  gasLimits: opts.fee?.gasSettings?.gasLimits ?? estimated.gasLimits,
165
203
  teardownGasLimits: opts.fee?.gasSettings?.teardownGasLimits ?? estimated.teardownGasLimits,
166
204
  });
167
- const waitOpts: WaitOpts = typeof opts.wait === 'object' ? opts.wait : {};
168
-
169
- if (!waitOpts?.waitForStatus) {
170
- // Default to PROPOSED so the wait returns as soon as the tx lands in a proposed L2 block,
171
- // rather than waiting until the end of the slot for the checkpoint to be published to L1.
172
- // This is what makes MBPS (Multiple Blocks Per Slot) actually improve UX: with CHECKPOINTED
173
- // we'd block until L1 inclusion regardless of how early in the slot the tx was sequenced.
174
- // The tradeoff is a weaker guarantee a proposed block only becomes canonical once it (or
175
- // a later block in the same slot) is checkpointed, so a tx could be re-orged out if the
176
- // proposer fails to publish to L1 (which should be rare, since they'd get slashed for it).
177
- 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
+ };
178
219
  }
179
220
  return super.sendTx(executionPayload, {
180
221
  ...opts,
222
+ wait: wait as W,
181
223
  fee: { ...opts.fee, gasSettings },
182
224
  });
183
225
  }
184
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
+
185
291
  /**
186
292
  * Builds contract overrides for all provided addresses by replacing their account contracts with stub implementations.
187
293
  * Uses a type-specific stub artifact so that the stub's constructor selector matches the real account's constructor.
@@ -195,7 +301,12 @@ export class EmbeddedWallet extends BaseWallet {
195
301
  for (const account of filtered) {
196
302
  const address = account.item;
197
303
  const { type } = await this.walletDB.retrieveAccount(address);
198
- const stubArtifact = await this.accountContracts.getStubAccountContractArtifact(type);
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
+ }
199
310
 
200
311
  const originalAccount = await this.getAccountFromAddress(address);
201
312
  const completeAddress = originalAccount.getCompleteAddress();
@@ -206,15 +317,8 @@ export class EmbeddedWallet extends BaseWallet {
206
317
  );
207
318
  }
208
319
 
209
- const stubConstructorArgs = type === 'schnorr' ? [Fr.ZERO, Fr.ZERO] : [Buffer.alloc(32), Buffer.alloc(32)];
210
- const stubInstance = await getContractInstanceFromInstantiationParams(stubArtifact, {
211
- salt: Fr.random(),
212
- constructorArgs: stubConstructorArgs,
213
- });
214
-
215
320
  contracts[address.toString()] = {
216
- instance: stubInstance,
217
- artifact: stubArtifact,
321
+ instance: { ...contractInstance, currentContractClassId: stubClassId },
218
322
  };
219
323
  }
220
324
 
@@ -230,7 +334,7 @@ export class EmbeddedWallet extends BaseWallet {
230
334
  executionPayload: ExecutionPayload,
231
335
  opts: SimulateViaEntrypointOptions,
232
336
  ): Promise<TxSimulationResultWithAppOffset> {
233
- const { from, feeOptions, additionalScopes, skipTxValidation, skipFeeEnforcement } = opts;
337
+ const { from, feeOptions, additionalScopes, skipTxValidation, skipFeeEnforcement, sendMessagesAs } = opts;
234
338
  const scopes = this.scopesFrom(from, additionalScopes);
235
339
 
236
340
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
@@ -240,7 +344,7 @@ export class EmbeddedWallet extends BaseWallet {
240
344
  const chainInfo = await this.getChainInfo();
241
345
 
242
346
  const accountOverrides = await this.buildAccountOverrides(scopes);
243
- const overrides = new SimulationOverrides(accountOverrides);
347
+ const overrides = new SimulationOverrides({ contracts: accountOverrides });
244
348
 
245
349
  let txRequest: TxExecutionRequest;
246
350
  if (from === NO_FROM) {
@@ -271,6 +375,7 @@ export class EmbeddedWallet extends BaseWallet {
271
375
  skipTxValidation,
272
376
  overrides,
273
377
  scopes,
378
+ senderForTags: this.senderForTagsFrom(from, sendMessagesAs),
274
379
  });
275
380
  const appCallOffset = await this.computeAppCallOffset(from, feeOptions);
276
381
  return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
@@ -301,7 +406,7 @@ export class EmbeddedWallet extends BaseWallet {
301
406
  }
302
407
  }
303
408
 
304
- const accountManager = await AccountManager.create(this, secret, contract, salt);
409
+ const accountManager = await AccountManager.create(this, secret, contract, { salt });
305
410
 
306
411
  const instance = accountManager.getInstance();
307
412
  const existingInstance = await this.pxe.getContractInstance(instance.address);
@@ -349,7 +454,8 @@ export class EmbeddedWallet extends BaseWallet {
349
454
  this.estimatedGasPadding = value ?? DEFAULT_ESTIMATED_GAS_PADDING;
350
455
  }
351
456
 
352
- stop() {
353
- return this.pxe.stop();
457
+ async stop(): Promise<void> {
458
+ await this.pxe.stop();
459
+ await this.walletDB.close();
354
460
  }
355
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
  }