@aztec/wallets 0.0.1-commit.3fd054f6 → 0.0.1-commit.431c48d

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