@aztec/wallet-sdk 0.0.1-commit.023c3e5 → 0.0.1-commit.03b9a845c

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.
@@ -1,20 +1,28 @@
1
- import type { Account } from '@aztec/aztec.js/account';
1
+ import type { Account, NoFrom } from '@aztec/aztec.js/account';
2
+ import { NO_FROM } from '@aztec/aztec.js/account';
2
3
  import type { CallIntent, IntentInnerHash } from '@aztec/aztec.js/authorization';
3
- import { type InteractionWaitOptions, NO_WAIT, type SendReturn } from '@aztec/aztec.js/contracts';
4
+ import {
5
+ type InteractionWaitOptions,
6
+ NO_WAIT,
7
+ type SendReturn,
8
+ extractOffchainOutput,
9
+ } from '@aztec/aztec.js/contracts';
4
10
  import type { FeePaymentMethod } from '@aztec/aztec.js/fee';
5
11
  import { waitForTx } from '@aztec/aztec.js/node';
6
- import type {
7
- Aliased,
8
- AppCapabilities,
9
- BatchResults,
10
- BatchedMethod,
11
- PrivateEvent,
12
- PrivateEventFilter,
13
- ProfileOptions,
14
- SendOptions,
15
- SimulateOptions,
16
- Wallet,
17
- WalletCapabilities,
12
+ import {
13
+ type Aliased,
14
+ type AppCapabilities,
15
+ type BatchResults,
16
+ type BatchedMethod,
17
+ ContractInitializationStatus,
18
+ type ExecuteUtilityOptions,
19
+ type PrivateEvent,
20
+ type PrivateEventFilter,
21
+ type ProfileOptions,
22
+ type SendOptions,
23
+ type SimulateOptions,
24
+ type Wallet,
25
+ type WalletCapabilities,
18
26
  } from '@aztec/aztec.js/wallet';
19
27
  import {
20
28
  GAS_ESTIMATION_DA_GAS_LIMIT,
@@ -23,10 +31,12 @@ import {
23
31
  GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT,
24
32
  } from '@aztec/constants';
25
33
  import { AccountFeePaymentMethodOptions, type DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
34
+ import { DefaultEntrypoint } from '@aztec/entrypoints/default';
26
35
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
27
36
  import { Fr } from '@aztec/foundation/curves/bn254';
28
37
  import { createLogger } from '@aztec/foundation/log';
29
38
  import type { FieldsOf } from '@aztec/foundation/types';
39
+ import { type AccessScopes, displayDebugLogs } from '@aztec/pxe/client/lazy';
30
40
  import type { PXE, PackedPrivateEvent } from '@aztec/pxe/server';
31
41
  import {
32
42
  type ContractArtifact,
@@ -35,7 +45,7 @@ import {
35
45
  decodeFromAbi,
36
46
  } from '@aztec/stdlib/abi';
37
47
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
38
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
48
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
39
49
  import {
40
50
  type ContractInstanceWithAddress,
41
51
  computePartialAddress,
@@ -43,18 +53,24 @@ import {
43
53
  } from '@aztec/stdlib/contract';
44
54
  import { SimulationError } from '@aztec/stdlib/errors';
45
55
  import { Gas, GasSettings } from '@aztec/stdlib/gas';
46
- import { siloNullifier } from '@aztec/stdlib/hash';
56
+ import {
57
+ computeSiloedPrivateInitializationNullifier,
58
+ computeSiloedPublicInitializationNullifier,
59
+ } from '@aztec/stdlib/hash';
47
60
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
48
- import type {
49
- TxExecutionRequest,
50
- TxProfileResult,
61
+ import {
62
+ BlockHeader,
63
+ type TxExecutionRequest,
64
+ type TxProfileResult,
51
65
  TxSimulationResult,
52
- UtilitySimulationResult,
66
+ type UtilityExecutionResult,
53
67
  } from '@aztec/stdlib/tx';
54
68
  import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
55
69
 
56
70
  import { inspect } from 'util';
57
71
 
72
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
73
+
58
74
  /**
59
75
  * Options to configure fee payment for a transaction
60
76
  */
@@ -65,17 +81,25 @@ export type FeeOptions = {
65
81
  */
66
82
  walletFeePaymentMethod?: FeePaymentMethod;
67
83
  /** Configuration options for the account to properly handle the selected fee payment method */
68
- accountFeePaymentMethodOptions: AccountFeePaymentMethodOptions;
84
+ accountFeePaymentMethodOptions?: AccountFeePaymentMethodOptions;
69
85
  /** The gas settings to use for the transaction */
70
86
  gasSettings: GasSettings;
71
87
  };
72
88
 
89
+ /** Options for `simulateViaEntrypoint`. */
90
+ export type SimulateViaEntrypointOptions = Pick<
91
+ SimulateOptions,
92
+ 'from' | 'additionalScopes' | 'skipTxValidation' | 'skipFeeEnforcement'
93
+ > & {
94
+ /** Fee options for the entrypoint */
95
+ feeOptions: FeeOptions;
96
+ /** Scopes to use for the simulation */
97
+ scopes: AccessScopes;
98
+ };
73
99
  /**
74
100
  * A base class for Wallet implementations
75
101
  */
76
102
  export abstract class BaseWallet implements Wallet {
77
- protected log = createLogger('wallet-sdk:base_wallet');
78
-
79
103
  protected minFeePadding = 0.5;
80
104
  protected cancellableTransactions = false;
81
105
 
@@ -83,8 +107,15 @@ export abstract class BaseWallet implements Wallet {
83
107
  protected constructor(
84
108
  protected readonly pxe: PXE,
85
109
  protected readonly aztecNode: AztecNode,
110
+ protected log = createLogger('wallet-sdk:base_wallet'),
86
111
  ) {}
87
112
 
113
+ protected scopesFrom(from: AztecAddress | NoFrom, additionalScopes: AztecAddress[] = []): AztecAddress[] {
114
+ const allScopes = from === NO_FROM ? additionalScopes : [from, ...additionalScopes];
115
+ const scopeSet = new Set(allScopes.map(address => address.toString()));
116
+ return [...scopeSet].map(AztecAddress.fromString);
117
+ }
118
+
88
119
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
89
120
 
90
121
  abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
@@ -108,26 +139,33 @@ export abstract class BaseWallet implements Wallet {
108
139
 
109
140
  protected async createTxExecutionRequestFromPayloadAndFee(
110
141
  executionPayload: ExecutionPayload,
111
- from: AztecAddress,
142
+ from: AztecAddress | NoFrom,
112
143
  feeOptions: FeeOptions,
113
144
  ): Promise<TxExecutionRequest> {
114
145
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
115
- const executionOptions: DefaultAccountEntrypointOptions = {
116
- txNonce: Fr.random(),
117
- cancellable: this.cancellableTransactions,
118
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
119
- };
120
146
  const finalExecutionPayload = feeExecutionPayload
121
147
  ? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
122
148
  : executionPayload;
123
- const fromAccount = await this.getAccountFromAddress(from);
124
149
  const chainInfo = await this.getChainInfo();
125
- return fromAccount.createTxExecutionRequest(
126
- finalExecutionPayload,
127
- feeOptions.gasSettings,
128
- chainInfo,
129
- executionOptions,
130
- );
150
+
151
+ if (from === NO_FROM) {
152
+ const entrypoint = new DefaultEntrypoint();
153
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
154
+ } else {
155
+ const fromAccount = await this.getAccountFromAddress(from);
156
+ const executionOptions: DefaultAccountEntrypointOptions = {
157
+ txNonce: Fr.random(),
158
+ cancellable: this.cancellableTransactions,
159
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
160
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions!,
161
+ };
162
+ return fromAccount.createTxExecutionRequest(
163
+ finalExecutionPayload,
164
+ feeOptions.gasSettings,
165
+ chainInfo,
166
+ executionOptions,
167
+ );
168
+ }
131
169
  }
132
170
 
133
171
  public async createAuthWit(
@@ -182,23 +220,27 @@ export abstract class BaseWallet implements Wallet {
182
220
  * @returns - Complete fee options that can be used to create a transaction execution request
183
221
  */
184
222
  protected async completeFeeOptions(
185
- from: AztecAddress,
223
+ from: AztecAddress | NoFrom,
186
224
  feePayer?: AztecAddress,
187
225
  gasSettings?: Partial<FieldsOf<GasSettings>>,
188
226
  ): Promise<FeeOptions> {
189
227
  const maxFeesPerGas =
190
228
  gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
191
229
  let accountFeePaymentMethodOptions;
192
- // The transaction does not include a fee payment method, so we set the flag
193
- // for the account to use its fee juice balance
194
- if (!feePayer) {
195
- accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
196
- } else {
197
- // The transaction includes fee payment method, so we check if we are the fee payer for it
198
- // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
199
- accountFeePaymentMethodOptions = from.equals(feePayer)
200
- ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
201
- : AccountFeePaymentMethodOptions.EXTERNAL;
230
+ // If from is an address, we need to determine the appropriate fee payment method options for the
231
+ // account contract entrypoint to use
232
+ if (from !== NO_FROM) {
233
+ if (!feePayer) {
234
+ // The transaction does not include a fee payment method, so we set the flag
235
+ // for the account to use its fee juice balance
236
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
237
+ } else {
238
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
239
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
240
+ accountFeePaymentMethodOptions = from.equals(feePayer)
241
+ ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM
242
+ : AccountFeePaymentMethodOptions.EXTERNAL;
243
+ }
202
244
  }
203
245
  const fullGasSettings: GasSettings = GasSettings.default({ ...gasSettings, maxFeesPerGas });
204
246
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
@@ -218,7 +260,7 @@ export abstract class BaseWallet implements Wallet {
218
260
  * @param gasSettings - User-provided partial gas settings
219
261
  */
220
262
  protected async completeFeeOptionsForEstimation(
221
- from: AztecAddress,
263
+ from: AztecAddress | NoFrom,
222
264
  feePayer?: AztecAddress,
223
265
  gasSettings?: Partial<FieldsOf<GasSettings>>,
224
266
  ) {
@@ -282,23 +324,86 @@ export abstract class BaseWallet implements Wallet {
282
324
  return instance;
283
325
  }
284
326
 
327
+ /**
328
+ * Simulates calls through the standard PXE path (account entrypoint).
329
+ * @param executionPayload - The execution payload to simulate.
330
+ * @param opts - Simulation options.
331
+ */
332
+ protected async simulateViaEntrypoint(executionPayload: ExecutionPayload, opts: SimulateViaEntrypointOptions) {
333
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(
334
+ executionPayload,
335
+ opts.from,
336
+ opts.feeOptions,
337
+ );
338
+ return this.pxe.simulateTx(txRequest, {
339
+ simulatePublic: true,
340
+ skipTxValidation: opts.skipTxValidation,
341
+ skipFeeEnforcement: opts.skipFeeEnforcement,
342
+ scopes: opts.scopes,
343
+ });
344
+ }
345
+
346
+ /**
347
+ * Simulates a transaction, optimizing leading public static calls by running them directly
348
+ * on the node while sending the remaining calls through the standard PXE path.
349
+ * Return values from both paths are merged back in original call order.
350
+ * @param executionPayload - The execution payload to simulate.
351
+ * @param opts - Simulation options (from address, fee settings, etc.).
352
+ * @returns The merged simulation result.
353
+ */
285
354
  async simulateTx(executionPayload: ExecutionPayload, opts: SimulateOptions): Promise<TxSimulationResult> {
286
355
  const feeOptions = opts.fee?.estimateGas
287
356
  ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings)
288
357
  : await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
289
- const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
290
- return this.pxe.simulateTx(
291
- txRequest,
292
- true /* simulatePublic */,
293
- opts?.skipTxValidation,
294
- opts?.skipFeeEnforcement ?? true,
295
- );
358
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
359
+ const remainingPayload = { ...executionPayload, calls: remainingCalls };
360
+
361
+ const chainInfo = await this.getChainInfo();
362
+ let blockHeader: BlockHeader;
363
+ // PXE might not be synced yet, so we pull the latest header from the node
364
+ // To keep things consistent, we'll always try with PXE first
365
+ try {
366
+ blockHeader = await this.pxe.getSyncedBlockHeader();
367
+ } catch {
368
+ blockHeader = (await this.aztecNode.getBlockHeader())!;
369
+ }
370
+
371
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
372
+ const [optimizedResults, normalResult] = await Promise.all([
373
+ optimizableCalls.length > 0
374
+ ? simulateViaNode(
375
+ this.aztecNode,
376
+ optimizableCalls,
377
+ simulationOrigin,
378
+ chainInfo,
379
+ feeOptions.gasSettings,
380
+ blockHeader,
381
+ opts.skipFeeEnforcement ?? true,
382
+ this.getContractName.bind(this),
383
+ )
384
+ : Promise.resolve([]),
385
+ remainingCalls.length > 0
386
+ ? this.simulateViaEntrypoint(remainingPayload, {
387
+ from: opts.from,
388
+ feeOptions,
389
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
390
+ skipTxValidation: opts.skipTxValidation,
391
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true,
392
+ })
393
+ : Promise.resolve(null),
394
+ ]);
395
+
396
+ return buildMergedSimulationResult(optimizedResults, normalResult);
296
397
  }
297
398
 
298
399
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
299
400
  const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
300
401
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
301
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
402
+ return this.pxe.profileTx(txRequest, {
403
+ profileMode: opts.profileMode,
404
+ skipProofGeneration: opts.skipProofGeneration ?? true,
405
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes),
406
+ });
302
407
  }
303
408
 
304
409
  public async sendTx<W extends InteractionWaitOptions = undefined>(
@@ -307,7 +412,11 @@ export abstract class BaseWallet implements Wallet {
307
412
  ): Promise<SendReturn<W>> {
308
413
  const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
309
414
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
310
- const provenTx = await this.pxe.proveTx(txRequest);
415
+ const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
416
+ const offchainOutput = extractOffchainOutput(
417
+ provenTx.getOffchainEffects(),
418
+ provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp,
419
+ );
311
420
  const tx = await provenTx.toTx();
312
421
  const txHash = tx.getTxHash();
313
422
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -321,12 +430,32 @@ export abstract class BaseWallet implements Wallet {
321
430
 
322
431
  // If wait is NO_WAIT, return txHash immediately
323
432
  if (opts.wait === NO_WAIT) {
324
- return txHash as SendReturn<W>;
433
+ return { txHash, ...offchainOutput } as SendReturn<W>;
325
434
  }
326
435
 
327
436
  // Otherwise, wait for the full receipt (default behavior on wait: undefined)
328
437
  const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
329
- return (await waitForTx(this.aztecNode, txHash, waitOpts)) as SendReturn<W>;
438
+ const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
439
+
440
+ // Display debug logs from public execution if present (served in test mode only)
441
+ if (receipt.debugLogs?.length) {
442
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
443
+ }
444
+
445
+ return { receipt, ...offchainOutput } as SendReturn<W>;
446
+ }
447
+
448
+ /**
449
+ * Resolves a contract address to a human-readable name via PXE, if available.
450
+ * @param address - The contract address to resolve.
451
+ */
452
+ protected async getContractName(address: AztecAddress): Promise<string | undefined> {
453
+ const instance = await this.pxe.getContractInstance(address);
454
+ if (!instance) {
455
+ return undefined;
456
+ }
457
+ const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
458
+ return artifact?.name;
330
459
  }
331
460
 
332
461
  protected contextualizeError(err: Error, ...context: string[]): Error {
@@ -343,8 +472,8 @@ export abstract class BaseWallet implements Wallet {
343
472
  return err;
344
473
  }
345
474
 
346
- simulateUtility(call: FunctionCall, authwits?: AuthWitness[]): Promise<UtilitySimulationResult> {
347
- return this.pxe.simulateUtility(call, authwits);
475
+ executeUtility(call: FunctionCall, opts: ExecuteUtilityOptions): Promise<UtilityExecutionResult> {
476
+ return this.pxe.executeUtility(call, { authwits: opts.authWitnesses, scopes: opts.scopes });
348
477
  }
349
478
 
350
479
  async getPrivateEvents<T>(
@@ -367,17 +496,39 @@ export abstract class BaseWallet implements Wallet {
367
496
  return decodedEvents;
368
497
  }
369
498
 
499
+ /**
500
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
501
+ * @param address - The contract address to query.
502
+ */
370
503
  async getContractMetadata(address: AztecAddress) {
371
504
  const instance = await this.pxe.getContractInstance(address);
372
- const initNullifier = await siloNullifier(address, address.toField());
373
- const publiclyRegisteredContract = await this.aztecNode.getContract(address);
374
- const initNullifierMembershipWitness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
505
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
506
+
507
+ let initializationStatus: ContractInitializationStatus;
508
+ if (instance) {
509
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
510
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
511
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
512
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
513
+ initializationStatus = witness
514
+ ? ContractInitializationStatus.INITIALIZED
515
+ : ContractInitializationStatus.UNINITIALIZED;
516
+ } else {
517
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
518
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
519
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
520
+ // uninitialized.
521
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
522
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
523
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
524
+ }
525
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
375
526
  const isContractUpdated =
376
527
  publiclyRegisteredContract &&
377
528
  !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
378
529
  return {
379
530
  instance: instance ?? undefined,
380
- isContractInitialized: !!initNullifierMembershipWitness,
531
+ initializationStatus,
381
532
  isContractPublished: !!publiclyRegisteredContract,
382
533
  isContractUpdated: !!isContractUpdated,
383
534
  updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined,
@@ -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
+ }