@aztec/wallets 0.0.1-commit.ffe5b04ea → 0.0.1-dev

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 (36) hide show
  1. package/dest/embedded/account-contract-providers/bundle.d.ts +4 -3
  2. package/dest/embedded/account-contract-providers/bundle.d.ts.map +1 -1
  3. package/dest/embedded/account-contract-providers/bundle.js +6 -5
  4. package/dest/embedded/account-contract-providers/lazy.d.ts +4 -3
  5. package/dest/embedded/account-contract-providers/lazy.d.ts.map +1 -1
  6. package/dest/embedded/account-contract-providers/lazy.js +16 -6
  7. package/dest/embedded/account-contract-providers/types.d.ts +4 -3
  8. package/dest/embedded/account-contract-providers/types.d.ts.map +1 -1
  9. package/dest/embedded/embedded_wallet.d.ts +46 -10
  10. package/dest/embedded/embedded_wallet.d.ts.map +1 -1
  11. package/dest/embedded/embedded_wallet.js +164 -64
  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 +24 -8
  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 +18 -8
  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/dest/testing.d.ts +1 -1
  25. package/dest/testing.d.ts.map +1 -1
  26. package/dest/testing.js +2 -2
  27. package/package.json +17 -15
  28. package/src/embedded/account-contract-providers/bundle.ts +7 -5
  29. package/src/embedded/account-contract-providers/lazy.ts +17 -6
  30. package/src/embedded/account-contract-providers/types.ts +4 -2
  31. package/src/embedded/embedded_wallet.ts +212 -72
  32. package/src/embedded/entrypoints/browser.ts +33 -19
  33. package/src/embedded/entrypoints/node.ts +32 -25
  34. package/src/embedded/store_encryption.ts +107 -0
  35. package/src/embedded/wallet_db.ts +12 -9
  36. package/src/testing.ts +2 -1
