@aztec-labs/wallets 6.0.0-nightly.20260829

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 (41) hide show
  1. package/dest/embedded/account-contract-providers/bundle.d.ts +19 -0
  2. package/dest/embedded/account-contract-providers/bundle.d.ts.map +1 -0
  3. package/dest/embedded/account-contract-providers/bundle.js +29 -0
  4. package/dest/embedded/account-contract-providers/lazy.d.ts +19 -0
  5. package/dest/embedded/account-contract-providers/lazy.d.ts.map +1 -0
  6. package/dest/embedded/account-contract-providers/lazy.js +39 -0
  7. package/dest/embedded/account-contract-providers/types.d.ts +20 -0
  8. package/dest/embedded/account-contract-providers/types.d.ts.map +1 -0
  9. package/dest/embedded/account-contract-providers/types.js +6 -0
  10. package/dest/embedded/embedded_wallet.d.ts +103 -0
  11. package/dest/embedded/embedded_wallet.d.ts.map +1 -0
  12. package/dest/embedded/embedded_wallet.js +359 -0
  13. package/dest/embedded/entrypoints/browser.d.ts +14 -0
  14. package/dest/embedded/entrypoints/browser.d.ts.map +1 -0
  15. package/dest/embedded/entrypoints/browser.js +72 -0
  16. package/dest/embedded/entrypoints/node.d.ts +14 -0
  17. package/dest/embedded/entrypoints/node.d.ts.map +1 -0
  18. package/dest/embedded/entrypoints/node.js +75 -0
  19. package/dest/embedded/entrypoints/resolve_aztec_node.d.ts +4 -0
  20. package/dest/embedded/entrypoints/resolve_aztec_node.d.ts.map +1 -0
  21. package/dest/embedded/entrypoints/resolve_aztec_node.js +4 -0
  22. package/dest/embedded/store_encryption.d.ts +74 -0
  23. package/dest/embedded/store_encryption.d.ts.map +1 -0
  24. package/dest/embedded/store_encryption.js +93 -0
  25. package/dest/embedded/wallet_db.d.ts +41 -0
  26. package/dest/embedded/wallet_db.d.ts.map +1 -0
  27. package/dest/embedded/wallet_db.js +133 -0
  28. package/dest/testing.d.ts +16 -0
  29. package/dest/testing.d.ts.map +1 -0
  30. package/dest/testing.js +18 -0
  31. package/package.json +102 -0
  32. package/src/embedded/account-contract-providers/bundle.ts +43 -0
  33. package/src/embedded/account-contract-providers/lazy.ts +53 -0
  34. package/src/embedded/account-contract-providers/types.ts +21 -0
  35. package/src/embedded/embedded_wallet.ts +481 -0
  36. package/src/embedded/entrypoints/browser.ts +93 -0
  37. package/src/embedded/entrypoints/node.ts +100 -0
  38. package/src/embedded/entrypoints/resolve_aztec_node.ts +10 -0
  39. package/src/embedded/store_encryption.ts +146 -0
  40. package/src/embedded/wallet_db.ts +150 -0
  41. package/src/testing.ts +37 -0
