@aztec/wallet-sdk 0.0.1-commit.d431d1c → 0.0.1-commit.e2b2873ed

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 (75) hide show
  1. package/README.md +217 -294
  2. package/dest/base-wallet/base_wallet.d.ts +40 -8
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +92 -18
  5. package/dest/base-wallet/index.d.ts +2 -1
  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 +48 -0
  9. package/dest/base-wallet/utils.d.ts.map +1 -0
  10. package/dest/base-wallet/utils.js +128 -0
  11. package/dest/crypto.d.ts +59 -50
  12. package/dest/crypto.d.ts.map +1 -1
  13. package/dest/crypto.js +202 -108
  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 +131 -0
  33. package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
  34. package/dest/{providers/extension → extension/provider}/extension_wallet.js +48 -95
  35. package/dest/extension/provider/index.d.ts +3 -0
  36. package/dest/extension/provider/index.d.ts.map +1 -0
  37. package/dest/{providers/extension → extension/provider}/index.js +0 -2
  38. package/dest/manager/index.d.ts +2 -8
  39. package/dest/manager/index.d.ts.map +1 -1
  40. package/dest/manager/index.js +0 -6
  41. package/dest/manager/types.d.ts +88 -6
  42. package/dest/manager/types.d.ts.map +1 -1
  43. package/dest/manager/types.js +17 -1
  44. package/dest/manager/wallet_manager.d.ts +50 -7
  45. package/dest/manager/wallet_manager.d.ts.map +1 -1
  46. package/dest/manager/wallet_manager.js +174 -44
  47. package/dest/types.d.ts +43 -12
  48. package/dest/types.d.ts.map +1 -1
  49. package/dest/types.js +3 -2
  50. package/package.json +17 -10
  51. package/src/base-wallet/base_wallet.ts +125 -34
  52. package/src/base-wallet/index.ts +1 -0
  53. package/src/base-wallet/utils.ts +229 -0
  54. package/src/crypto.ts +237 -113
  55. package/src/emoji_alphabet.ts +317 -0
  56. package/src/extension/handlers/background_connection_handler.ts +423 -0
  57. package/src/extension/handlers/content_script_connection_handler.ts +246 -0
  58. package/src/extension/handlers/index.ts +25 -0
  59. package/src/extension/handlers/internal_message_types.ts +69 -0
  60. package/src/extension/provider/extension_provider.ts +233 -0
  61. package/src/{providers/extension → extension/provider}/extension_wallet.ts +52 -110
  62. package/src/extension/provider/index.ts +7 -0
  63. package/src/manager/index.ts +2 -10
  64. package/src/manager/types.ts +91 -5
  65. package/src/manager/wallet_manager.ts +192 -46
  66. package/src/types.ts +44 -10
  67. package/dest/providers/extension/extension_provider.d.ts +0 -63
  68. package/dest/providers/extension/extension_provider.d.ts.map +0 -1
  69. package/dest/providers/extension/extension_provider.js +0 -124
  70. package/dest/providers/extension/extension_wallet.d.ts +0 -155
  71. package/dest/providers/extension/extension_wallet.d.ts.map +0 -1
  72. package/dest/providers/extension/index.d.ts +0 -6
  73. package/dest/providers/extension/index.d.ts.map +0 -1
  74. package/src/providers/extension/extension_provider.ts +0 -167
  75. package/src/providers/extension/index.ts +0 -5
package/package.json CHANGED
@@ -1,19 +1,26 @@
1
1
  {
2
2
  "name": "@aztec/wallet-sdk",
3
3
  "homepage": "https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/wallet-sdk",
4
- "version": "0.0.1-commit.d431d1c",
4
+ "version": "0.0.1-commit.e2b2873ed",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  "./base-wallet": "./dest/base-wallet/index.js",
8
- "./providers/extension": "./dest/providers/extension/index.js",
8
+ "./extension/handlers": "./dest/extension/handlers/index.js",
9
+ "./extension/provider": "./dest/extension/provider/index.js",
9
10
  "./crypto": "./dest/crypto.js",
10
11
  "./types": "./dest/types.js",
11
12
  "./manager": "./dest/manager/index.js"
12
13
  },
