@aztec/wallet-sdk 0.0.1-commit.9b94fc1 → 0.0.1-commit.9ee6fcc6

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 (81) hide show
  1. package/README.md +228 -331
  2. package/dest/base-wallet/base_wallet.d.ts +74 -16
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +185 -33
  5. package/dest/base-wallet/index.d.ts +3 -2
  6. package/dest/base-wallet/index.d.ts.map +1 -1
  7. package/dest/base-wallet/index.js +1 -0
  8. package/dest/base-wallet/utils.d.ts +49 -0
  9. package/dest/base-wallet/utils.d.ts.map +1 -0
  10. package/dest/base-wallet/utils.js +131 -0
  11. package/dest/crypto.d.ts +192 -0
  12. package/dest/crypto.d.ts.map +1 -0
  13. package/dest/crypto.js +394 -0
  14. package/dest/emoji_alphabet.d.ts +35 -0
  15. package/dest/emoji_alphabet.d.ts.map +1 -0
  16. package/dest/emoji_alphabet.js +299 -0
  17. package/dest/extension/handlers/background_connection_handler.d.ts +158 -0
  18. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -0
  19. package/dest/extension/handlers/background_connection_handler.js +258 -0
  20. package/dest/extension/handlers/content_script_connection_handler.d.ts +56 -0
  21. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -0
  22. package/dest/extension/handlers/content_script_connection_handler.js +174 -0
  23. package/dest/extension/handlers/index.d.ts +12 -0
  24. package/dest/extension/handlers/index.d.ts.map +1 -0
  25. package/dest/extension/handlers/index.js +10 -0
  26. package/dest/extension/handlers/internal_message_types.d.ts +63 -0
  27. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -0
  28. package/dest/extension/handlers/internal_message_types.js +22 -0
  29. package/dest/extension/provider/extension_provider.d.ts +107 -0
  30. package/dest/extension/provider/extension_provider.d.ts.map +1 -0
  31. package/dest/extension/provider/extension_provider.js +160 -0
  32. package/dest/extension/provider/extension_wallet.d.ts +132 -0
  33. package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
  34. package/dest/extension/provider/extension_wallet.js +278 -0
  35. package/dest/extension/provider/index.d.ts +3 -0
  36. package/dest/extension/provider/index.d.ts.map +1 -0
  37. package/dest/manager/index.d.ts +2 -7
  38. package/dest/manager/index.d.ts.map +1 -1
  39. package/dest/manager/index.js +0 -4
  40. package/dest/manager/types.d.ts +108 -5
  41. package/dest/manager/types.d.ts.map +1 -1
  42. package/dest/manager/types.js +17 -1
  43. package/dest/manager/wallet_manager.d.ts +50 -7
  44. package/dest/manager/wallet_manager.d.ts.map +1 -1
  45. package/dest/manager/wallet_manager.js +178 -29
  46. package/dest/types.d.ts +123 -0
  47. package/dest/types.d.ts.map +1 -0
  48. package/dest/types.js +11 -0
  49. package/package.json +22 -13
  50. package/src/base-wallet/base_wallet.ts +242 -60
  51. package/src/base-wallet/index.ts +2 -1
  52. package/src/base-wallet/utils.ts +238 -0
  53. package/src/crypto.ts +499 -0
  54. package/src/emoji_alphabet.ts +317 -0
  55. package/src/extension/handlers/background_connection_handler.ts +423 -0
  56. package/src/extension/handlers/content_script_connection_handler.ts +246 -0
  57. package/src/extension/handlers/index.ts +25 -0
  58. package/src/extension/handlers/internal_message_types.ts +69 -0
  59. package/src/extension/provider/extension_provider.ts +233 -0
  60. package/src/extension/provider/extension_wallet.ts +329 -0
  61. package/src/extension/provider/index.ts +7 -0
  62. package/src/manager/index.ts +3 -15
  63. package/src/manager/types.ts +112 -4
  64. package/src/manager/wallet_manager.ts +202 -31
  65. package/src/types.ts +132 -0
  66. package/dest/providers/extension/extension_provider.d.ts +0 -17
  67. package/dest/providers/extension/extension_provider.d.ts.map +0 -1
  68. package/dest/providers/extension/extension_provider.js +0 -56
  69. package/dest/providers/extension/extension_wallet.d.ts +0 -23
  70. package/dest/providers/extension/extension_wallet.d.ts.map +0 -1
  71. package/dest/providers/extension/extension_wallet.js +0 -96
  72. package/dest/providers/extension/index.d.ts +0 -4
  73. package/dest/providers/extension/index.d.ts.map +0 -1
  74. package/dest/providers/types.d.ts +0 -67
  75. package/dest/providers/types.d.ts.map +0 -1
  76. package/dest/providers/types.js +0 -3
  77. package/src/providers/extension/extension_provider.ts +0 -72
  78. package/src/providers/extension/extension_wallet.ts +0 -124
  79. package/src/providers/extension/index.ts +0 -3
  80. package/src/providers/types.ts +0 -71
  81. /package/dest/{providers/extension → extension/provider}/index.js +0 -0