@@ -0,0 +1,481 @@
1
+ import { type Account, NO_FROM } from '@aztec-labs/aztec.js/account';
2
+ import { CallAuthorizationRequest } from '@aztec-labs/aztec.js/authorization';
3
+ import {
4
+ ContractFunctionInteraction,
5
+ type InteractionWaitOptions,
6
+ NO_WAIT,
7
+ type SendReturn,
8
+ type WaitOpts,
9
+ } from '@aztec-labs/aztec.js/contracts';
10
+ import type { AztecNodeClientOptions } from '@aztec-labs/aztec.js/node';
11
+ import type {
12
+ Aliased,
13
+ ExecuteUtilityOptions,
14
+ PrivateEvent,
15
+ PrivateEventFilter,
16
+ ProfileOptions,
17
+ SendOptions,
18
+ SimulateOptions,
19
+ } from '@aztec-labs/aztec.js/wallet';
20
+ import { AccountManager, TxSimulationResultWithAppOffset } from '@aztec-labs/aztec.js/wallet';
21
+ import type { DefaultAccountEntrypointOptions } from '@aztec-labs/entrypoints/account';
22
+ import { DefaultEntrypoint } from '@aztec-labs/entrypoints/default';
23
+ import { poseidon2Hash } from '@aztec-labs/foundation/crypto/poseidon';
24
+ import { Schnorr } from '@aztec-labs/foundation/crypto/schnorr';
25
+ import { Fq, Fr } from '@aztec-labs/foundation/curves/bn254';
26
+ import type { Logger } from '@aztec-labs/foundation/log';
27
+ import type { AztecAsyncKVStore } from '@aztec-labs/kv-store';
28
+ import type { PXEConfig, PXECreationOptions } from '@aztec-labs/pxe/client/lazy';
29
+ import type { PXE } from '@aztec-labs/pxe/server';
30
+ import type { EventMetadataDefinition, FunctionCall } from '@aztec-labs/stdlib/abi';
31
+ import { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
32
+ import { getContractClassFromArtifact } from '@aztec-labs/stdlib/contract';
33
+ import { GasSettings } from '@aztec-labs/stdlib/gas';
34
+ import type { AztecNode } from '@aztec-labs/stdlib/interfaces/client';
35
+ import {
36
+ type ContractOverrides,
37
+ ExecutionPayload,
38
+ SimulationOverrides,
39
+ type TxExecutionRequest,
40
+ type TxProfileResult,
41
+ TxStatus,
42
+ type UtilityExecutionResult,
43
+ collectOffchainEffects,
44
+ mergeExecutionPayloads,
45
+ } from '@aztec-labs/stdlib/tx';
46
+ import { BaseWallet, type SimulateViaEntrypointOptions, getGasLimits } from '@aztec-labs/wallet-sdk/base-wallet';
47
+
48
+ import type { AccountContractsProvider } from './account-contract-providers/types.js';
49
+ import { type AccountType, WalletDB } from './wallet_db.js';
50
+
51
+ /** Options for the PXE instance created by the EmbeddedWallet. */
52
+ export type EmbeddedWalletPXEOptions = Partial<PXEConfig> & PXECreationOptions;
53
+
54
+ /** Splits a unified EmbeddedWalletPXEOptions into PXEConfig overrides and PXECreationOptions. */
55
+ export function splitPxeOptions(pxe?: EmbeddedWalletPXEOptions): {
56
+ config: Partial<PXEConfig>;
57
+ creation: PXECreationOptions;
58
+ } {
59
+ if (!pxe) {
60
+ return { config: {}, creation: {} };
61
+ }
62
+ const { loggers, loggerActorLabel, proverOrOptions, store, simulator, hooks, preloadedContractsProvider, ...config } =
63
+ pxe;
64
+ return {
65
+ config,
66
+ creation: { loggers, loggerActorLabel, proverOrOptions, store, simulator, hooks, preloadedContractsProvider },
67
+ };
68
+ }
69
+
70
+ /** Options for the EmbeddedWallet's own DB (accounts, senders — distinct from PXE state). */
71
+ export type EmbeddedWalletDBOptions = {
72
+ /** Override the wallet DB backend. If omitted, an IndexedDB (browser) / LMDB (node) store is created. */
73
+ store?: AztecAsyncKVStore;
74
+ };
75
+
76
+ export type EmbeddedWalletOptions = {
77
+ /** Parent logger. Child loggers are derived via createChild() for each subsystem. */
78
+ logger?: Logger;
79
+ /** Use ephemeral (in-memory) stores. Data will not persist across sessions. */
80
+ ephemeral?: boolean;
81
+ /** PXE configuration and dependency overrides (custom store, prover, simulator). */
82
+ pxe?: EmbeddedWalletPXEOptions;
83
+ /** Wallet DB dependency overrides (custom store). */
84
+ walletDb?: EmbeddedWalletDBOptions;
85
+ /** JSON-RPC client options used when the wallet is created from a node URL. */
86
+ nodeClientOptions?: AztecNodeClientOptions;
87
+ /**
88
+ * Override PXE configuration.
89
+ * @deprecated Use `pxe` instead.
90
+ */
91
+ pxeConfig?: Partial<PXEConfig>;
92
+ /**
93
+ * Advanced PXE creation options (custom store, prover, simulator).
94
+ * @deprecated Use `pxe` instead.
95
+ */
96
+ pxeOptions?: PXECreationOptions;
97
+ };
98
+
99
+ const DEFAULT_ESTIMATED_GAS_PADDING = 0.1;
100
+
101
+ export class EmbeddedWallet extends BaseWallet {
102
+ protected estimatedGasPadding = DEFAULT_ESTIMATED_GAS_PADDING;
103
+
104
+ // Stub class ids, populated on wallet startup
105
+ // to avoid redundant work per simulation
106
+ protected stubClassIds = new Map<AccountType, Fr>();
107
+
108
+ constructor(
109
+ pxe: PXE,
110
+ aztecNode: AztecNode,
111
+ protected walletDB: WalletDB,
112
+ protected accountContracts: AccountContractsProvider,
113
+ log?: Logger,
114
+ ) {
115
+ super(pxe, aztecNode, log);
116
+ }
117
+
118
+ protected async getAccountFromAddress(address: AztecAddress): Promise<Account> {
119
+ const { secretKey, salt, signingKey, type } = await this.walletDB.retrieveAccount(address);
120
+ const accountManager = await this.createAccountInternal(type, secretKey, salt, signingKey);
121
+ const account = await accountManager.getAccount();
122
+
123
+ if (!account) {
124
+ throw new Error(`Account not found in wallet for address: ${address}`);
125
+ }
126
+
127
+ return account;
128
+ }
129
+
130
+ getAccounts(): Promise<Aliased<AztecAddress>[]> {
131
+ return this.walletDB.listAccounts();
132
+ }
133
+
134
+ override async registerSender(address: AztecAddress, alias: string) {
135
+ await this.walletDB.storeSender(address, alias);
136
+ await this.pxe.registerTaggingSecretSource({ kind: 'address-derived', sender: address });
137
+ return address;
138
+ }
139
+
140
+ override async getAddressBook(): Promise<Aliased<AztecAddress>[]> {
141
+ const sources = await this.pxe.getTaggingSecretSources({ kind: 'address-derived' });
142
+ const senders = sources.map(source => source.sender);
143
+ const storedSenders = await this.walletDB.listSenders();
144
+ for (const storedSender of storedSenders) {
145
+ if (senders.findIndex(sender => sender.equals(storedSender.item)) === -1) {
146
+ await this.pxe.registerTaggingSecretSource({ kind: 'address-derived', sender: storedSender.item });
147
+ }
148
+ }
149
+ return storedSenders;
150
+ }
151
+
152
+ /**
153
+ * Overrides the base sendTx to add a pre-simulation step before the actual send. The simulation
154
+ * estimates actual gas usage and captures call authorization requests to generate
155
+ * the necessary authwitnesses.
156
+ */
157
+ public override async sendTx<W extends InteractionWaitOptions = undefined>(
158
+ executionPayload: ExecutionPayload,
159
+ opts: SendOptions<W>,
160
+ ): Promise<SendReturn<W>> {
161
+ // PXE has autoSync disabled by the embedded wallet entrypoints, so we sync once here to cover
162
+ // both the inner simulateTx (via simulateViaEntrypoint) and the proveTx that super.sendTx
163
+ await this.pxe.sync();
164
+ const feeOptions = await this.completeFeeOptions({
165
+ from: opts.from,
166
+ feePayer: executionPayload.feePayer,
167
+ gasSettings: opts.fee?.gasSettings,
168
+ forEstimation: true,
169
+ });
170
+
171
+ // Simulate the transaction first to estimate gas and capture required
172
+ // private authwitnesses based on offchain effects.
173
+ const simulationResult = await this.simulateViaEntrypoint(executionPayload, {
174
+ from: opts.from,
175
+ feeOptions,
176
+ additionalScopes: opts.additionalScopes,
177
+ skipTxValidation: true,
178
+ sendMessagesAs: opts.sendMessagesAs,
179
+ });
180
+
181
+ const offchainEffects = collectOffchainEffects(simulationResult.privateExecutionResult);
182
+ const authWitnesses = await Promise.all(
183
+ offchainEffects.map(async effect => {
184
+ try {
185
+ const authRequest = await CallAuthorizationRequest.fromFields(effect.data);
186
+ return this.createAuthWit(authRequest.onBehalfOf, {
187
+ consumer: effect.contractAddress,
188
+ innerHash: authRequest.innerHash,
189
+ });
190
+ } catch {
191
+ return undefined;
192
+ }
193
+ }),
194
+ );
195
+ for (const authwit of authWitnesses) {
196
+ if (authwit) {
197
+ executionPayload.authWitnesses.push(authwit);
198
+ }
199
+ }
200
+ const maxTxGasLimits = await this.getMaxTxGasLimits();
201
+ const estimated = getGasLimits(simulationResult.gasUsed, maxTxGasLimits, this.estimatedGasPadding);
202
+ this.log.verbose(
203
+ `Estimated gas limits for tx: DA=${estimated.gasLimits.daGas} L2=${estimated.gasLimits.l2Gas} teardownDA=${estimated.teardownGasLimits.daGas} teardownL2=${estimated.teardownGasLimits.l2Gas}`,
204
+ );
205
+ const gasSettings = GasSettings.from({
206
+ ...opts.fee?.gasSettings,
207
+ maxFeesPerGas: feeOptions.gasSettings.maxFeesPerGas,
208
+ maxPriorityFeesPerGas: feeOptions.gasSettings.maxPriorityFeesPerGas,
209
+ gasLimits: opts.fee?.gasSettings?.gasLimits ?? estimated.gasLimits,
210
+ teardownGasLimits: opts.fee?.gasSettings?.teardownGasLimits ?? estimated.teardownGasLimits,
211
+ });
212
+ let wait: InteractionWaitOptions = opts.wait;
213
+ if (wait !== NO_WAIT) {
214
+ const callerWaitOpts: WaitOpts = typeof wait === 'object' ? wait : {};
215
+ wait = {
216
+ ...callerWaitOpts,
217
+ // Default to PROPOSED so the wait returns as soon as the tx lands in a proposed L2 block,
218
+ // rather than waiting until the end of the slot for the checkpoint to be published to L1.
219
+ // This is what makes MBPS (Multiple Blocks Per Slot) actually improve UX: with CHECKPOINTED
220
+ // we'd block until L1 inclusion regardless of how early in the slot the tx was sequenced.
221
+ // The tradeoff is a weaker guarantee — a proposed block only becomes canonical once it (or
222
+ // a later block in the same slot) is checkpointed, so a tx could be re-orged out if the
223
+ // proposer fails to publish to L1 (which should be rare, since they'd get slashed for it).
224
+ waitForStatus: callerWaitOpts.waitForStatus ?? TxStatus.PROPOSED,
225
+ };
226
+ }
227
+ return super.sendTx(executionPayload, {
228
+ ...opts,
229
+ wait: wait as W,
230
+ fee: { ...opts.fee, gasSettings },
231
+ });
232
+ }
233
+
234
+ /**
235
+ * Overrides the base simulateTx to drive PXE syncing explicitly. The PXE created by the embedded
236
+ * wallet has autoSync disabled (so we can share one sync across simulate+send in sendTx); for
237
+ * standalone simulations we still need a fresh anchor block, which we provide here.
238
+ */
239
+ public override async simulateTx(
240
+ executionPayload: ExecutionPayload,
241
+ opts: SimulateOptions,
242
+ ): Promise<TxSimulationResultWithAppOffset> {
243
+ await this.pxe.sync();
244
+ return super.simulateTx(executionPayload, opts);
245
+ }
246
+
247
+ public override async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
248
+ await this.pxe.sync();
249
+ return super.profileTx(executionPayload, opts);
250
+ }
251
+
252
+ public override async executeUtility(
253
+ call: FunctionCall,
254
+ opts: ExecuteUtilityOptions,
255
+ ): Promise<UtilityExecutionResult> {
256
+ await this.pxe.sync();
257
+ return super.executeUtility(call, opts);
258
+ }
259
+
260
+ public override async getPrivateEvents<T>(
261
+ eventDef: EventMetadataDefinition,
262
+ eventFilter: PrivateEventFilter,
263
+ ): Promise<PrivateEvent<T>[]> {
264
+ await this.pxe.sync();
265
+ return super.getPrivateEvents<T>(eventDef, eventFilter);
266
+ }
267
+
268
+ /**
269
+ * Hashes and registers the stub class for every supported account type with PXE, populating
270
+ * stubClassIds. Called on wallet initialization.
271
+ */
272
+ async initStubClasses(): Promise<void> {
273
+ const schnorrArtifact = await this.accountContracts.getStubAccountContractArtifact('schnorr');
274
+ const { id: schnorrClassId } = await getContractClassFromArtifact(schnorrArtifact);
275
+ await this.pxe.registerContractClass(schnorrArtifact);
276
+
277
+ // ecdsa stubs share the same class id
278
+ const ecdsaArtifact = await this.accountContracts.getStubAccountContractArtifact('ecdsasecp256r1');
279
+ const { id: ecdsaClassId } = await getContractClassFromArtifact(ecdsaArtifact);
280
+ await this.pxe.registerContractClass(ecdsaArtifact);
281
+
282
+ this.stubClassIds.set('schnorr', schnorrClassId);
283
+ this.stubClassIds.set('schnorr_initializerless', schnorrClassId);
284
+ this.stubClassIds.set('ecdsasecp256k1', ecdsaClassId);
285
+ this.stubClassIds.set('ecdsasecp256r1', ecdsaClassId);
286
+ }
287
+
288
+ /**
289
+ * Builds contract overrides for all provided addresses by replacing their account contracts with stub implementations.
290
+ * Uses a type-specific stub artifact so that the stub's constructor selector matches the real account's constructor.
291
+ */
292
+ protected async buildAccountOverrides(addresses: AztecAddress[]): Promise<ContractOverrides> {
293
+ const accounts = await this.getAccounts();
294
+ const contracts: ContractOverrides = {};
295
+
296
+ const filtered = accounts.filter(acc => addresses.some(addr => addr.equals(acc.item)));
297
+
298
+ for (const account of filtered) {
299
+ const address = account.item;
300
+ const { type } = await this.walletDB.retrieveAccount(address);
301
+ const stubClassId = this.stubClassIds.get(type);
302
+ if (!stubClassId) {
303
+ throw new Error(
304
+ `Stub class for account type '${type}' was not registered at wallet init. This is a bug — initStubClasses should cover every supported AccountType.`,
305
+ );
306
+ }
307
+
308
+ const originalAccount = await this.getAccountFromAddress(address);
309
+ const completeAddress = originalAccount.getCompleteAddress();
310
+ const contractInstance = await this.pxe.getContractInstance(completeAddress.address);
311
+ if (!contractInstance) {
312
+ throw new Error(
313
+ `No contract instance found for address: ${completeAddress.address} during account override building. This is a bug!`,
314
+ );
315
+ }
316
+
317
+ contracts[address.toString()] = {
318
+ instance: { ...contractInstance, currentContractClassId: stubClassId },
319
+ };
320
+ }
321
+
322
+ return contracts;
323
+ }
324
+
325
+ /**
326
+ * Simulates calls via a stub account entrypoint, bypassing real account authorization.
327
+ * This allows kernelless simulation with contract overrides, skipping expensive
328
+ * private kernel circuit execution.
329
+ */
330
+ protected override async simulateViaEntrypoint(
331
+ executionPayload: ExecutionPayload,
332
+ opts: SimulateViaEntrypointOptions,
333
+ ): Promise<TxSimulationResultWithAppOffset> {
334
+ const { from, feeOptions, additionalScopes, skipTxValidation, skipFeeEnforcement, sendMessagesAs } = opts;
335
+ const scopes = this.scopesFrom(from, additionalScopes ?? [], sendMessagesAs);
336
+
337
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
338
+ const finalExecutionPayload = feeExecutionPayload
339
+ ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
340
+ : executionPayload;
341
+ const chainInfo = await this.getChainInfo();
342
+
343
+ const accountOverrides = await this.buildAccountOverrides(scopes);
344
+ const overrides = new SimulationOverrides({ contracts: accountOverrides });
345
+
346
+ let txRequest: TxExecutionRequest;
347
+ if (from === NO_FROM) {
348
+ const entrypoint = new DefaultEntrypoint();
349
+ txRequest = await entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
350
+ } else {
351
+ const { type } = await this.walletDB.retrieveAccount(from);
352
+ const originalAccount = await this.getAccountFromAddress(from);
353
+ const completeAddress = originalAccount.getCompleteAddress();
354
+ const account = await this.accountContracts.createStubAccount(completeAddress, type);
355
+ const executionOptions: DefaultAccountEntrypointOptions = {
356
+ txNonce: Fr.random(),
357
+ cancellable: this.cancellableTransactions,
358
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
359
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
360
+ };
361
+ txRequest = await account.createTxExecutionRequest(
362
+ finalExecutionPayload,
363
+ feeOptions.gasSettings,
364
+ chainInfo,
365
+ executionOptions,
366
+ );
367
+ }
368
+
369
+ const result = await this.pxe.simulateTx(txRequest, {
370
+ simulatePublic: true,
371
+ skipFeeEnforcement,
372
+ skipTxValidation,
373
+ overrides,
374
+ scopes,
375
+ senderForTags: this.senderForTagsFrom(from, sendMessagesAs),
376
+ });
377
+ const appCallOffset = await this.computeAppCallOffset(from, feeOptions);
378
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
379
+ }
380
+
381
+ protected async createAccountInternal(
382
+ type: AccountType,
383
+ secret: Fr,
384
+ salt: Fr,
385
+ signingKey: Buffer,
386
+ ): Promise<AccountManager> {
387
+ let contract;
388
+ let immutablesHash;
389
+ let publicKey;
390
+ switch (type) {
391
+ case 'schnorr': {
392
+ contract = await this.accountContracts.getSchnorrAccountContract(Fq.fromBuffer(signingKey));
393
+ break;
394
+ }
395
+ case 'schnorr_initializerless': {
396
+ contract = await this.accountContracts.getSchnorrInitializerlessAccountContract(Fq.fromBuffer(signingKey));
397
+ publicKey = await new Schnorr().computePublicKey(Fq.fromBuffer(signingKey));
398
+ immutablesHash = await poseidon2Hash([publicKey.x, publicKey.y]);
399
+ break;
400
+ }
401
+ case 'ecdsasecp256k1': {
402
+ contract = await this.accountContracts.getEcdsaKAccountContract(signingKey);
403
+ break;
404
+ }
405
+ case 'ecdsasecp256r1': {
406
+ contract = await this.accountContracts.getEcdsaRAccountContract(signingKey);
407
+ break;
408
+ }
409
+ default: {
410
+ throw new Error(`Unknown account type ${type}`);
411
+ }
412
+ }
413
+
414
+ const accountManager = await AccountManager.create(this, secret, contract, { salt, immutablesHash });
415
+
416
+ const instance = accountManager.getInstance();
417
+ const existingInstance = await this.pxe.getContractInstance(instance.address);
418
+ if (!existingInstance) {
419
+ const existingArtifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
420
+ const artifact = existingArtifact ?? (await accountManager.getAccountContract().getContractArtifact());
421
+ await this.registerContract(
422
+ instance,
423
+ !existingArtifact ? await accountManager.getAccountContract().getContractArtifact() : undefined,
424
+ accountManager.getSecretKey(),
425
+ );
426
+ if (type === 'schnorr_initializerless') {
427
+ const constructor = artifact.functions.find(f => f.name === 'constructor');
428
+ if (!constructor) {
429
+ throw new Error('Could not create SchnorrInitializerlessAccountContract: constructor ABI not found');
430
+ }
431
+ const storeCall = new ContractFunctionInteraction(this, instance.address, constructor, [
432
+ publicKey!.x,
433
+ publicKey!.y,
434
+ ]);
435
+ await storeCall.simulate({ from: instance.address });
436
+ }
437
+ }
438
+ return accountManager;
439
+ }
440
+
441
+ async createAndStoreAccount(
442
+ alias: string,
443
+ type: AccountType,
444
+ secret: Fr,
445
+ salt: Fr,
446
+ signingKey: Buffer,
447
+ ): Promise<AccountManager> {
448
+ const accountManager = await this.createAccountInternal(type, secret, salt, signingKey);
449
+ await this.walletDB.storeAccount(accountManager.address, { type, secretKey: secret, salt, alias, signingKey });
450
+ return accountManager;
451
+ }
452
+
453
+ createSchnorrAccount(secret: Fr, salt: Fr, signingKey: Fq, alias?: string): Promise<AccountManager> {
454
+ return this.createAndStoreAccount(alias ?? '', 'schnorr', secret, salt, signingKey.toBuffer());
455
+ }
456
+
457
+ createSchnorrInitializerlessAccount(secret: Fr, salt: Fr, signingKey: Fq, alias?: string): Promise<AccountManager> {
458
+ return this.createAndStoreAccount(alias ?? '', 'schnorr_initializerless', secret, salt, signingKey.toBuffer());
459
+ }
460
+
461
+ createECDSARAccount(secret: Fr, salt: Fr, signingKey: Buffer, alias?: string): Promise<AccountManager> {
462
+ return this.createAndStoreAccount(alias ?? '', 'ecdsasecp256r1', secret, salt, signingKey);
463
+ }
464
+
465
+ createECDSAKAccount(secret: Fr, salt: Fr, signingKey: Buffer, alias?: string): Promise<AccountManager> {
466
+ return this.createAndStoreAccount(alias ?? '', 'ecdsasecp256k1', secret, salt, signingKey);
467
+ }
468
+
469
+ setMinFeePadding(value?: number) {
470
+ this.minFeePadding = value ?? 0.5;
471
+ }
472
+
473
+ setEstimatedGasPadding(value?: number) {
474
+ this.estimatedGasPadding = value ?? DEFAULT_ESTIMATED_GAS_PADDING;
475
+ }
476
+
477
+ async stop(): Promise<void> {
478
+ await this.pxe.stop();
479
+ await this.walletDB.close();
480
+ }
481
+ }
@@ -0,0 +1,93 @@
1
+ import type { AztecNode } from '@aztec-labs/aztec.js/node';
2
+ import { type Logger, createLogger } from '@aztec-labs/foundation/log';
3
+ import { openTmpStore } from '@aztec-labs/kv-store/sqlite-opfs';
4
+ import { type PXE, type PXECreationOptions, createPXE, openBrowserStore } from '@aztec-labs/pxe/client/lazy';
5
+ import { type PXEConfig, getPXEConfig } from '@aztec-labs/pxe/config';
6
+ import { getStandardAuthRegistry } from '@aztec-labs/standard-contracts/auth-registry/lazy';
7
+ import { getStandardHandshakeRegistry } from '@aztec-labs/standard-contracts/handshake-registry/lazy';
8
+ import { getStandardMultiCallEntrypoint } from '@aztec-labs/standard-contracts/multi-call-entrypoint/lazy';
9
+
10
+ import { LazyAccountContractsProvider } from '../account-contract-providers/lazy.js';
11
+ import type { AccountContractsProvider } from '../account-contract-providers/types.js';
12
+ import { EmbeddedWallet, type EmbeddedWalletOptions, splitPxeOptions } from '../embedded_wallet.js';
13
+ import { WALLET_DATA_SCHEMA_VERSION, WalletDB } from '../wallet_db.js';
14
+ import { resolveAztecNode } from './resolve_aztec_node.js';
15
+
16
+ export class BrowserEmbeddedWallet extends EmbeddedWallet {
17
+ static async create<T extends BrowserEmbeddedWallet = BrowserEmbeddedWallet>(
18
+ this: new (
19
+ pxe: PXE,
20
+ aztecNode: AztecNode,
21
+ walletDB: WalletDB,
22
+ accountContracts: AccountContractsProvider,
23
+ log?: Logger,
24
+ ) => T,
25
+ nodeOrUrl: string | AztecNode,
26
+ options: EmbeddedWalletOptions = {},
27
+ ): Promise<T> {
28
+ const rootLogger = options.logger ?? createLogger('embedded-wallet');
29
+
30
+ const aztecNode = resolveAztecNode(nodeOrUrl, options.nodeClientOptions);
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
+
37
+ const pxeConfig: PXEConfig = Object.assign(getPXEConfig(), {
38
+ proverEnabled: mergedConfigOverrides.proverEnabled,
39
+ // Unused in the browser: sqlite-opfs keys stores by name, not directory.
40
+ dataDirectory: 'pxe_data',
41
+ autoSync: false,
42
+ ...mergedConfigOverrides,
43
+ });
44
+
45
+ if (options.ephemeral) {
46
+ delete pxeConfig.dataDirectory;
47
+ }
48
+
49
+ const pxeOptions: PXECreationOptions = {
50
+ ...mergedCreationOverrides,
51
+ preloadedContractsProvider: mergedCreationOverrides.preloadedContractsProvider ?? {
52
+ getPreloadedContracts: async () => [
53
+ await getStandardMultiCallEntrypoint(),
54
+ await getStandardAuthRegistry(),
55
+ await getStandardHandshakeRegistry(),
56
+ ],
57
+ },
58
+ loggers: {
59
+ store: rootLogger.createChild('pxe:data'),
60
+ pxe: rootLogger.createChild('pxe:service'),
61
+ prover: rootLogger.createChild('pxe:prover'),
62
+ ...mergedCreationOverrides.loggers,
63
+ },
64
+ };
65
+
66
+ const pxe = await createPXE(aztecNode, pxeConfig, pxeOptions);
67
+
68
+ let walletDBStore = options.walletDb?.store;
69
+ if (!walletDBStore) {
70
+ if (options.ephemeral) {
71
+ walletDBStore = await openTmpStore(true);
72
+ } else {
73
+ const { l1ChainId, l1ContractAddresses } = await aztecNode.getNodeInfo();
74
+ walletDBStore = await openBrowserStore(
75
+ 'wallet_data',
76
+ WALLET_DATA_SCHEMA_VERSION,
77
+ { l1ChainId, rollupAddress: l1ContractAddresses.rollupAddress },
78
+ rootLogger.createChild('wallet:data'),
79
+ );
80
+ }
81
+ }
82
+ const walletDB = new WalletDB(walletDBStore, rootLogger.createChild('wallet:db').info);
83
+
84
+ const wallet = new this(pxe, aztecNode, walletDB, new LazyAccountContractsProvider(), rootLogger) as T;
85
+ await wallet.initStubClasses();
86
+ return wallet;
87
+ }
88
+ }
89
+
90
+ export { BrowserEmbeddedWallet as EmbeddedWallet };
91
+ export type { EmbeddedWalletOptions, EmbeddedWalletPXEOptions } from '../embedded_wallet.js';
92
+ export { WalletDB } from '../wallet_db.js';
93
+ export type { AccountType } from '../wallet_db.js';
@@ -0,0 +1,100 @@
1
+ import { type Logger, createLogger } from '@aztec-labs/foundation/log';
2
+ import { openTmpStore } from '@aztec-labs/kv-store/lmdb-v2';
3
+ import { type PXEConfig, getPXEConfig } from '@aztec-labs/pxe/config';
4
+ import { type PXE, type PXECreationOptions, createPXE, openStore } from '@aztec-labs/pxe/server';
5
+ import { getStandardAuthRegistry } from '@aztec-labs/standard-contracts/auth-registry';
6
+ import { getStandardHandshakeRegistry } from '@aztec-labs/standard-contracts/handshake-registry';
7
+ import { getStandardMultiCallEntrypoint } from '@aztec-labs/standard-contracts/multi-call-entrypoint';
8
+ import type { AztecNode } from '@aztec-labs/stdlib/interfaces/client';
9
+
10
+ import { BundleAccountContractsProvider } from '../account-contract-providers/bundle.js';
11
+ import type { AccountContractsProvider } from '../account-contract-providers/types.js';
12
+ import { EmbeddedWallet, type EmbeddedWalletOptions, splitPxeOptions } from '../embedded_wallet.js';
13
+ import { WALLET_DATA_SCHEMA_VERSION, WalletDB } from '../wallet_db.js';
14
+ import { resolveAztecNode } from './resolve_aztec_node.js';
15
+
16
+ const DEFAULT_WALLET_DATA_DIRECTORY = 'aztec-wallet-data';
17
+
18
+ export class NodeEmbeddedWallet extends EmbeddedWallet {
19
+ static async create<T extends NodeEmbeddedWallet = NodeEmbeddedWallet>(
20
+ this: new (
21
+ pxe: PXE,
22
+ aztecNode: AztecNode,
23
+ walletDB: WalletDB,
24
+ accountContracts: AccountContractsProvider,
25
+ log?: Logger,
26
+ ) => T,
27
+ nodeOrUrl: string | AztecNode,
28
+ options: EmbeddedWalletOptions = {},
29
+ ): Promise<T> {
30
+ const rootLogger = options.logger ?? createLogger('embedded-wallet');
31
+
32
+ const aztecNode = resolveAztecNode(nodeOrUrl, options.nodeClientOptions);
33
+
34
+ // Support both the new unified `pxe` option and the deprecated `pxeConfig`/`pxeOptions`.
35
+ const { config: pxeConfigFromPxe, creation: pxeCreationFromPxe } = splitPxeOptions(options.pxe);
36
+ const mergedConfigOverrides = { ...options.pxeConfig, ...pxeConfigFromPxe };
37
+ const mergedCreationOverrides: PXECreationOptions = { ...options.pxeOptions, ...pxeCreationFromPxe };
38
+
39
+ const pxeConfig: PXEConfig = Object.assign(getPXEConfig(), {
40
+ proverEnabled: mergedConfigOverrides.proverEnabled,
41
+ dataDirectory: DEFAULT_WALLET_DATA_DIRECTORY,
42
+ autoSync: false,
43
+ ...mergedConfigOverrides,
44
+ });
45
+
46
+ if (options.ephemeral) {
47
+ delete pxeConfig.dataDirectory;
48
+ }
49
+
50
+ const pxeOptions: PXECreationOptions = {
51
+ ...mergedCreationOverrides,
52
+ preloadedContractsProvider: mergedCreationOverrides.preloadedContractsProvider ?? {
53
+ getPreloadedContracts: async () => [
54
+ await getStandardMultiCallEntrypoint(),
55
+ await getStandardAuthRegistry(),
56
+ await getStandardHandshakeRegistry(),
57
+ ],
58
+ },
59
+ loggers: {
60
+ store: rootLogger.createChild('pxe:data'),
61
+ pxe: rootLogger.createChild('pxe:service'),
62
+ prover: rootLogger.createChild('pxe:prover'),
63
+ ...mergedCreationOverrides.loggers,
64
+ },
65
+ };
66
+
67
+ const pxe = await createPXE(aztecNode, pxeConfig, pxeOptions);
68
+
69
+ let walletDBStore = options.walletDb?.store;
70
+ if (!walletDBStore) {
71
+ const bindings = rootLogger.createChild('wallet:data').getBindings();
72
+ if (options.ephemeral) {
73
+ walletDBStore = await openTmpStore('wallet_data', true, undefined, undefined, bindings);
74
+ } else {
75
+ const { l1ChainId, l1ContractAddresses } = await aztecNode.getNodeInfo();
76
+ walletDBStore = await openStore(
77
+ 'wallet_data',
78
+ WALLET_DATA_SCHEMA_VERSION,
79
+ {
80
+ dataDirectory: pxeConfig.dataDirectory ?? DEFAULT_WALLET_DATA_DIRECTORY,
81
+ dataStoreMapSizeKb: pxeConfig.dataStoreMapSizeKb,
82
+ l1ChainId,
83
+ rollupAddress: l1ContractAddresses.rollupAddress,
84
+ },
85
+ bindings,
86
+ );
87
+ }
88
+ }
89
+ const walletDB = new WalletDB(walletDBStore, rootLogger.createChild('wallet:db').info);
90
+
91
+ const wallet = new this(pxe, aztecNode, walletDB, new BundleAccountContractsProvider(), rootLogger) as T;
92
+ await wallet.initStubClasses();
93
+ return wallet;
94
+ }
95
+ }
96
+
97
+ export { NodeEmbeddedWallet as EmbeddedWallet };
98
+ export type { EmbeddedWalletOptions, EmbeddedWalletPXEOptions } from '../embedded_wallet.js';
99
+ export { WalletDB } from '../wallet_db.js';
100
+ export type { AccountType } from '../wallet_db.js';
@@ -0,0 +1,10 @@
1
+ import {
2
+ type AztecNode,
3
+ type AztecNodeClientOptions,
4
+ createAztecNodeClient,
5
+ } from '@aztec-labs/stdlib/interfaces/client';
6
+
7
+ /** Returns a provided node or creates a JSON-RPC client for a node URL. */
8
+ export function resolveAztecNode(nodeOrUrl: string | AztecNode, nodeClientOptions?: AztecNodeClientOptions): AztecNode {
9
+ return typeof nodeOrUrl === 'string' ? createAztecNodeClient(nodeOrUrl, nodeClientOptions) : nodeOrUrl;
10
+ }