13
14
  "typedocOptions": {
14
15
  "entryPoints": [
15
- "./src/index.ts"
16
+ "./src/base-wallet/index.ts",
17
+ "./src/extension/handlers/index.ts",
18
+ "./src/extension/provider/index.ts",
19
+ "./src/crypto.ts",
20
+ "./src/types.ts",
21
+ "./src/manager/index.ts"
16
22
  ],
23
+ "name": "Wallet SDK",
17
24
  "tsconfig": "./tsconfig.json"
18
25
  },
19
26
  "scripts": {
@@ -64,15 +71,15 @@
64
71
  ]
65
72
  },
66
73
  "dependencies": {
67
- "@aztec/aztec.js": "0.0.1-commit.d431d1c",
68
- "@aztec/constants": "0.0.1-commit.d431d1c",
69
- "@aztec/entrypoints": "0.0.1-commit.d431d1c",
70
- "@aztec/foundation": "0.0.1-commit.d431d1c",
71
- "@aztec/pxe": "0.0.1-commit.d431d1c",
72
- "@aztec/stdlib": "0.0.1-commit.d431d1c"
74
+ "@aztec/aztec.js": "0.0.1-commit.e2b2873ed",
75
+ "@aztec/constants": "0.0.1-commit.e2b2873ed",
76
+ "@aztec/entrypoints": "0.0.1-commit.e2b2873ed",
77
+ "@aztec/foundation": "0.0.1-commit.e2b2873ed",
78
+ "@aztec/pxe": "0.0.1-commit.e2b2873ed",
79
+ "@aztec/stdlib": "0.0.1-commit.e2b2873ed"
73
80
  },