@@ -1,15 +1,26 @@
1
1
  import type { Account } from '@aztec/aztec.js/account';
2
2
  import type { CallIntent, IntentInnerHash } from '@aztec/aztec.js/authorization';
3
+ import {
4
+ type InteractionWaitOptions,
5
+ NO_WAIT,
6
+ type SendReturn,
7
+ extractOffchainOutput,
8
+ } from '@aztec/aztec.js/contracts';
3
9
  import type { FeePaymentMethod } from '@aztec/aztec.js/fee';
10
+ import { waitForTx } from '@aztec/aztec.js/node';
4
11
  import type {
5
12
  Aliased,
13
+ AppCapabilities,
6
14
  BatchResults,
7
- BatchableMethods,
8
15
  BatchedMethod,
16
+ ExecuteUtilityOptions,
17
+ PrivateEvent,
18
+ PrivateEventFilter,
9
19
  ProfileOptions,
10
20
  SendOptions,
11
21
  SimulateOptions,
12
22
  Wallet,
23
+ WalletCapabilities,
13
24
  } from '@aztec/aztec.js/wallet';
14
25
  import {
15
26
  GAS_ESTIMATION_DA_GAS_LIMIT,
@@ -19,10 +30,11 @@ import {
19
30
  } from '@aztec/constants';
20
31
  import { AccountFeePaymentMethodOptions, type DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
21
32
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
22
- import { Fr } from '@aztec/foundation/fields';
33
+ import { Fr } from '@aztec/foundation/curves/bn254';
23
34
  import { createLogger } from '@aztec/foundation/log';
24
35
  import type { FieldsOf } from '@aztec/foundation/types';
25
- import type { PXE } from '@aztec/pxe/server';
36
+ import { type AccessScopes, displayDebugLogs } from '@aztec/pxe/client/lazy';
37
+ import type { PXE, PackedPrivateEvent } from '@aztec/pxe/server';
26
38
  import {
27
39
  type ContractArtifact,
28
40
  type EventMetadataDefinition,
@@ -30,29 +42,29 @@ import {
30
42
  decodeFromAbi,
31
43
  } from '@aztec/stdlib/abi';
32
44
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
33
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
45
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
34
46
  import {
35
- type ContractClassMetadata,
36
47
  type ContractInstanceWithAddress,
37
- type ContractMetadata,
38
48
  computePartialAddress,
39
49
  getContractClassFromArtifact,
40
50
  } from '@aztec/stdlib/contract';
41
51
  import { SimulationError } from '@aztec/stdlib/errors';
42
52
  import { Gas, GasSettings } from '@aztec/stdlib/gas';
53
+ import { computeSiloedPrivateInitializationNullifier } from '@aztec/stdlib/hash';
43
54
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
44
- import type {
45
- TxExecutionRequest,
46
- TxHash,
47
- TxProfileResult,
48
- TxReceipt,
55
+ import {
56
+ BlockHeader,
57
+ type TxExecutionRequest,
58
+ type TxProfileResult,
49
59
  TxSimulationResult,
50
- UtilitySimulationResult,
60
+ type UtilityExecutionResult,
51
61
  } from '@aztec/stdlib/tx';
52
62
  import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
53
63
 
54
64
  import { inspect } from 'util';
55
65
 
66
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
67
+
56
68
  /**
57
69
  * Options to configure fee payment for a transaction
58
70
  */
@@ -68,21 +80,36 @@ export type FeeOptions = {
68
80
  gasSettings: GasSettings;
69
81
  };
70
82
 
83
+ /** Options for `simulateViaEntrypoint`. */
84
+ export type SimulateViaEntrypointOptions = Pick<
85
+ SimulateOptions,
86
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement'
87
+ > & {
88
+ /** Fee options for the entrypoint */
89
+ feeOptions: FeeOptions;
90
+ /** Scopes to use for the simulation */
91
+ scopes: AccessScopes;
92
+ };
71
93
  /**
72
94
  * A base class for Wallet implementations
73
95
  */
74
96
  export abstract class BaseWallet implements Wallet {
75
- protected log = createLogger('wallet-sdk:base_wallet');
76
-
77
- protected baseFeePadding = 0.5;
97
+ protected minFeePadding = 0.5;
78
98
  protected cancellableTransactions = false;
79
99
 
80
100
  // Protected because we want to force wallets to instantiate their own PXE.
81
101
  protected constructor(
82
102
  protected readonly pxe: PXE,
83
103
  protected readonly aztecNode: AztecNode,
104
+ protected log = createLogger('wallet-sdk:base_wallet'),
84
105
  ) {}
85
106
 
107
+ protected scopesFrom(from: AztecAddress, additionalScopes: AztecAddress[] = []): AztecAddress[] {
108
+ const allScopes = from.isZero() ? additionalScopes : [from, ...additionalScopes];
109
+ const scopeSet = new Set(allScopes.map(address => address.toString()));
110
+ return [...scopeSet].map(AztecAddress.fromString);
111
+ }
112
+
86
113
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
87
114
 
88
115
  abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
@@ -119,20 +146,42 @@ export abstract class BaseWallet implements Wallet {
119
146
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
120
147
  : executionPayload;
121
148
  const fromAccount = await this.getAccountFromAddress(from);
122
- return fromAccount.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, executionOptions);
149
+ const chainInfo = await this.getChainInfo();
150
+ return fromAccount.createTxExecutionRequest(
151
+ finalExecutionPayload,
152
+ feeOptions.gasSettings,
153
+ chainInfo,
154
+ executionOptions,
155
+ );
123
156
  }
124
157
 
125
158
  public async createAuthWit(
126
159
  from: AztecAddress,
127
- messageHashOrIntent: Fr | IntentInnerHash | CallIntent,
160
+ messageHashOrIntent: IntentInnerHash | CallIntent,
128
161
  ): Promise<AuthWitness> {
129
162
  const account = await this.getAccountFromAddress(from);
130
- return account.createAuthWit(messageHashOrIntent);
163
+ const chainInfo = await this.getChainInfo();
164
+ return account.createAuthWit(messageHashOrIntent, chainInfo);
165
+ }
166
+
167
+ /**
168
+ * Request capabilities from the wallet.
169
+ *
170
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
171
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
172
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
173
+ * friction by allowing apps to request permissions upfront.
174
+ *
175
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
176
+ * while the feature stabilizes.
177
+ *
178
+ * @param _manifest - Application capability manifest declaring what operations the app needs
179
+ */
180
+ public requestCapabilities(_manifest: AppCapabilities): Promise<WalletCapabilities> {
181
+ throw new Error('Not implemented');
131
182
  }
132
183
 
133
- public async batch<const T extends readonly BatchedMethod<keyof BatchableMethods>[]>(
134
- methods: T,
135
- ): Promise<BatchResults<T>> {
184
+ public async batch<const T extends readonly BatchedMethod[]>(methods: T): Promise<BatchResults<T>> {
136
185
  const results: any[] = [];
137
186
  for (const method of methods) {
138
187
  const { name, args } = method;
@@ -163,7 +212,7 @@ export abstract class BaseWallet implements Wallet {
163
212
  gasSettings?: Partial<FieldsOf<GasSettings>>,
164
213
  ): Promise<FeeOptions> {
165
214
  const maxFeesPerGas =
166
- gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentBaseFees()).mul(1 + this.baseFeePadding);
215
+ gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
167
216
  let accountFeePaymentMethodOptions;
168
217
  // The transaction does not include a fee payment method, so we set the flag
169
218
  // for the account to use its fee juice balance
@@ -225,7 +274,7 @@ export abstract class BaseWallet implements Wallet {
225
274
  artifact?: ContractArtifact,
226
275
  secretKey?: Fr,
227
276
  ): Promise<ContractInstanceWithAddress> {
228
- const { contractInstance: existingInstance } = await this.pxe.getContractMetadata(instance.address);
277
+ const existingInstance = await this.pxe.getContractInstance(instance.address);
229
278
 
230
279
  if (existingInstance) {
231
280
  // Instance already registered in the wallet
@@ -242,13 +291,12 @@ export abstract class BaseWallet implements Wallet {
242
291
  // Instance not registered yet
243
292
  if (!artifact) {
244
293
  // Try to get the artifact from the wallet's contract class storage
245
- const classMetadata = await this.pxe.getContractClassMetadata(instance.currentContractClassId, true);
246
- if (!classMetadata.artifact) {
294
+ artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
295
+ if (!artifact) {
247
296
  throw new Error(
248
297
  `Cannot register contract at ${instance.address.toString()}: artifact is required but not provided, and wallet does not have the artifact for contract class ${instance.currentContractClassId.toString()}`,
249
298
  );
250
299
  }
251
- artifact = classMetadata.artifact;
252
300
  }
253
301
  await this.pxe.registerContract({ artifact, instance });
254
302
  }
@@ -259,29 +307,98 @@ export abstract class BaseWallet implements Wallet {
259
307
  return instance;
260
308
  }
261
309
 
310
+ /**
311
+ * Simulates calls through the standard PXE path (account entrypoint).
312
+ * @param executionPayload - The execution payload to simulate.
313
+ * @param opts - Simulation options.
314
+ */
315
+ protected async simulateViaEntrypoint(executionPayload: ExecutionPayload, opts: SimulateViaEntrypointOptions) {
316
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(
317
+ executionPayload,
318
+ opts.from,
319
+ opts.feeOptions,
320
+ );
321
+ return this.pxe.simulateTx(txRequest, {
322
+ simulatePublic: true,
323
+ skipTxValidation: opts.skipTxValidation,
324
+ skipFeeEnforcement: opts.skipFeeEnforcement,
325
+ scopes: opts.scopes,
326
+ });
327
+ }
328
+
329
+ /**
330
+ * Simulates a transaction, optimizing leading public static calls by running them directly
331
+ * on the node while sending the remaining calls through the standard PXE path.
332
+ * Return values from both paths are merged back in original call order.
333
+ * @param executionPayload - The execution payload to simulate.
334
+ * @param opts - Simulation options (from address, fee settings, etc.).
335
+ * @returns The merged simulation result.
336
+ */
262
337
  async simulateTx(executionPayload: ExecutionPayload, opts: SimulateOptions): Promise<TxSimulationResult> {
263
338
  const feeOptions = opts.fee?.estimateGas
264
339
  ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings)
265
340
  : await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
266
- const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
267
- return this.pxe.simulateTx(
268
- txRequest,
269
- true /* simulatePublic */,
270
- opts?.skipTxValidation,
271
- opts?.skipFeeEnforcement ?? true,
272
- );
341
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
342
+ const remainingPayload = { ...executionPayload, calls: remainingCalls };
343
+
344
+ const chainInfo = await this.getChainInfo();
345
+ let blockHeader: BlockHeader;
346
+ // PXE might not be synced yet, so we pull the latest header from the node
347
+ // To keep things consistent, we'll always try with PXE first
348
+ try {
349
+ blockHeader = await this.pxe.getSyncedBlockHeader();
350
+ } catch {
351
+ blockHeader = (await this.aztecNode.getBlockHeader())!;
352
+ }
353
+
354
+ const [optimizedResults, normalResult] = await Promise.all([
355
+ optimizableCalls.length > 0
356
+ ? simulateViaNode(
357
+ this.aztecNode,
358
+ optimizableCalls,
359
+ opts.from,
360
+ chainInfo,
361
+ feeOptions.gasSettings,
362
+ blockHeader,
363
+ opts.skipFeeEnforcement ?? true,
364
+ this.getContractName.bind(this),
365
+ )
366
+ : Promise.resolve([]),
367
+ remainingCalls.length > 0
368
+ ? this.simulateViaEntrypoint(remainingPayload, {
369
+ from: opts.from,
370
+ feeOptions,
371
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
372
+ skipTxValidation: opts.skipTxValidation,
373
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
374
+ })
375
+ : Promise.resolve(null),
376
+ ]);
377
+
378
+ return buildMergedSimulationResult(optimizedResults, normalResult);
273
379
  }
274
380
 
275
381
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
276
382
  const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
277
383
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
278
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
384
+ return this.pxe.profileTx(txRequest, {
385
+ profileMode: opts.profileMode,
386
+ skipProofGeneration: opts.skipProofGeneration ?? true,
387
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
388
+ });
279
389
  }
280
390
 
281
- async sendTx(executionPayload: ExecutionPayload, opts: SendOptions): Promise<TxHash> {
391
+ public async sendTx<W extends InteractionWaitOptions = undefined>(
392
+ executionPayload: ExecutionPayload,
393
+ opts: SendOptions<W>,
394
+ ): Promise<SendReturn<W>> {
282
395
  const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
283
396
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
284
- const provenTx = await this.pxe.proveTx(txRequest);
397
+ const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
398
+ const offchainOutput = extractOffchainOutput(
399
+ provenTx.getOffchainEffects(),
400
+ provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
401
+ );
285
402
  const tx = await provenTx.toTx();
286
403
  const txHash = tx.getTxHash();
287
404
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -292,7 +409,35 @@ export abstract class BaseWallet implements Wallet {
292
409
  throw this.contextualizeError(err, inspect(tx));
293
410
  });
294
411
  this.log.info(`Sent transaction ${txHash}`);
295
- return txHash;
412
+
413
+ // If wait is NO_WAIT, return txHash immediately
414
+ if (opts.wait === NO_WAIT) {
415
+ return { txHash, ...offchainOutput } as SendReturn<W>;
416
+ }
417
+
418
+ // Otherwise, wait for the full receipt (default behavior on wait: undefined)
419
+ const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
420
+ const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
421
+
422
+ // Display debug logs from public execution if present (served in test mode only)
423
+ if (receipt.debugLogs?.length) {
424
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
425
+ }
426
+
427
+ return { receipt, ...offchainOutput } as SendReturn<W>;
428
+ }
429
+
430
+ /**
431
+ * Resolves a contract address to a human-readable name via PXE, if available.
432
+ * @param address - The contract address to resolve.
433
+ */
434
+ protected async getContractName(address: AztecAddress): Promise<string | undefined> {
435
+ const instance = await this.pxe.getContractInstance(address);
436
+ if (!instance) {
437
+ return undefined;
438
+ }
439
+ const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
440
+ return artifact?.name;
296
441
  }
297
442
 
298
443
  protected contextualizeError(err: Error, ...context: string[]): Error {
@@ -309,34 +454,71 @@ export abstract class BaseWallet implements Wallet {
309
454
  return err;
310
455
  }
311
456
 
312
- simulateUtility(call: FunctionCall, authwits?: AuthWitness[]): Promise<UtilitySimulationResult> {
313
- return this.pxe.simulateUtility(call, authwits);
314
- }
315
-
316
- getContractClassMetadata(id: Fr, includeArtifact: boolean = false): Promise<ContractClassMetadata> {
317
- return this.pxe.getContractClassMetadata(id, includeArtifact);
318
- }
319
- getContractMetadata(address: AztecAddress): Promise<ContractMetadata> {
320
- return this.pxe.getContractMetadata(address);
321
- }
322
-
323
- getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
324
- return this.aztecNode.getTxReceipt(txHash);
457
+ executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
458
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: [opts.scope] });
325
459
  }
326
460
 
327
461
  async getPrivateEvents<T>(
328
- contractAddress: AztecAddress,
329
462
  eventDef: EventMetadataDefinition,
330
- from: number,
331
- limit: number,
332
- recipients: AztecAddress[] = [],
333
- ): Promise<T[]> {
334
- const events = await this.pxe.getPrivateEvents(contractAddress, eventDef.eventSelector, from, limit, recipients);
335
-
336
- const decodedEvents = events.map(
337
- (event: any /** PrivateEvent */): T => decodeFromAbi([eventDef.abiType], event.packedEvent) as T,
338
- );
463
+ eventFilter: PrivateEventFilter,
464
+ ): Promise<PrivateEvent<T>[]> {
465
+ const pxeEvents = await this.pxe.getPrivateEvents(eventDef.eventSelector, eventFilter);
466
+
467
+ const decodedEvents = pxeEvents.map((pxeEvent: PackedPrivateEvent): PrivateEvent<T> => {
468
+ return {
469
+ event: decodeFromAbi([eventDef.abiType], pxeEvent.packedEvent) as T,
470
+ metadata: {
471
+ l2BlockNumber: pxeEvent.l2BlockNumber,
472
+ l2BlockHash: pxeEvent.l2BlockHash,
473
+ txHash: pxeEvent.txHash,
474
+ },
475
+ };
476
+ });
339
477
 
340
478
  return decodedEvents;
341
479
  }
480
+
481
+ /**
482
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
483
+ *
484
+ * `isContractInitialized` requires the contract instance to be registered in the PXE (for `init_hash`). When the
485
+ * instance is not available, `isContractInitialized` is `undefined` since it cannot be determined.
486
+ * @param address - The contract address to query.
487
+ */
488
+ async getContractMetadata(address: AztecAddress) {
489
+ const instance = await this.pxe.getContractInstance(address);
490
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
491
+ // We check only the private initialization nullifier. It is emitted by both private and public initializers and
492
+ // includes init_hash, preventing observers from determining initialization status from the address alone. Without
493
+ // the instance (and thus init_hash), we can't compute it, so we return undefined.
494
+ //
495
+ // We skip the public initialization nullifier because it's not always emitted (contracts without public external
496
+ // functions that require initialization checks won't emit it). If the private one exists, the public one was
497
+ // created in the same tx and will also be present.
498
+ let isContractInitialized: boolean | undefined = undefined;
499
+ if (instance) {
500
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
501
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
502
+ isContractInitialized = !!witness;
503
+ }
504
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
505
+ const isContractUpdated =
506
+ publiclyRegisteredContract &&
507
+ !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
508
+ return {
509
+ instance: instance ?? undefined,
510
+ isContractInitialized,
511
+ isContractPublished: !!publiclyRegisteredContract,
512
+ isContractUpdated: !!isContractUpdated,
513
+ updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined,
514
+ };
515
+ }
516
+
517
+ async getContractClassMetadata(id: Fr) {
518
+ const publiclyRegisteredContractClass = await this.aztecNode.getContractClass(id);
519
+ return {
520
+ isArtifactRegistered: !!(await this.pxe.getContractArtifact(id)),
521
+ isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass,
522
+ };
523
+ }
342
524
  }
@@ -1 +1,2 @@
1
- export { BaseWallet, type FeeOptions } from './base_wallet.js';
1
+ export { BaseWallet, type FeeOptions, type SimulateViaEntrypointOptions } from './base_wallet.js';
2
+ export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';
@@ -0,0 +1,238 @@
1
+ import type { AztecNode } from '@aztec/aztec.js/node';
2
+ import { MAX_ENQUEUED_CALLS_PER_CALL } from '@aztec/constants';
3
+ import type { ChainInfo } from '@aztec/entrypoints/interfaces';
4
+ import { makeTuple } from '@aztec/foundation/array';
5
+ import { Fr } from '@aztec/foundation/curves/bn254';
6
+ import type { Tuple } from '@aztec/foundation/serialize';
7
+ import type { ContractNameResolver } from '@aztec/pxe/client/lazy';
8
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
9
+ import { generateSimulatedProvingResult } from '@aztec/pxe/simulator';
10
+ import { type FunctionCall, FunctionSelector } from '@aztec/stdlib/abi';
11
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
12
+ import type { GasSettings } from '@aztec/stdlib/gas';
13
+ import {
14
+ ClaimedLengthArray,
15
+ CountedPublicCallRequest,
16
+ PrivateCircuitPublicInputs,
17
+ PublicCallRequest,
18
+ } from '@aztec/stdlib/kernel';
19
+ import { ChonkProof } from '@aztec/stdlib/proofs';
20
+ import {
21
+ type BlockHeader,
22
+ type ExecutionPayload,
23
+ HashedValues,
24
+ PrivateCallExecutionResult,
25
+ PrivateExecutionResult,
26
+ PublicSimulationOutput,
27
+ Tx,
28
+ TxContext,
29
+ TxSimulationResult,
30
+ } from '@aztec/stdlib/tx';
31
+
32
+ /**
33
+ * Splits an execution payload into a leading prefix of public static calls
34
+ * (eligible for direct node simulation) and the remaining calls.
35
+ *
36
+ * Only a leading run of public static calls is eligible for optimization.
37
+ * Any non-public-static call may enqueue public state mutations
38
+ * (e.g. private calls can enqueue public calls), so all calls that follow
39
+ * must go through the normal simulation path to see the correct state.
40
+ *
41
+ */
42
+ export function extractOptimizablePublicStaticCalls(payload: ExecutionPayload): {
43
+ /** Leading public static calls eligible for direct node simulation. */
44
+ optimizableCalls: FunctionCall[];
45
+ /** All remaining calls. */
46
+ remainingCalls: FunctionCall[];
47
+ } {
48
+ const splitIndex = payload.calls.findIndex(call => !call.isPublicStatic());
49
+ const boundary = splitIndex === -1 ? payload.calls.length : splitIndex;
50
+ return {
51
+ optimizableCalls: payload.calls.slice(0, boundary),
52
+ remainingCalls: payload.calls.slice(boundary),
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Simulates a batch of public static calls by bypassing account entrypoint and private execution,
58
+ * directly constructing a minimal Tx and calling node.simulatePublicCalls.
59
+ *
60
+ * @param node - The Aztec node to simulate on.
61
+ * @param publicStaticCalls - Array of public static function calls (max MAX_ENQUEUED_CALLS_PER_CALL).
62
+ * @param from - The account address making the calls.
63
+ * @param chainInfo - Chain information (chainId and version).
64
+ * @param gasSettings - Gas settings for the transaction.
65
+ * @param blockHeader - Block header to use as anchor.
66
+ * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
67
+ * @returns TxSimulationResult with public return values.
68
+ */
69
+ async function simulateBatchViaNode(
70
+ node: AztecNode,
71
+ publicStaticCalls: FunctionCall[],
72
+ from: AztecAddress,
73
+ chainInfo: ChainInfo,
74
+ gasSettings: GasSettings,
75
+ blockHeader: BlockHeader,
76
+ skipFeeEnforcement: boolean,
77
+ getContractName: ContractNameResolver,
78
+ ): Promise<TxSimulationResult> {
79
+ const txContext = new TxContext(chainInfo.chainId, chainInfo.version, gasSettings);
80
+
81
+ const publicFunctionCalldata: HashedValues[] = [];
82
+ for (const call of publicStaticCalls) {
83
+ const calldata = await HashedValues.fromCalldata([call.selector.toField(), ...call.args]);
84
+ publicFunctionCalldata.push(calldata);
85
+ }
86
+
87
+ const publicCallRequests = makeTuple(MAX_ENQUEUED_CALLS_PER_CALL, i => {
88
+ const call = publicStaticCalls[i];
89
+ if (!call) {
90
+ return CountedPublicCallRequest.empty();
91
+ }
92
+ const publicCallRequest = new PublicCallRequest(from, call.to, call.isStatic, publicFunctionCalldata[i]!.hash);
93
+ // Counter starts at 1 (minRevertibleSideEffectCounter) so all calls are revertible
94
+ return new CountedPublicCallRequest(publicCallRequest, i + 1);
95
+ });
96
+
97
+ const publicCallRequestsArray: ClaimedLengthArray<CountedPublicCallRequest, typeof MAX_ENQUEUED_CALLS_PER_CALL> =
98
+ new ClaimedLengthArray(
99
+ publicCallRequests as Tuple<CountedPublicCallRequest, typeof MAX_ENQUEUED_CALLS_PER_CALL>,
100
+ publicStaticCalls.length,
101
+ );
102
+
103
+ const publicInputs = PrivateCircuitPublicInputs.from({
104
+ ...PrivateCircuitPublicInputs.empty(),
105
+ anchorBlockHeader: blockHeader,
106
+ txContext: txContext,
107
+ publicCallRequests: publicCallRequestsArray,
108
+ startSideEffectCounter: new Fr(0),
109
+ endSideEffectCounter: new Fr(publicStaticCalls.length + 1),
110
+ });
111
+
112
+ // Minimal entrypoint structure — no real private execution, just public call requests
113
+ const emptyEntrypoint = new PrivateCallExecutionResult(
114
+ Buffer.alloc(0),
115
+ Buffer.alloc(0),
116
+ new Map(),
117
+ publicInputs,
118
+ [],
119
+ new Map(),
120
+ [],
121
+ [],
122
+ [],
123
+ [],
124
+ [],
125
+ );
126
+
127
+ const privateResult = new PrivateExecutionResult(emptyEntrypoint, Fr.random(), publicFunctionCalldata);
128
+
129
+ const provingResult = await generateSimulatedProvingResult(
130
+ privateResult,
131
+ (_contractAddress: AztecAddress, _functionSelector: FunctionSelector) => Promise.resolve(''),
132
+ node,
133
+ 1, // minRevertibleSideEffectCounter
134
+ );
135
+
136
+ provingResult.publicInputs.feePayer = from;
137
+
138
+ const tx = await Tx.create({
139
+ data: provingResult.publicInputs,
140
+ chonkProof: ChonkProof.empty(),
141
+ contractClassLogFields: [],
142
+ publicFunctionCalldata: publicFunctionCalldata,
143
+ });
144
+
145
+ const publicOutput = await node.simulatePublicCalls(tx, skipFeeEnforcement);
146
+
147
+ if (publicOutput.revertReason) {
148
+ throw publicOutput.revertReason;
149
+ }
150
+
151
+ // Display debug logs from the public simulation.
152
+ await displayDebugLogs(publicOutput.debugLogs, getContractName);
153
+
154
+ return new TxSimulationResult(privateResult, provingResult.publicInputs, publicOutput, undefined);
155
+ }
156
+
157
+ /**
158
+ * Simulates public static calls by splitting them into batches of MAX_ENQUEUED_CALLS_PER_CALL
159
+ * and sending each batch directly to the node.
160
+ *
161
+ * @param node - The Aztec node to simulate on.
162
+ * @param publicStaticCalls - Array of public static function calls to optimize.
163
+ * @param from - The account address making the calls.
164
+ * @param chainInfo - Chain information (chainId and version).
165
+ * @param gasSettings - Gas settings for the transaction.
166
+ * @param blockHeader - Block header to use as anchor.
167
+ * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
168
+ * @returns Array of TxSimulationResult, one per batch.
169
+ */
170
+ export async function simulateViaNode(
171
+ node: AztecNode,
172
+ publicStaticCalls: FunctionCall[],
173
+ from: AztecAddress,
174
+ chainInfo: ChainInfo,
175
+ gasSettings: GasSettings,
176
+ blockHeader: BlockHeader,
177
+ skipFeeEnforcement: boolean = true,
178
+ getContractName: ContractNameResolver,
179
+ ): Promise<TxSimulationResult[]> {
180
+ const batches: FunctionCall[][] = [];
181
+
182
+ for (let i = 0; i < publicStaticCalls.length; i += MAX_ENQUEUED_CALLS_PER_CALL) {
183
+ batches.push(publicStaticCalls.slice(i, i + MAX_ENQUEUED_CALLS_PER_CALL));
184
+ }
185
+
186
+ const results: TxSimulationResult[] = [];
187
+
188
+ for (const batch of batches) {
189
+ const result = await simulateBatchViaNode(
190
+ node,
191
+ batch,
192
+ from,
193
+ chainInfo,
194
+ gasSettings,
195
+ blockHeader,
196
+ skipFeeEnforcement,
197
+ getContractName,
198
+ );
199
+ results.push(result);
200
+ }
201
+
202
+ return results;
203
+ }
204
+
205
+ /**
206
+ * Merges simulation results from the optimized (public static) and normal paths.
207
+ * Since optimized calls are always a leading prefix, return values are simply
208
+ * concatenated: optimized first, then normal.
209
+ * Stats are taken from the normal result only (the optimized path doesn't produce them).
210
+ *
211
+ * @param optimizedResults - Results from optimized public static call batches.
212
+ * @param normalResult - Result from normal simulation (null if all calls were optimized).
213
+ * @returns A single TxSimulationResult with return values in original call order.
214
+ */
215
+ export function buildMergedSimulationResult(
216
+ optimizedResults: TxSimulationResult[],
217
+ normalResult: TxSimulationResult | null,
218
+ ): TxSimulationResult {
219
+ const optimizedReturnValues = optimizedResults.flatMap(r => r.publicOutput?.publicReturnValues ?? []);
220
+ const normalReturnValues = normalResult?.publicOutput?.publicReturnValues ?? [];
221
+ const allReturnValues = [...optimizedReturnValues, ...normalReturnValues];
222
+
223
+ const baseResult = normalResult ?? optimizedResults[0];
224
+
225
+ const mergedPublicOutput: PublicSimulationOutput | undefined = baseResult.publicOutput
226
+ ? {
227
+ ...baseResult.publicOutput,
228
+ publicReturnValues: allReturnValues,
229
+ }
230
+ : undefined;
231
+
232
+ return new TxSimulationResult(
233
+ baseResult.privateExecutionResult,
234
+ baseResult.publicInputs,
235
+ mergedPublicOutput,
236
+ normalResult?.stats,
237
+ );
238
+ }