@@ -1,33 +1,81 @@
1
- import { type Account, SignerlessAccount } from '@aztec/aztec.js/account';
2
- import type { Aliased } from '@aztec/aztec.js/wallet';
3
- import { AccountManager } from '@aztec/aztec.js/wallet';
1
+ import { type Account, NO_FROM } from '@aztec/aztec.js/account';
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, TxSimulationResultWithAppOffset } from '@aztec/aztec.js/wallet';
4
6
  import type { DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
7
+ import { DefaultEntrypoint } from '@aztec/entrypoints/default';
5
8
  import { Fq, Fr } from '@aztec/foundation/curves/bn254';
6
9
  import type { Logger } from '@aztec/foundation/log';
7
- import type { AccessScopes, PXEConfig, PXECreationOptions } from '@aztec/pxe/client/lazy';
10
+ import type { AztecAsyncKVStore } from '@aztec/kv-store';
11
+ import type { PXEConfig, PXECreationOptions } from '@aztec/pxe/client/lazy';
8
12
  import type { PXE } from '@aztec/pxe/server';
9
13
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
10
14
  import { getContractInstanceFromInstantiationParams } from '@aztec/stdlib/contract';
15
+ import { GasSettings } from '@aztec/stdlib/gas';
11
16
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
12
17
  import { deriveSigningKey } from '@aztec/stdlib/keys';
13
- import { ExecutionPayload, type TxSimulationResult, mergeExecutionPayloads } from '@aztec/stdlib/tx';
14
- import { BaseWallet, type FeeOptions } from '@aztec/wallet-sdk/base-wallet';
18
+ import {
19
+ type ContractOverrides,
20
+ ExecutionPayload,
21
+ SimulationOverrides,
22
+ type TxExecutionRequest,
23
+ TxStatus,
24
+ collectOffchainEffects,
25
+ mergeExecutionPayloads,
26
+ } from '@aztec/stdlib/tx';
27
+ import { BaseWallet, type SimulateViaEntrypointOptions } from '@aztec/wallet-sdk/base-wallet';
15
28
 
16
29
  import type { AccountContractsProvider } from './account-contract-providers/types.js';
17
30
  import { type AccountType, WalletDB } from './wallet_db.js';
18
31
 
32
+ /** Options for the PXE instance created by the EmbeddedWallet. */
33
+ export type EmbeddedWalletPXEOptions = Partial<PXEConfig> & PXECreationOptions;
34
+
35
+ /** Splits a unified EmbeddedWalletPXEOptions into PXEConfig overrides and PXECreationOptions. */
36
+ export function splitPxeOptions(pxe?: EmbeddedWalletPXEOptions): {
37
+ config: Partial<PXEConfig>;
38
+ creation: PXECreationOptions;
39
+ } {
40
+ if (!pxe) {
41
+ return { config: {}, creation: {} };
42
+ }
43
+ const { loggers, loggerActorLabel, proverOrOptions, store, simulator, ...config } = pxe;
44
+ return { config, creation: { loggers, loggerActorLabel, proverOrOptions, store, simulator } };
45
+ }
46
+
47
+ /** Options for the EmbeddedWallet's own DB (accounts, senders — distinct from PXE state). */
48
+ export type EmbeddedWalletDBOptions = {
49
+ /** Override the wallet DB backend. If omitted, an IndexedDB (browser) / LMDB (node) store is created. */
50
+ store?: AztecAsyncKVStore;
51
+ };
52
+
19
53
  export type EmbeddedWalletOptions = {
20
54
  /** Parent logger. Child loggers are derived via createChild() for each subsystem. */
21
55
  logger?: Logger;
22
56
  /** Use ephemeral (in-memory) stores. Data will not persist across sessions. */
23
57
  ephemeral?: boolean;
24
- /** Override PXE configuration. */
58
+ /** PXE configuration and dependency overrides (custom store, prover, simulator). */
59
+ pxe?: EmbeddedWalletPXEOptions;
60
+ /** Wallet DB dependency overrides (custom store). */
61
+ walletDb?: EmbeddedWalletDBOptions;
62
+ /**
63
+ * Override PXE configuration.
64
+ * @deprecated Use `pxe` instead.
65
+ */
25
66
  pxeConfig?: Partial<PXEConfig>;
26
- /** Advanced PXE creation options (custom store, prover, simulator). */
67
+ /**
68
+ * Advanced PXE creation options (custom store, prover, simulator).
69
+ * @deprecated Use `pxe` instead.
70
+ */
27
71
  pxeOptions?: PXECreationOptions;
28
72
  };
29
73
 
74
+ const DEFAULT_ESTIMATED_GAS_PADDING = 0.1;
75
+
30
76
  export class EmbeddedWallet extends BaseWallet {
77
+ protected estimatedGasPadding = DEFAULT_ESTIMATED_GAS_PADDING;
78
+
31
79
  constructor(
32
80
  pxe: PXE,
33
81
  aztecNode: AztecNode,
@@ -39,10 +87,6 @@ export class EmbeddedWallet extends BaseWallet {
39
87
  }
40
88
 
41
89
  protected async getAccountFromAddress(address: AztecAddress): Promise<Account> {
42
- if (address.equals(AztecAddress.ZERO)) {
43
- return new SignerlessAccount();
44
- }
45
-
46
90
  const { secretKey, salt, signingKey, type } = await this.walletDB.retrieveAccount(address);
47
91
  const accountManager = await this.createAccountInternal(type, secretKey, salt, signingKey);
48
92
  const account = await accountManager.getAccount();
@@ -75,81 +119,172 @@ export class EmbeddedWallet extends BaseWallet {
75
119
  }
76
120
 
77
121
  /**
78
- * Simulates calls via a stub account entrypoint, bypassing real account authorization.
79
- * This allows kernelless simulation with contract overrides, skipping expensive
80
- * private kernel circuit execution.
122
+ * Overrides the base sendTx to add a pre-simulation step before the actual send. The simulation
123
+ * estimates actual gas usage and captures call authorization requests to generate
124
+ * the necessary authwitnesses.
81
125
  */
82
- protected override async simulateViaEntrypoint(
126
+ public override async sendTx<W extends InteractionWaitOptions = undefined>(
83
127
  executionPayload: ExecutionPayload,
84
- from: AztecAddress,
85
- feeOptions: FeeOptions,
86
- scopes: AccessScopes,
87
- _skipTxValidation?: boolean,
88
- _skipFeeEnforcement?: boolean,
89
- ): Promise<TxSimulationResult> {
90
- const { account: fromAccount, instance, artifact } = await this.getFakeAccountDataFor(from);
128
+ opts: SendOptions<W>,
129
+ ): Promise<SendReturn<W>> {
130
+ const feeOptions = await this.completeFeeOptions({
131
+ from: opts.from,
132
+ feePayer: executionPayload.feePayer,
133
+ gasSettings: opts.fee?.gasSettings,
134
+ forEstimation: true,
135
+ });
91
136
 
92
- const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
93
- const executionOptions: DefaultAccountEntrypointOptions = {
94
- txNonce: Fr.random(),
95
- cancellable: this.cancellableTransactions,
96
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
97
- };
98
- const finalExecutionPayload = feeExecutionPayload
99
- ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
100
- : executionPayload;
101
- const chainInfo = await this.getChainInfo();
102
- const txRequest = await fromAccount.createTxExecutionRequest(
103
- finalExecutionPayload,
104
- feeOptions.gasSettings,
105
- chainInfo,
106
- executionOptions,
107
- );
108
- return this.pxe.simulateTx(txRequest, {
109
- simulatePublic: true,
110
- skipFeeEnforcement: true,
137
+ // Simulate the transaction first to estimate gas and capture required
138
+ // private authwitnesses based on offchain effects.
139
+ const simulationResult = await this.simulateViaEntrypoint(executionPayload, {
140
+ from: opts.from,
141
+ feeOptions,
142
+ additionalScopes: opts.additionalScopes,
111
143
  skipTxValidation: true,
112
- overrides: {
113
- contracts: { [from.toString()]: { instance, artifact } },
114
- },
115
- scopes,
144
+ sendMessagesAs: opts.sendMessagesAs,
145
+ });
146
+
147
+ const offchainEffects = collectOffchainEffects(simulationResult.privateExecutionResult);
148
+ const authWitnesses = await Promise.all(
149
+ offchainEffects.map(async effect => {
150
+ try {
151
+ const authRequest = await CallAuthorizationRequest.fromFields(effect.data);
152
+ return this.createAuthWit(authRequest.onBehalfOf, {
153
+ consumer: effect.contractAddress,
154
+ innerHash: authRequest.innerHash,
155
+ });
156
+ } catch {
157
+ return undefined;
158
+ }
159
+ }),
160
+ );
161
+ for (const authwit of authWitnesses) {
162
+ if (authwit) {
163
+ executionPayload.authWitnesses.push(authwit);
164
+ }
165
+ }
166
+ const estimated = getGasLimits(simulationResult, this.estimatedGasPadding);
167
+ this.log.verbose(
168
+ `Estimated gas limits for tx: DA=${estimated.gasLimits.daGas} L2=${estimated.gasLimits.l2Gas} teardownDA=${estimated.teardownGasLimits.daGas} teardownL2=${estimated.teardownGasLimits.l2Gas}`,
169
+ );
170
+ const gasSettings = GasSettings.from({
171
+ ...opts.fee?.gasSettings,
172
+ maxFeesPerGas: feeOptions.gasSettings.maxFeesPerGas,
173
+ maxPriorityFeesPerGas: feeOptions.gasSettings.maxPriorityFeesPerGas,
174
+ gasLimits: opts.fee?.gasSettings?.gasLimits ?? estimated.gasLimits,
175
+ teardownGasLimits: opts.fee?.gasSettings?.teardownGasLimits ?? estimated.teardownGasLimits,
176
+ });
177
+ const waitOpts: WaitOpts = typeof opts.wait === 'object' ? opts.wait : {};
178
+
179
+ if (!waitOpts?.waitForStatus) {
180
+ // Default to PROPOSED so the wait returns as soon as the tx lands in a proposed L2 block,
181
+ // rather than waiting until the end of the slot for the checkpoint to be published to L1.
182
+ // This is what makes MBPS (Multiple Blocks Per Slot) actually improve UX: with CHECKPOINTED
183
+ // we'd block until L1 inclusion regardless of how early in the slot the tx was sequenced.
184
+ // The tradeoff is a weaker guarantee — a proposed block only becomes canonical once it (or
185
+ // a later block in the same slot) is checkpointed, so a tx could be re-orged out if the
186
+ // proposer fails to publish to L1 (which should be rare, since they'd get slashed for it).
187
+ waitOpts!.waitForStatus = TxStatus.PROPOSED;
188
+ }
189
+ return super.sendTx(executionPayload, {
190
+ ...opts,
191
+ fee: { ...opts.fee, gasSettings },
116
192
  });
117
193
  }
118
194
 
119
- private async getFakeAccountDataFor(address: AztecAddress) {
120
- // While we have the convention of "Zero address means no auth", and also
121
- // we don't have a way to trigger kernelless simulations without overrides,
122
- // we need to explicitly handle the zero address case here by
123
- // returning the actual multicall contract instead of trying to create a stub account for it.
124
- if (!address.equals(AztecAddress.ZERO)) {
195
+ /**
196
+ * Builds contract overrides for all provided addresses by replacing their account contracts with stub implementations.
197
+ * Uses a type-specific stub artifact so that the stub's constructor selector matches the real account's constructor.
198
+ */
199
+ protected async buildAccountOverrides(addresses: AztecAddress[]): Promise<ContractOverrides> {
200
+ const accounts = await this.getAccounts();
201
+ const contracts: ContractOverrides = {};
202
+
203
+ const filtered = accounts.filter(acc => addresses.some(addr => addr.equals(acc.item)));
204
+
205
+ for (const account of filtered) {
206
+ const address = account.item;
207
+ const { type } = await this.walletDB.retrieveAccount(address);
208
+ const stubArtifact = await this.accountContracts.getStubAccountContractArtifact(type);
209
+
125
210
  const originalAccount = await this.getAccountFromAddress(address);
126
- if (originalAccount instanceof SignerlessAccount) {
127
- throw new Error(`Cannot create fake account data for SignerlessAccount at address: ${address}`);
128
- }
129
- const originalAddress = (originalAccount as Account).getCompleteAddress();
130
- const contractInstance = await this.pxe.getContractInstance(originalAddress.address);
211
+ const completeAddress = originalAccount.getCompleteAddress();
212
+ const contractInstance = await this.pxe.getContractInstance(completeAddress.address);
131
213
  if (!contractInstance) {
132
- throw new Error(`No contract instance found for address: ${originalAddress.address}`);
214
+ throw new Error(
215
+ `No contract instance found for address: ${completeAddress.address} during account override building. This is a bug!`,
216
+ );
133
217
  }
134
- const stubAccount = await this.accountContracts.createStubAccount(originalAddress);
135
- const stubArtifact = await this.accountContracts.getStubAccountContractArtifact();
136
- const instance = await getContractInstanceFromInstantiationParams(stubArtifact, {
218
+
219
+ const stubConstructorArgs = type === 'schnorr' ? [Fr.ZERO, Fr.ZERO] : [Buffer.alloc(32), Buffer.alloc(32)];
220
+ const stubInstance = await getContractInstanceFromInstantiationParams(stubArtifact, {
137
221
  salt: Fr.random(),
222
+ constructorArgs: stubConstructorArgs,
138
223
  });
139
- return {
140
- account: stubAccount,
141
- instance,
224
+
225
+ contracts[address.toString()] = {
226
+ instance: stubInstance,
142
227
  artifact: stubArtifact,
143
228
  };
229
+ }
230
+
231
+ return contracts;
232
+ }
233
+
234
+ /**
235
+ * Simulates calls via a stub account entrypoint, bypassing real account authorization.
236
+ * This allows kernelless simulation with contract overrides, skipping expensive
237
+ * private kernel circuit execution.
238
+ */
239
+ protected override async simulateViaEntrypoint(
240
+ executionPayload: ExecutionPayload,
241
+ opts: SimulateViaEntrypointOptions,
242
+ ): Promise<TxSimulationResultWithAppOffset> {
243
+ const { from, feeOptions, additionalScopes, skipTxValidation, skipFeeEnforcement, sendMessagesAs } = opts;
244
+ const scopes = this.scopesFrom(from, additionalScopes);
245
+
246
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
247
+ const finalExecutionPayload = feeExecutionPayload
248
+ ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
249
+ : executionPayload;
250
+ const chainInfo = await this.getChainInfo();
251
+
252
+ const accountOverrides = await this.buildAccountOverrides(scopes);
253
+ const overrides = new SimulationOverrides(accountOverrides);
254
+
255
+ let txRequest: TxExecutionRequest;
256
+ if (from === NO_FROM) {
257
+ const entrypoint = new DefaultEntrypoint();
258
+ txRequest = await entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
144
259
  } else {
145
- const { instance, artifact } = await this.accountContracts.getMulticallContract();
146
- const account = new SignerlessAccount();
147
- return {
148
- instance,
149
- account,
150
- artifact,
260
+ const { type } = await this.walletDB.retrieveAccount(from);
261
+ const originalAccount = await this.getAccountFromAddress(from);
262
+ const completeAddress = originalAccount.getCompleteAddress();
263
+ const account = await this.accountContracts.createStubAccount(completeAddress, type);
264
+ const executionOptions: DefaultAccountEntrypointOptions = {
265
+ txNonce: Fr.random(),
266
+ cancellable: this.cancellableTransactions,
267
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
268
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
151
269
  };
270
+ txRequest = await account.createTxExecutionRequest(
271
+ finalExecutionPayload,
272
+ feeOptions.gasSettings,
273
+ chainInfo,
274
+ executionOptions,
275
+ );
152
276
  }
277
+
278
+ const result = await this.pxe.simulateTx(txRequest, {
279
+ simulatePublic: true,
280
+ skipFeeEnforcement,
281
+ skipTxValidation,
282
+ overrides,
283
+ scopes,
284
+ senderForTags: this.senderForTagsFrom(from, sendMessagesAs),
285
+ });
286
+ const appCallOffset = await this.computeAppCallOffset(from, feeOptions);
287
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
153
288
  }
154
289
 
155
290
  protected async createAccountInternal(
@@ -221,7 +356,12 @@ export class EmbeddedWallet extends BaseWallet {
221
356
  this.minFeePadding = value ?? 0.5;
222
357
  }
223
358
 
224
- stop() {
225
- return this.pxe.stop();
359
+ setEstimatedGasPadding(value?: number) {
360
+ this.estimatedGasPadding = value ?? DEFAULT_ESTIMATED_GAS_PADDING;
361
+ }
362
+
363
+ async stop(): Promise<void> {
364
+ await this.pxe.stop();
365
+ await this.walletDB.close();
226
366
  }
227
367
  }
@@ -6,7 +6,7 @@ import { type PXEConfig, getPXEConfig } from '@aztec/pxe/config';
6
6
 
7
7
  import { LazyAccountContractsProvider } from '../account-contract-providers/lazy.js';
8
8
  import type { AccountContractsProvider } from '../account-contract-providers/types.js';
9
- import { EmbeddedWallet, type EmbeddedWalletOptions } from '../embedded_wallet.js';
9
+ import { EmbeddedWallet, type EmbeddedWalletOptions, splitPxeOptions } from '../embedded_wallet.js';
10
10
  import { WalletDB } from '../wallet_db.js';
11
11
 
12
12
  export class BrowserEmbeddedWallet extends EmbeddedWallet {
@@ -26,10 +26,15 @@ export class BrowserEmbeddedWallet extends EmbeddedWallet {
26
26
  const aztecNode = typeof nodeOrUrl === 'string' ? createAztecNodeClient(nodeOrUrl) : nodeOrUrl;
27
27
  const l1Contracts = await aztecNode.getL1ContractAddresses();
28
28
 
29
+ // Support both the new unified `pxe` option and the deprecated `pxeConfig`/`pxeOptions`.
30
+ const { config: pxeConfigFromPxe, creation: pxeCreationFromPxe } = splitPxeOptions(options.pxe);
31
+ const mergedConfigOverrides = { ...options.pxeConfig, ...pxeConfigFromPxe };
32
+ const mergedCreationOverrides: PXECreationOptions = { ...options.pxeOptions, ...pxeCreationFromPxe };
33
+
29
34
  const pxeConfig: PXEConfig = Object.assign(getPXEConfig(), {
30
- proverEnabled: options.pxeConfig?.proverEnabled ?? false,
35
+ proverEnabled: mergedConfigOverrides.proverEnabled ?? false,
31
36
  dataDirectory: `pxe_data_${l1Contracts.rollupAddress}`,
32
- ...options.pxeConfig,
37
+ ...mergedConfigOverrides,
33
38
  });
34
39
 
35
40
  if (options.ephemeral) {
@@ -37,36 +42,45 @@ export class BrowserEmbeddedWallet extends EmbeddedWallet {
37
42
  }
38
43
 
39
44
  const pxeOptions: PXECreationOptions = {
40
- ...options.pxeOptions,
45
+ ...mergedCreationOverrides,
41
46
  loggers: {
42
47
  store: rootLogger.createChild('pxe:data'),
43
48
  pxe: rootLogger.createChild('pxe:service'),
44
49
  prover: rootLogger.createChild('pxe:prover'),
45
- ...options.pxeOptions?.loggers,
50
+ ...mergedCreationOverrides.loggers,
46
51
  },
47
52
  };
48
53
 
49
54
  const pxe = await createPXE(aztecNode, pxeConfig, pxeOptions);
50
55
 
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);
56
+ const walletDBStore =
57
+ options.walletDb?.store ??
58
+ (options.ephemeral
59
+ ? await openTmpStore(true)
60
+ : await createStore(
61
+ 'wallet_data',
62
+ {
63
+ dataDirectory: `wallet_data_${l1Contracts.rollupAddress}`,
64
+ dataStoreMapSizeKb: pxeConfig.dataStoreMapSizeKb,
65
+ l1Contracts,
66
+ },
67
+ 1,
68
+ rootLogger.createChild('wallet:data'),
69
+ ));
70
+ const walletDB = new WalletDB(walletDBStore, rootLogger.createChild('wallet:db').info);
64
71
 
65
72
  return new this(pxe, aztecNode, walletDB, new LazyAccountContractsProvider(), rootLogger) as T;
66
73
  }
67
74
  }
68
75
 
69
76
  export { BrowserEmbeddedWallet as EmbeddedWallet };
70
- export type { EmbeddedWalletOptions } from '../embedded_wallet.js';
77
+ export type { EmbeddedWalletOptions, EmbeddedWalletPXEOptions } from '../embedded_wallet.js';
71
78
  export { WalletDB } from '../wallet_db.js';
72
79
  export type { AccountType } from '../wallet_db.js';
80
+
81
+ // At-rest encryption helpers are intentionally NOT re-exported here. They live
82
+ // on the `@aztec/wallets/embedded/store-encryption` sub-path so consumers
83
+ // (and bundlers) of this entrypoint don't transitively pull in
84
+ // `@aztec/kv-store/sqlite-opfs` and its `new Worker(new URL('./worker.js'))`
85
+ // chain into `@aztec/sqlite3mc-wasm`. Apps that don't use encryption-at-rest
86
+ // (e.g. the playground) should never see sqlite-opfs in their bundle.
@@ -7,7 +7,7 @@ import type { AztecNode } from '@aztec/stdlib/interfaces/client';
7
7
 
8
8
  import { BundleAccountContractsProvider } from '../account-contract-providers/bundle.js';
9
9
  import type { AccountContractsProvider } from '../account-contract-providers/types.js';
10
- import { EmbeddedWallet, type EmbeddedWalletOptions } from '../embedded_wallet.js';
10
+ import { EmbeddedWallet, type EmbeddedWalletOptions, splitPxeOptions } from '../embedded_wallet.js';
11
11
  import { WalletDB } from '../wallet_db.js';
12
12
 
13
13
  export class NodeEmbeddedWallet extends EmbeddedWallet {
@@ -27,10 +27,15 @@ export class NodeEmbeddedWallet extends EmbeddedWallet {
27
27
  const aztecNode = typeof nodeOrUrl === 'string' ? createAztecNodeClient(nodeOrUrl) : nodeOrUrl;
28
28
  const l1Contracts = await aztecNode.getL1ContractAddresses();
29
29
 
30
+ // Support both the new unified `pxe` option and the deprecated `pxeConfig`/`pxeOptions`.
31
+ const { config: pxeConfigFromPxe, creation: pxeCreationFromPxe } = splitPxeOptions(options.pxe);
32
+ const mergedConfigOverrides = { ...options.pxeConfig, ...pxeConfigFromPxe };
33
+ const mergedCreationOverrides: PXECreationOptions = { ...options.pxeOptions, ...pxeCreationFromPxe };
34
+
30
35
  const pxeConfig: PXEConfig = Object.assign(getPXEConfig(), {
31
- proverEnabled: options.pxeConfig?.proverEnabled ?? false,
36
+ proverEnabled: mergedConfigOverrides.proverEnabled ?? false,
32
37
  dataDirectory: `pxe_data_${l1Contracts.rollupAddress}`,
33
- ...options.pxeConfig,
38
+ ...mergedConfigOverrides,
34
39
  });
35
40
 
36
41
  if (options.ephemeral) {
@@ -38,42 +43,44 @@ export class NodeEmbeddedWallet extends EmbeddedWallet {
38
43
  }
39
44
 
40
45
  const pxeOptions: PXECreationOptions = {
41
- ...options.pxeOptions,
46
+ ...mergedCreationOverrides,
42
47
  loggers: {
43
48
  store: rootLogger.createChild('pxe:data'),
44
49
  pxe: rootLogger.createChild('pxe:service'),
45
50
  prover: rootLogger.createChild('pxe:prover'),
46
- ...options.pxeOptions?.loggers,
51
+ ...mergedCreationOverrides.loggers,
47
52
  },
48
53
  };
49
54
 
50
55
  const pxe = await createPXE(aztecNode, pxeConfig, pxeOptions);
51
56
 
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);
57
+ const walletDBStore =
58
+ options.walletDb?.store ??
59
+ (options.ephemeral
60
+ ? await openTmpStore(
61
+ `wallet_data_${l1Contracts.rollupAddress}`,
62
+ true,
63
+ undefined,
64
+ undefined,
65
+ rootLogger.createChild('wallet:data').getBindings(),
66
+ )
67
+ : await createStore(
68
+ 'wallet_data',
69
+ 1,
70
+ {
71
+ dataDirectory: `wallet_data_${l1Contracts.rollupAddress}`,
72
+ dataStoreMapSizeKb: pxeConfig.dataStoreMapSizeKb,
73
+ l1Contracts,
74
+ },
75
+ rootLogger.createChild('wallet:data').getBindings(),
76
+ ));
77
+ const walletDB = new WalletDB(walletDBStore, rootLogger.createChild('wallet:db').info);
71
78
 
72
79
  return new this(pxe, aztecNode, walletDB, new BundleAccountContractsProvider(), rootLogger) as T;
73
80
  }
74
81
  }
75
82
 
76
83
  export { NodeEmbeddedWallet as EmbeddedWallet };
77
- export type { EmbeddedWalletOptions } from '../embedded_wallet.js';
84
+ export type { EmbeddedWalletOptions, EmbeddedWalletPXEOptions } from '../embedded_wallet.js';
78
85
  export { WalletDB } from '../wallet_db.js';
79
86
  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
+ }