74
81
  "devDependencies": {
75
- "@aztec/noir-contracts.js": "0.0.1-commit.d431d1c",
82
+ "@aztec/noir-contracts.js": "0.0.1-commit.e2b2873ed",
76
83
  "@jest/globals": "^30.0.0",
77
84
  "@types/jest": "^30.0.0",
78
85
  "@types/node": "^22.15.17",
@@ -1,8 +1,11 @@
1
1
  import type { Account } from '@aztec/aztec.js/account';
2
2
  import type { CallIntent, IntentInnerHash } from '@aztec/aztec.js/authorization';
3
+ import { type InteractionWaitOptions, NO_WAIT, type SendReturn } from '@aztec/aztec.js/contracts';
3
4
  import type { FeePaymentMethod } from '@aztec/aztec.js/fee';
5
+ import { waitForTx } from '@aztec/aztec.js/node';
4
6
  import type {
5
7
  Aliased,
8
+ AppCapabilities,
6
9
  BatchResults,
7
10
  BatchedMethod,
8
11
  PrivateEvent,
@@ -10,7 +13,9 @@ import type {
10
13
  ProfileOptions,
11
14
  SendOptions,
12
15
  SimulateOptions,
16
+ SimulateUtilityOptions,
13
17
  Wallet,
18
+ WalletCapabilities,
14
19
  } from '@aztec/aztec.js/wallet';
15
20
  import {
16
21
  GAS_ESTIMATION_DA_GAS_LIMIT,
@@ -41,18 +46,19 @@ import { SimulationError } from '@aztec/stdlib/errors';
41
46
  import { Gas, GasSettings } from '@aztec/stdlib/gas';
42
47
  import { siloNullifier } from '@aztec/stdlib/hash';
43
48
  import type { AztecNode } from '@aztec/stdlib/interfaces/client';
44
- import type {
45
- TxExecutionRequest,
46
- TxHash,
47
- TxProfileResult,
48
- TxReceipt,
49
+ import {
50
+ BlockHeader,
51
+ type TxExecutionRequest,
52
+ type TxProfileResult,
49
53
  TxSimulationResult,
50
- UtilitySimulationResult,
54
+ type UtilitySimulationResult,
51
55
  } from '@aztec/stdlib/tx';
52
56
  import { ExecutionPayload, mergeExecutionPayloads } from '@aztec/stdlib/tx';
53
57
 
54
58
  import { inspect } from 'util';
55
59
 
60
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
61
+
56
62
  /**
57
63
  * Options to configure fee payment for a transaction
58
64
  */
@@ -72,8 +78,6 @@ export type FeeOptions = {
72
78
  * A base class for Wallet implementations
73
79
  */
74
80
  export abstract class BaseWallet implements Wallet {
75
- protected log = createLogger('wallet-sdk:base_wallet');
76
-
77
81
  protected minFeePadding = 0.5;
78
82
  protected cancellableTransactions = false;
79
83
 
@@ -81,8 +85,15 @@ export abstract class BaseWallet implements Wallet {
81
85
  protected constructor(
82
86
  protected readonly pxe: PXE,
83
87
  protected readonly aztecNode: AztecNode,
88
+ protected log = createLogger('wallet-sdk:base_wallet'),
84
89
  ) {}
85
90
 
91
+ // When `from` is the zero address (e.g. when deploying a new account contract), we return an
92
+ // empty scope list which acts as deny-all: no notes are visible and no keys are accessible.
93
+ protected scopesFor(from: AztecAddress): AztecAddress[] {
94
+ return from.isZero() ? [] : [from];
95
+ }
96
+
86
97
  protected abstract getAccountFromAddress(address: AztecAddress): Promise<Account>;
87
98
 
88
99
  abstract getAccounts(): Promise<Aliased<AztecAddress>[]>;
@@ -137,6 +148,23 @@ export abstract class BaseWallet implements Wallet {
137
148
  return account.createAuthWit(messageHashOrIntent, chainInfo);
138
149
  }
139
150
 
151
+ /**
152
+ * Request capabilities from the wallet.
153
+ *
154
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
155
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
156
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
157
+ * friction by allowing apps to request permissions upfront.
158
+ *
159
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
160
+ * while the feature stabilizes.
161
+ *
162
+ * @param _manifest - Application capability manifest declaring what operations the app needs
163
+ */
164
+ public requestCapabilities(_manifest: AppCapabilities): Promise<WalletCapabilities> {
165
+ throw new Error('Not implemented');
166
+ }
167
+
140
168
  public async batch<const T extends readonly BatchedMethod[]>(methods: T): Promise<BatchResults<T>> {
141
169
  const results: any[] = [];
142
170
  for (const method of methods) {
@@ -263,29 +291,96 @@ export abstract class BaseWallet implements Wallet {
263
291
  return instance;
264
292
  }
265
293
 
294
+ /**
295
+ * Simulates calls through the standard PXE path (account entrypoint).
296
+ * @param executionPayload - The execution payload to simulate.
297
+ * @param from - The sender address.
298
+ * @param feeOptions - Fee options for the transaction.
299
+ * @param skipTxValidation - Whether to skip tx validation.
300
+ * @param skipFeeEnforcement - Whether to skip fee enforcement.
301
+ * @param scopes - The scopes to use for the simulation.
302
+ */
303
+ protected async simulateViaEntrypoint(
304
+ executionPayload: ExecutionPayload,
305
+ from: AztecAddress,
306
+ feeOptions: FeeOptions,
307
+ skipTxValidation?: boolean,
308
+ skipFeeEnforcement?: boolean,
309
+ scopes?: AztecAddress[],
310
+ ) {
311
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, from, feeOptions);
312
+ return this.pxe.simulateTx(txRequest, { simulatePublic: true, skipTxValidation, skipFeeEnforcement, scopes });
313
+ }
314
+
315
+ /**
316
+ * Simulates a transaction, optimizing leading public static calls by running them directly
317
+ * on the node while sending the remaining calls through the standard PXE path.
318
+ * Return values from both paths are merged back in original call order.
319
+ * @param executionPayload - The execution payload to simulate.
320
+ * @param opts - Simulation options (from address, fee settings, etc.).
321
+ * @returns The merged simulation result.
322
+ */
266
323
  async simulateTx(executionPayload: ExecutionPayload, opts: SimulateOptions): Promise<TxSimulationResult> {
267
324
  const feeOptions = opts.fee?.estimateGas
268
325
  ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings)
269
326
  : await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
270
- const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
271
- return this.pxe.simulateTx(
272
- txRequest,
273
- true /* simulatePublic */,
274
- opts?.skipTxValidation,
275
- opts?.skipFeeEnforcement ?? true,
276
- );
327
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
328
+ const remainingPayload = { ...executionPayload, calls: remainingCalls };
329
+
330
+ const chainInfo = await this.getChainInfo();
331
+ let blockHeader: BlockHeader;
332
+ // PXE might not be synced yet, so we pull the latest header from the node
333
+ // To keep things consistent, we'll always try with PXE first
334
+ try {
335
+ blockHeader = await this.pxe.getSyncedBlockHeader();
336
+ } catch {
337
+ blockHeader = (await this.aztecNode.getBlockHeader())!;
338
+ }
339
+
340
+ const [optimizedResults, normalResult] = await Promise.all([
341
+ optimizableCalls.length > 0
342
+ ? simulateViaNode(
343
+ this.aztecNode,
344
+ optimizableCalls,
345
+ opts.from,
346
+ chainInfo,
347
+ feeOptions.gasSettings,
348
+ blockHeader,
349
+ opts.skipFeeEnforcement ?? true,
350
+ )
351
+ : Promise.resolve([]),
352
+ remainingCalls.length > 0
353
+ ? this.simulateViaEntrypoint(
354
+ remainingPayload,
355
+ opts.from,
356
+ feeOptions,
357
+ opts.skipTxValidation,
358
+ opts.skipFeeEnforcement ?? true,
359
+ this.scopesFor(opts.from),
360
+ )
361
+ : Promise.resolve(null),
362
+ ]);
363
+
364
+ return buildMergedSimulationResult(optimizedResults, normalResult);
277
365
  }
278
366
 
279
367
  async profileTx(executionPayload: ExecutionPayload, opts: ProfileOptions): Promise<TxProfileResult> {
280
368
  const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
281
369
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
282
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
370
+ return this.pxe.profileTx(txRequest, {
371
+ profileMode: opts.profileMode,
372
+ skipProofGeneration: opts.skipProofGeneration ?? true,
373
+ scopes: this.scopesFor(opts.from),
374
+ });
283
375
  }
284
376
 
285
- async sendTx(executionPayload: ExecutionPayload, opts: SendOptions): Promise<TxHash> {
377
+ public async sendTx<W extends InteractionWaitOptions = undefined>(
378
+ executionPayload: ExecutionPayload,
379
+ opts: SendOptions<W>,
380
+ ): Promise<SendReturn<W>> {
286
381
  const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
287
382
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
288
- const provenTx = await this.pxe.proveTx(txRequest);
383
+ const provenTx = await this.pxe.proveTx(txRequest, this.scopesFor(opts.from));
289
384
  const tx = await provenTx.toTx();
290
385
  const txHash = tx.getTxHash();
291
386
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -296,7 +391,15 @@ export abstract class BaseWallet implements Wallet {
296
391
  throw this.contextualizeError(err, inspect(tx));
297
392
  });
298
393
  this.log.info(`Sent transaction ${txHash}`);
299
- return txHash;
394
+
395
+ // If wait is NO_WAIT, return txHash immediately
396
+ if (opts.wait === NO_WAIT) {
397
+ return txHash as SendReturn<W>;
398
+ }
399
+
400
+ // Otherwise, wait for the full receipt (default behavior on wait: undefined)
401
+ const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
402
+ return (await waitForTx(this.aztecNode, txHash, waitOpts)) as SendReturn<W>;
300
403
  }
301
404
 
302
405
  protected contextualizeError(err: Error, ...context: string[]): Error {
@@ -313,12 +416,8 @@ export abstract class BaseWallet implements Wallet {
313
416
  return err;
314
417
  }
315
418
 
316
- simulateUtility(call: FunctionCall, authwits?: AuthWitness[]): Promise<UtilitySimulationResult> {
317
- return this.pxe.simulateUtility(call, authwits);
318
- }
319
-
320
- getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
321
- return this.aztecNode.getTxReceipt(txHash);
419
+ simulateUtility(call: FunctionCall, opts: SimulateUtilityOptions): Promise<UtilitySimulationResult> {
420
+ return this.pxe.simulateUtility(call, { authwits: opts.authWitnesses, scopes: [opts.scope] });
322
421
  }
323
422
 
324
423
  async getPrivateEvents<T>(
@@ -345,14 +444,7 @@ export abstract class BaseWallet implements Wallet {
345
444
  const instance = await this.pxe.getContractInstance(address);
346
445
  const initNullifier = await siloNullifier(address, address.toField());
347
446
  const publiclyRegisteredContract = await this.aztecNode.getContract(address);
348
- const [initNullifierMembershipWitness, publiclyRegisteredContractClass] = await Promise.all([
349
- this.aztecNode.getNullifierMembershipWitness('latest', initNullifier),
350
- publiclyRegisteredContract
351
- ? this.aztecNode.getContractClass(
352
- publiclyRegisteredContract.currentContractClassId || instance?.currentContractClassId,
353
- )
354
- : undefined,
355
- ]);
447
+ const initNullifierMembershipWitness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
356
448
  const isContractUpdated =
357
449
  publiclyRegisteredContract &&
358
450
  !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
@@ -360,7 +452,6 @@ export abstract class BaseWallet implements Wallet {
360
452
  instance: instance ?? undefined,
361
453
  isContractInitialized: !!initNullifierMembershipWitness,
362
454
  isContractPublished: !!publiclyRegisteredContract,
363
- isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass,
364
455
  isContractUpdated: !!isContractUpdated,
365
456
  updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined,
366
457
  };
@@ -1 +1,2 @@
1
1
  export { BaseWallet, type FeeOptions } from './base_wallet.js';
2
+ export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';
@@ -0,0 +1,229 @@
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 { generateSimulatedProvingResult } from '@aztec/pxe/simulator';
8
+ import { type FunctionCall, FunctionSelector } from '@aztec/stdlib/abi';
9
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
10
+ import type { GasSettings } from '@aztec/stdlib/gas';
11
+ import {
12
+ ClaimedLengthArray,
13
+ CountedPublicCallRequest,
14
+ PrivateCircuitPublicInputs,
15
+ PublicCallRequest,
16
+ } from '@aztec/stdlib/kernel';
17
+ import { ChonkProof } from '@aztec/stdlib/proofs';
18
+ import {
19
+ type BlockHeader,
20
+ type ExecutionPayload,
21
+ HashedValues,
22
+ PrivateCallExecutionResult,
23
+ PrivateExecutionResult,
24
+ PublicSimulationOutput,
25
+ Tx,
26
+ TxContext,
27
+ TxSimulationResult,
28
+ } from '@aztec/stdlib/tx';
29
+
30
+ /**
31
+ * Splits an execution payload into a leading prefix of public static calls
32
+ * (eligible for direct node simulation) and the remaining calls.
33
+ *
34
+ * Only a leading run of public static calls is eligible for optimization.
35
+ * Any non-public-static call may enqueue public state mutations
36
+ * (e.g. private calls can enqueue public calls), so all calls that follow
37
+ * must go through the normal simulation path to see the correct state.
38
+ *
39
+ */
40
+ export function extractOptimizablePublicStaticCalls(payload: ExecutionPayload): {
41
+ /** Leading public static calls eligible for direct node simulation. */
42
+ optimizableCalls: FunctionCall[];
43
+ /** All remaining calls. */
44
+ remainingCalls: FunctionCall[];
45
+ } {
46
+ const splitIndex = payload.calls.findIndex(call => !call.isPublicStatic());
47
+ const boundary = splitIndex === -1 ? payload.calls.length : splitIndex;
48
+ return {
49
+ optimizableCalls: payload.calls.slice(0, boundary),
50
+ remainingCalls: payload.calls.slice(boundary),
51
+ };
52
+ }
53
+
54
+ /**
55
+ * Simulates a batch of public static calls by bypassing account entrypoint and private execution,
56
+ * directly constructing a minimal Tx and calling node.simulatePublicCalls.
57
+ *
58
+ * @param node - The Aztec node to simulate on.
59
+ * @param publicStaticCalls - Array of public static function calls (max MAX_ENQUEUED_CALLS_PER_CALL).
60
+ * @param from - The account address making the calls.
61
+ * @param chainInfo - Chain information (chainId and version).
62
+ * @param gasSettings - Gas settings for the transaction.
63
+ * @param blockHeader - Block header to use as anchor.
64
+ * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
65
+ * @returns TxSimulationResult with public return values.
66
+ */
67
+ async function simulateBatchViaNode(
68
+ node: AztecNode,
69
+ publicStaticCalls: FunctionCall[],
70
+ from: AztecAddress,
71
+ chainInfo: ChainInfo,
72
+ gasSettings: GasSettings,
73
+ blockHeader: BlockHeader,
74
+ skipFeeEnforcement: boolean,
75
+ ): Promise<TxSimulationResult> {
76
+ const txContext = new TxContext(chainInfo.chainId, chainInfo.version, gasSettings);
77
+
78
+ const publicFunctionCalldata: HashedValues[] = [];
79
+ for (const call of publicStaticCalls) {
80
+ const calldata = await HashedValues.fromCalldata([call.selector.toField(), ...call.args]);
81
+ publicFunctionCalldata.push(calldata);
82
+ }
83
+
84
+ const publicCallRequests = makeTuple(MAX_ENQUEUED_CALLS_PER_CALL, i => {
85
+ const call = publicStaticCalls[i];
86
+ if (!call) {
87
+ return CountedPublicCallRequest.empty();
88
+ }
89
+ const publicCallRequest = new PublicCallRequest(from, call.to, call.isStatic, publicFunctionCalldata[i]!.hash);
90
+ // Counter starts at 1 (minRevertibleSideEffectCounter) so all calls are revertible
91
+ return new CountedPublicCallRequest(publicCallRequest, i + 1);
92
+ });
93
+
94
+ const publicCallRequestsArray: ClaimedLengthArray<CountedPublicCallRequest, typeof MAX_ENQUEUED_CALLS_PER_CALL> =
95
+ new ClaimedLengthArray(
96
+ publicCallRequests as Tuple<CountedPublicCallRequest, typeof MAX_ENQUEUED_CALLS_PER_CALL>,
97
+ publicStaticCalls.length,
98
+ );
99
+
100
+ const publicInputs = PrivateCircuitPublicInputs.from({
101
+ ...PrivateCircuitPublicInputs.empty(),
102
+ anchorBlockHeader: blockHeader,
103
+ txContext: txContext,
104
+ publicCallRequests: publicCallRequestsArray,
105
+ startSideEffectCounter: new Fr(0),
106
+ endSideEffectCounter: new Fr(publicStaticCalls.length + 1),
107
+ });
108
+
109
+ // Minimal entrypoint structure — no real private execution, just public call requests
110
+ const emptyEntrypoint = new PrivateCallExecutionResult(
111
+ Buffer.alloc(0),
112
+ Buffer.alloc(0),
113
+ new Map(),
114
+ publicInputs,
115
+ [],
116
+ new Map(),
117
+ [],
118
+ [],
119
+ [],
120
+ [],
121
+ [],
122
+ );
123
+
124
+ const privateResult = new PrivateExecutionResult(emptyEntrypoint, Fr.random(), publicFunctionCalldata);
125
+
126
+ const provingResult = await generateSimulatedProvingResult(
127
+ privateResult,
128
+ (_contractAddress: AztecAddress, _functionSelector: FunctionSelector) => Promise.resolve(''),
129
+ 1, // minRevertibleSideEffectCounter
130
+ );
131
+
132
+ provingResult.publicInputs.feePayer = from;
133
+
134
+ const tx = await Tx.create({
135
+ data: provingResult.publicInputs,
136
+ chonkProof: ChonkProof.empty(),
137
+ contractClassLogFields: [],
138
+ publicFunctionCalldata: publicFunctionCalldata,
139
+ });
140
+
141
+ const publicOutput = await node.simulatePublicCalls(tx, skipFeeEnforcement);
142
+
143
+ if (publicOutput.revertReason) {
144
+ throw publicOutput.revertReason;
145
+ }
146
+
147
+ return new TxSimulationResult(privateResult, provingResult.publicInputs, publicOutput, undefined);
148
+ }
149
+
150
+ /**
151
+ * Simulates public static calls by splitting them into batches of MAX_ENQUEUED_CALLS_PER_CALL
152
+ * and sending each batch directly to the node.
153
+ *
154
+ * @param node - The Aztec node to simulate on.
155
+ * @param publicStaticCalls - Array of public static function calls to optimize.
156
+ * @param from - The account address making the calls.
157
+ * @param chainInfo - Chain information (chainId and version).
158
+ * @param gasSettings - Gas settings for the transaction.
159
+ * @param blockHeader - Block header to use as anchor.
160
+ * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
161
+ * @returns Array of TxSimulationResult, one per batch.
162
+ */
163
+ export async function simulateViaNode(
164
+ node: AztecNode,
165
+ publicStaticCalls: FunctionCall[],
166
+ from: AztecAddress,
167
+ chainInfo: ChainInfo,
168
+ gasSettings: GasSettings,
169
+ blockHeader: BlockHeader,
170
+ skipFeeEnforcement: boolean = true,
171
+ ): Promise<TxSimulationResult[]> {
172
+ const batches: FunctionCall[][] = [];
173
+
174
+ for (let i = 0; i < publicStaticCalls.length; i += MAX_ENQUEUED_CALLS_PER_CALL) {
175
+ batches.push(publicStaticCalls.slice(i, i + MAX_ENQUEUED_CALLS_PER_CALL));
176
+ }
177
+
178
+ const results: TxSimulationResult[] = [];
179
+
180
+ for (const batch of batches) {
181
+ const result = await simulateBatchViaNode(
182
+ node,
183
+ batch,
184
+ from,
185
+ chainInfo,
186
+ gasSettings,
187
+ blockHeader,
188
+ skipFeeEnforcement,
189
+ );
190
+ results.push(result);
191
+ }
192
+
193
+ return results;
194
+ }
195
+
196
+ /**
197
+ * Merges simulation results from the optimized (public static) and normal paths.
198
+ * Since optimized calls are always a leading prefix, return values are simply
199
+ * concatenated: optimized first, then normal.
200
+ * Stats are taken from the normal result only (the optimized path doesn't produce them).
201
+ *
202
+ * @param optimizedResults - Results from optimized public static call batches.
203
+ * @param normalResult - Result from normal simulation (null if all calls were optimized).
204
+ * @returns A single TxSimulationResult with return values in original call order.
205
+ */
206
+ export function buildMergedSimulationResult(
207
+ optimizedResults: TxSimulationResult[],
208
+ normalResult: TxSimulationResult | null,
209
+ ): TxSimulationResult {
210
+ const optimizedReturnValues = optimizedResults.flatMap(r => r.publicOutput?.publicReturnValues ?? []);
211
+ const normalReturnValues = normalResult?.publicOutput?.publicReturnValues ?? [];
212
+ const allReturnValues = [...optimizedReturnValues, ...normalReturnValues];
213
+
214
+ const baseResult = normalResult ?? optimizedResults[0];
215
+
216
+ const mergedPublicOutput: PublicSimulationOutput | undefined = baseResult.publicOutput
217
+ ? {
218
+ ...baseResult.publicOutput,
219
+ publicReturnValues: allReturnValues,
220
+ }
221
+ : undefined;
222
+
223
+ return new TxSimulationResult(
224
+ baseResult.privateExecutionResult,
225
+ baseResult.publicInputs,
226
+ mergedPublicOutput,
227
+ normalResult?.stats,
228
+ );
229
+ }