@aztec/wallet-sdk 0.0.1-commit.5476d83 → 0.0.1-commit.5914bae

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 (105) hide show
  1. package/README.md +228 -331
  2. package/dest/base-wallet/base_wallet.d.ts +92 -42
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +261 -80
  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 +50 -0
  9. package/dest/base-wallet/utils.d.ts.map +1 -0
  10. package/dest/base-wallet/utils.js +133 -0
  11. package/dest/crypto.d.ts +230 -0
  12. package/dest/crypto.d.ts.map +1 -0
  13. package/dest/crypto.js +482 -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 +129 -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/iframe/handlers/iframe_connection_handler.d.ts +118 -0
  38. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -0
  39. package/dest/iframe/handlers/iframe_connection_handler.js +228 -0
  40. package/dest/iframe/handlers/index.d.ts +2 -0
  41. package/dest/iframe/handlers/index.d.ts.map +1 -0
  42. package/dest/iframe/handlers/index.js +1 -0
  43. package/dest/iframe/provider/iframe_discovery.d.ts +25 -0
  44. package/dest/iframe/provider/iframe_discovery.d.ts.map +1 -0
  45. package/dest/iframe/provider/iframe_discovery.js +167 -0
  46. package/dest/iframe/provider/iframe_provider.d.ts +65 -0
  47. package/dest/iframe/provider/iframe_provider.d.ts.map +1 -0
  48. package/dest/iframe/provider/iframe_provider.js +257 -0
  49. package/dest/iframe/provider/iframe_wallet.d.ts +68 -0
  50. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -0
  51. package/dest/iframe/provider/iframe_wallet.js +200 -0
  52. package/dest/iframe/provider/index.d.ts +4 -0
  53. package/dest/iframe/provider/index.d.ts.map +1 -0
  54. package/dest/iframe/provider/index.js +3 -0
  55. package/dest/manager/index.d.ts +2 -7
  56. package/dest/manager/index.d.ts.map +1 -1
  57. package/dest/manager/index.js +0 -4
  58. package/dest/manager/types.d.ts +109 -5
  59. package/dest/manager/types.d.ts.map +1 -1
  60. package/dest/manager/types.js +17 -1
  61. package/dest/manager/wallet_manager.d.ts +50 -7
  62. package/dest/manager/wallet_manager.d.ts.map +1 -1
  63. package/dest/manager/wallet_manager.js +208 -29
  64. package/dest/types.d.ts +135 -0
  65. package/dest/types.d.ts.map +1 -0
  66. package/dest/types.js +15 -0
  67. package/package.json +26 -13
  68. package/src/base-wallet/base_wallet.ts +360 -142
  69. package/src/base-wallet/index.ts +7 -1
  70. package/src/base-wallet/utils.ts +240 -0
  71. package/src/crypto.ts +603 -0
  72. package/src/emoji_alphabet.ts +317 -0
  73. package/src/extension/handlers/background_connection_handler.ts +423 -0
  74. package/src/extension/handlers/content_script_connection_handler.ts +246 -0
  75. package/src/extension/handlers/index.ts +25 -0
  76. package/src/extension/handlers/internal_message_types.ts +69 -0
  77. package/src/extension/provider/extension_provider.ts +233 -0
  78. package/src/extension/provider/extension_wallet.ts +324 -0
  79. package/src/extension/provider/index.ts +7 -0
  80. package/src/iframe/handlers/iframe_connection_handler.ts +328 -0
  81. package/src/iframe/handlers/index.ts +7 -0
  82. package/src/iframe/provider/iframe_discovery.ts +185 -0
  83. package/src/iframe/provider/iframe_provider.ts +331 -0
  84. package/src/iframe/provider/iframe_wallet.ts +229 -0
  85. package/src/iframe/provider/index.ts +3 -0
  86. package/src/manager/index.ts +3 -15
  87. package/src/manager/types.ts +113 -4
  88. package/src/manager/wallet_manager.ts +235 -30
  89. package/src/types.ts +145 -0
  90. package/dest/providers/extension/extension_provider.d.ts +0 -17
  91. package/dest/providers/extension/extension_provider.d.ts.map +0 -1
  92. package/dest/providers/extension/extension_provider.js +0 -56
  93. package/dest/providers/extension/extension_wallet.d.ts +0 -23
  94. package/dest/providers/extension/extension_wallet.d.ts.map +0 -1
  95. package/dest/providers/extension/extension_wallet.js +0 -96
  96. package/dest/providers/extension/index.d.ts +0 -4
  97. package/dest/providers/extension/index.d.ts.map +0 -1
  98. package/dest/providers/types.d.ts +0 -67
  99. package/dest/providers/types.d.ts.map +0 -1
  100. package/dest/providers/types.js +0 -3
  101. package/src/providers/extension/extension_provider.ts +0 -72
  102. package/src/providers/extension/extension_wallet.ts +0 -124
  103. package/src/providers/extension/index.ts +0 -3
  104. package/src/providers/types.ts +0 -71
  105. /package/dest/{providers/extension → extension/provider}/index.js +0 -0
@@ -1,29 +1,50 @@
1
- import { GAS_ESTIMATION_DA_GAS_LIMIT, GAS_ESTIMATION_L2_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT } from '@aztec/constants';
1
+ import { NO_FROM } from '@aztec/aztec.js/account';
2
+ import { NO_WAIT, extractOffchainOutput } from '@aztec/aztec.js/contracts';
3
+ import { waitForTx } from '@aztec/aztec.js/node';
4
+ import { ContractInitializationStatus, TxSimulationResultWithAppOffset } from '@aztec/aztec.js/wallet';
2
5
  import { AccountFeePaymentMethodOptions } from '@aztec/entrypoints/account';
3
- import { Fr } from '@aztec/foundation/fields';
6
+ import { DefaultEntrypoint } from '@aztec/entrypoints/default';
7
+ import { Fr } from '@aztec/foundation/curves/bn254';
4
8
  import { createLogger } from '@aztec/foundation/log';
9
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
5
10
  import { decodeFromAbi } from '@aztec/stdlib/abi';
11
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
6
12
  import { computePartialAddress, getContractClassFromArtifact } from '@aztec/stdlib/contract';
7
13
  import { SimulationError } from '@aztec/stdlib/errors';
8
- import { Gas, GasSettings } from '@aztec/stdlib/gas';
14
+ import { Gas, GasFees, GasSettings } from '@aztec/stdlib/gas';
15
+ import { computeSiloedPrivateInitializationNullifier, computeSiloedPublicInitializationNullifier } from '@aztec/stdlib/hash';
9
16
  import { mergeExecutionPayloads } from '@aztec/stdlib/tx';
10
17
  import { inspect } from 'util';
18
+ import { buildMergedSimulationResult, extractOptimizablePublicStaticCalls, simulateViaNode } from './utils.js';
11
19
  /**
12
20
  * A base class for Wallet implementations
13
21
  */ export class BaseWallet {
14
22
  pxe;
15
23
  aztecNode;
16
24
  log;
17
- baseFeePadding;
25
+ minFeePadding;
18
26
  cancellableTransactions;
27
+ // A wallet is instantiated for a particular chain, so chain info never changes during its lifetime.
28
+ // We cache it here because getChainInfo is called frequently (every tx simulation, send, auth wit, etc.).
29
+ nodeInfoPromise;
19
30
  // Protected because we want to force wallets to instantiate their own PXE.
20
- constructor(pxe, aztecNode){
31
+ constructor(pxe, aztecNode, log = createLogger('wallet-sdk:base_wallet')){
21
32
  this.pxe = pxe;
22
33
  this.aztecNode = aztecNode;
23
- this.log = createLogger('wallet-sdk:base_wallet');
24
- this.baseFeePadding = 0.5;
34
+ this.log = log;
35
+ this.minFeePadding = 0.5;
25
36
  this.cancellableTransactions = false;
26
37
  }
38
+ scopesFrom(from, additionalScopes = []) {
39
+ const allScopes = from === NO_FROM ? additionalScopes : [
40
+ from,
41
+ ...additionalScopes
42
+ ];
43
+ const scopeSet = new Set(allScopes.map((address)=>address.toString()));
44
+ return [
45
+ ...scopeSet
46
+ ].map(AztecAddress.fromString);
47
+ }
27
48
  /**
28
49
  * Returns the list of aliased contacts associated with the wallet.
29
50
  * This base implementation directly returns PXE's senders, but note that in general contacts are a superset of senders.
@@ -38,7 +59,10 @@ import { inspect } from 'util';
38
59
  }));
39
60
  }
40
61
  async getChainInfo() {
41
- const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
62
+ if (!this.nodeInfoPromise) {
63
+ this.nodeInfoPromise = this.aztecNode.getNodeInfo();
64
+ }
65
+ const { l1ChainId, rollupVersion } = await this.nodeInfoPromise;
42
66
  return {
43
67
  chainId: new Fr(l1ChainId),
44
68
  version: new Fr(rollupVersion)
@@ -46,21 +70,44 @@ import { inspect } from 'util';
46
70
  }
47
71
  async createTxExecutionRequestFromPayloadAndFee(executionPayload, from, feeOptions) {
48
72
  const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
49
- const executionOptions = {
50
- txNonce: Fr.random(),
51
- cancellable: this.cancellableTransactions,
52
- feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions
53
- };
54
73
  const finalExecutionPayload = feeExecutionPayload ? mergeExecutionPayloads([
55
74
  feeExecutionPayload,
56
75
  executionPayload
57
76
  ]) : executionPayload;
58
- const fromAccount = await this.getAccountFromAddress(from);
59
- return fromAccount.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, executionOptions);
77
+ const chainInfo = await this.getChainInfo();
78
+ if (from === NO_FROM) {
79
+ const entrypoint = new DefaultEntrypoint();
80
+ return entrypoint.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo);
81
+ } else {
82
+ const fromAccount = await this.getAccountFromAddress(from);
83
+ const executionOptions = {
84
+ txNonce: Fr.random(),
85
+ cancellable: this.cancellableTransactions,
86
+ // If from is an address, feeOptions include the way the account contract should handle the fee payment
87
+ feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions
88
+ };
89
+ return fromAccount.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo, executionOptions);
90
+ }
60
91
  }
61
92
  async createAuthWit(from, messageHashOrIntent) {
62
93
  const account = await this.getAccountFromAddress(from);
63
- return account.createAuthWit(messageHashOrIntent);
94
+ const chainInfo = await this.getChainInfo();
95
+ return account.createAuthWit(messageHashOrIntent, chainInfo);
96
+ }
97
+ /**
98
+ * Request capabilities from the wallet.
99
+ *
100
+ * This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
101
+ * Embedded wallets typically don't support capability-based authorization (no user authorization flow),
102
+ * while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
103
+ * friction by allowing apps to request permissions upfront.
104
+ *
105
+ * TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
106
+ * while the feature stabilizes.
107
+ *
108
+ * @param _manifest - Application capability manifest declaring what operations the app needs
109
+ */ requestCapabilities(_manifest) {
110
+ throw new Error('Not implemented');
64
111
  }
65
112
  async batch(methods) {
66
113
  const results = [];
@@ -83,26 +130,33 @@ import { inspect } from 'util';
83
130
  }
84
131
  /**
85
132
  * Completes partial user-provided fee options with wallet defaults.
86
- * @param from - The address where the transaction is being sent from
87
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
88
- * @param gasSettings - User-provided partial gas settings
89
- * @returns - Complete fee options that can be used to create a transaction execution request
90
- */ async completeFeeOptions(from, feePayer, gasSettings) {
91
- const maxFeesPerGas = gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentBaseFees()).mul(1 + this.baseFeePadding);
133
+ * @param config - Fee completion config.
134
+ */ async completeFeeOptions(config) {
135
+ const { from, feePayer, gasSettings, forEstimation } = config;
136
+ const maxFeesPerGas = gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
92
137
  let accountFeePaymentMethodOptions;
93
- // The transaction does not include a fee payment method, so we set the flag
94
- // for the account to use its fee juice balance
95
- if (!feePayer) {
96
- accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
97
- } else {
98
- // The transaction includes fee payment method, so we check if we are the fee payer for it
99
- // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
100
- accountFeePaymentMethodOptions = from.equals(feePayer) ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM : AccountFeePaymentMethodOptions.EXTERNAL;
138
+ // If from is an address, we need to determine the appropriate fee payment method options for the
139
+ // account contract entrypoint to use
140
+ if (from !== NO_FROM) {
141
+ if (!feePayer) {
142
+ // The transaction does not include a fee payment method, so we set the flag
143
+ // for the account to use its fee juice balance
144
+ accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
145
+ } else {
146
+ // The transaction includes fee payment method, so we check if we are the fee payer for it
147
+ // (this can only happen if the embedded payment method is FeeJuiceWithClaim)
148
+ accountFeePaymentMethodOptions = from.equals(feePayer) ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM : AccountFeePaymentMethodOptions.EXTERNAL;
149
+ }
101
150
  }
102
- const fullGasSettings = GasSettings.default({
103
- ...gasSettings,
104
- maxFeesPerGas
105
- });
151
+ const gasSettingsOverrides = {
152
+ gasLimits: gasSettings?.gasLimits ? Gas.from(gasSettings.gasLimits) : undefined,
153
+ teardownGasLimits: gasSettings?.teardownGasLimits ? Gas.from(gasSettings.teardownGasLimits) : undefined,
154
+ maxFeesPerGas,
155
+ maxPriorityFeesPerGas: gasSettings?.maxPriorityFeesPerGas ?? GasFees.empty()
156
+ };
157
+ // When estimating gas (simulation), use high limits so the simulation doesn't run out of gas.
158
+ // When sending for real, use protocol max limits that the network will actually accept.
159
+ const fullGasSettings = forEstimation ? GasSettings.forEstimation(gasSettingsOverrides) : GasSettings.fallback(gasSettingsOverrides);
106
160
  this.log.debug(`Using L2 gas settings`, fullGasSettings);
107
161
  return {
108
162
  gasSettings: fullGasSettings,
@@ -110,29 +164,11 @@ import { inspect } from 'util';
110
164
  accountFeePaymentMethodOptions
111
165
  };
112
166
  }
113
- /**
114
- * Completes partial user-provided fee options with unreasonably high gas limits
115
- * for gas estimation. Uses the same logic as completeFeeOptions but sets high limits
116
- * to avoid running out of gas during estimation.
117
- * @param from - The address where the transaction is being sent from
118
- * @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
119
- * @param gasSettings - User-provided partial gas settings
120
- */ async completeFeeOptionsForEstimation(from, feePayer, gasSettings) {
121
- const defaultFeeOptions = await this.completeFeeOptions(from, feePayer, gasSettings);
122
- const { gasSettings: { maxFeesPerGas, maxPriorityFeesPerGas } } = defaultFeeOptions;
123
- // Use unrealistically high gas limits for estimation to avoid running out of gas.
124
- // They will be tuned down after the simulation.
125
- const gasSettingsForEstimation = new GasSettings(new Gas(GAS_ESTIMATION_DA_GAS_LIMIT, GAS_ESTIMATION_L2_GAS_LIMIT), new Gas(GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT), maxFeesPerGas, maxPriorityFeesPerGas);
126
- return {
127
- ...defaultFeeOptions,
128
- gasSettings: gasSettingsForEstimation
129
- };
130
- }
131
167
  registerSender(address, _alias = '') {
132
168
  return this.pxe.registerSender(address);
133
169
  }
134
170
  async registerContract(instance, artifact, secretKey) {
135
- const { contractInstance: existingInstance } = await this.pxe.getContractMetadata(instance.address);
171
+ const existingInstance = await this.pxe.getContractInstance(instance.address);
136
172
  if (existingInstance) {
137
173
  // Instance already registered in the wallet
138
174
  if (artifact) {
@@ -148,11 +184,10 @@ import { inspect } from 'util';
148
184
  // Instance not registered yet
149
185
  if (!artifact) {
150
186
  // Try to get the artifact from the wallet's contract class storage
151
- const classMetadata = await this.pxe.getContractClassMetadata(instance.currentContractClassId, true);
152
- if (!classMetadata.artifact) {
187
+ artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
188
+ if (!artifact) {
153
189
  throw new Error(`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()}`);
154
190
  }
155
- artifact = classMetadata.artifact;
156
191
  }
157
192
  await this.pxe.registerContract({
158
193
  artifact,
@@ -164,20 +199,96 @@ import { inspect } from 'util';
164
199
  }
165
200
  return instance;
166
201
  }
167
- async simulateTx(executionPayload, opts) {
168
- const feeOptions = opts.fee?.estimateGas ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings) : await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
169
- const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
170
- return this.pxe.simulateTx(txRequest, true, opts?.skipTxValidation, opts?.skipFeeEnforcement ?? true);
202
+ /**
203
+ * Simulates calls through the standard PXE path (account entrypoint).
204
+ * @param executionPayload - The execution payload to simulate.
205
+ * @param opts - Simulation options.
206
+ */ async simulateViaEntrypoint(executionPayload, opts) {
207
+ const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, opts.feeOptions);
208
+ const result = await this.pxe.simulateTx(txRequest, {
209
+ simulatePublic: true,
210
+ skipTxValidation: opts.skipTxValidation,
211
+ skipFeeEnforcement: opts.skipFeeEnforcement,
212
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes)
213
+ });
214
+ const appCallOffset = await this.computeAppCallOffset(opts.from, opts.feeOptions);
215
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(result, appCallOffset);
216
+ }
217
+ /**
218
+ * Computes the index where the app's calls begin in the flattened array of calls (0 = entrypoint/root, 1..N = fee
219
+ * calls, N+1 = app).
220
+ * @param from - The sender address, or NO_FROM for the default entrypoint.
221
+ * @param feeOptions - Fee options containing the wallet fee payment method.
222
+ */ async computeAppCallOffset(from, feeOptions) {
223
+ if (from === NO_FROM) {
224
+ return 0;
225
+ }
226
+ const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
227
+ return (feeExecutionPayload?.calls.length ?? 0) + 1; // +1 for entrypoint
228
+ }
229
+ /**
230
+ * Simulates a transaction, optimizing leading public static calls by running them directly
231
+ * on the node while sending the remaining calls through the standard PXE path.
232
+ * Return values from both paths are merged back in original call order.
233
+ * @param executionPayload - The execution payload to simulate.
234
+ * @param opts - Simulation options (from address, fee settings, etc.).
235
+ * @returns The merged simulation result.
236
+ */ async simulateTx(executionPayload, opts) {
237
+ const feeOptions = await this.completeFeeOptions({
238
+ from: opts.from,
239
+ feePayer: executionPayload.feePayer,
240
+ gasSettings: opts.fee?.gasSettings,
241
+ forEstimation: true
242
+ });
243
+ const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
244
+ const remainingPayload = {
245
+ ...executionPayload,
246
+ calls: remainingCalls
247
+ };
248
+ const chainInfo = await this.getChainInfo();
249
+ let blockHeader;
250
+ // PXE might not be synced yet, so we pull the latest header from the node
251
+ // To keep things consistent, we'll always try with PXE first
252
+ try {
253
+ blockHeader = await this.pxe.getSyncedBlockHeader();
254
+ } catch {
255
+ blockHeader = await this.aztecNode.getBlockHeader();
256
+ }
257
+ const simulationOrigin = opts.from === NO_FROM ? AztecAddress.ZERO : opts.from;
258
+ const [optimizedResults, normalResult] = await Promise.all([
259
+ optimizableCalls.length > 0 ? simulateViaNode(this.aztecNode, optimizableCalls, simulationOrigin, chainInfo, feeOptions.gasSettings, blockHeader, opts.skipFeeEnforcement ?? true, this.getContractName.bind(this)) : Promise.resolve([]),
260
+ remainingCalls.length > 0 ? this.simulateViaEntrypoint(remainingPayload, {
261
+ from: opts.from,
262
+ feeOptions,
263
+ additionalScopes: opts.additionalScopes,
264
+ skipTxValidation: opts.skipTxValidation,
265
+ skipFeeEnforcement: opts.skipFeeEnforcement ?? true
266
+ }) : Promise.resolve(null)
267
+ ]);
268
+ return buildMergedSimulationResult(optimizedResults, normalResult);
171
269
  }
172
270
  async profileTx(executionPayload, opts) {
173
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
271
+ const feeOptions = await this.completeFeeOptions({
272
+ from: opts.from,
273
+ feePayer: executionPayload.feePayer,
274
+ gasSettings: opts.fee?.gasSettings
275
+ });
174
276
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
175
- return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
277
+ return this.pxe.profileTx(txRequest, {
278
+ profileMode: opts.profileMode,
279
+ skipProofGeneration: opts.skipProofGeneration ?? true,
280
+ scopes: this.scopesFrom(opts.from, opts.additionalScopes)
281
+ });
176
282
  }
177
283
  async sendTx(executionPayload, opts) {
178
- const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
284
+ const feeOptions = await this.completeFeeOptions({
285
+ from: opts.from,
286
+ feePayer: executionPayload.feePayer,
287
+ gasSettings: opts.fee?.gasSettings
288
+ });
179
289
  const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
180
- const provenTx = await this.pxe.proveTx(txRequest);
290
+ const provenTx = await this.pxe.proveTx(txRequest, this.scopesFrom(opts.from, opts.additionalScopes));
291
+ const offchainOutput = extractOffchainOutput(provenTx.getOffchainEffects(), provenTx.publicInputs.constants.anchorBlockHeader.globalVariables.timestamp);
181
292
  const tx = await provenTx.toTx();
182
293
  const txHash = tx.getTxHash();
183
294
  if (await this.aztecNode.getTxEffect(txHash)) {
@@ -188,7 +299,35 @@ import { inspect } from 'util';
188
299
  throw this.contextualizeError(err, inspect(tx));
189
300
  });
190
301
  this.log.info(`Sent transaction ${txHash}`);
191
- return txHash;
302
+ // If wait is NO_WAIT, return txHash immediately
303
+ if (opts.wait === NO_WAIT) {
304
+ return {
305
+ txHash,
306
+ ...offchainOutput
307
+ };
308
+ }
309
+ // Otherwise, wait for the full receipt (default behavior on wait: undefined)
310
+ const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
311
+ const receipt = await waitForTx(this.aztecNode, txHash, waitOpts);
312
+ // Display debug logs from public execution if present (served in test mode only)
313
+ if (receipt.debugLogs?.length) {
314
+ await displayDebugLogs(receipt.debugLogs, this.getContractName.bind(this));
315
+ }
316
+ return {
317
+ receipt,
318
+ ...offchainOutput
319
+ };
320
+ }
321
+ /**
322
+ * Resolves a contract address to a human-readable name via PXE, if available.
323
+ * @param address - The contract address to resolve.
324
+ */ async getContractName(address) {
325
+ const instance = await this.pxe.getContractInstance(address);
326
+ if (!instance) {
327
+ return undefined;
328
+ }
329
+ const artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
330
+ return artifact?.name;
192
331
  }
193
332
  contextualizeError(err, ...context) {
194
333
  let contextStr = '';
@@ -203,23 +342,65 @@ import { inspect } from 'util';
203
342
  }
204
343
  return err;
205
344
  }
206
- simulateUtility(call, authwits) {
207
- return this.pxe.simulateUtility(call, authwits);
208
- }
209
- getContractClassMetadata(id, includeArtifact = false) {
210
- return this.pxe.getContractClassMetadata(id, includeArtifact);
345
+ executeUtility(call, opts) {
346
+ return this.pxe.executeUtility(call, {
347
+ authwits: opts.authWitnesses,
348
+ scopes: opts.scopes
349
+ });
211
350
  }
212
- getContractMetadata(address) {
213
- return this.pxe.getContractMetadata(address);
351
+ async getPrivateEvents(eventDef, eventFilter) {
352
+ const pxeEvents = await this.pxe.getPrivateEvents(eventDef.eventSelector, eventFilter);
353
+ const decodedEvents = pxeEvents.map((pxeEvent)=>{
354
+ return {
355
+ event: decodeFromAbi([
356
+ eventDef.abiType
357
+ ], pxeEvent.packedEvent),
358
+ metadata: {
359
+ l2BlockNumber: pxeEvent.l2BlockNumber,
360
+ l2BlockHash: pxeEvent.l2BlockHash,
361
+ txHash: pxeEvent.txHash
362
+ }
363
+ };
364
+ });
365
+ return decodedEvents;
214
366
  }
215
- getTxReceipt(txHash) {
216
- return this.aztecNode.getTxReceipt(txHash);
367
+ /**
368
+ * Returns metadata about a contract, including whether it has been initialized, published, and updated.
369
+ * @param address - The contract address to query.
370
+ */ async getContractMetadata(address) {
371
+ const instance = await this.pxe.getContractInstance(address);
372
+ const publiclyRegisteredContractPromise = this.aztecNode.getContract(address);
373
+ let initializationStatus;
374
+ if (instance) {
375
+ // We have the instance, so we can compute the private initialization nullifier (which includes init_hash and is
376
+ // emitted by both private and public initializers) and get a definitive INITIALIZED/UNINITIALIZED answer.
377
+ const initNullifier = await computeSiloedPrivateInitializationNullifier(address, instance.initializationHash);
378
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
379
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNINITIALIZED;
380
+ } else {
381
+ // Without the instance we lack the init_hash needed for the private nullifier. We fall back to checking the
382
+ // public initialization nullifier (computed from address alone). Not all contracts emit it (only those with
383
+ // public functions that require initialization checks), so its absence doesn't mean the contract is
384
+ // uninitialized.
385
+ const publicNullifier = await computeSiloedPublicInitializationNullifier(address);
386
+ const witness = await this.aztecNode.getNullifierMembershipWitness('latest', publicNullifier);
387
+ initializationStatus = witness ? ContractInitializationStatus.INITIALIZED : ContractInitializationStatus.UNKNOWN;
388
+ }
389
+ const publiclyRegisteredContract = await publiclyRegisteredContractPromise;
390
+ const isContractUpdated = publiclyRegisteredContract && !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
391
+ return {
392
+ instance: instance ?? undefined,
393
+ initializationStatus,
394
+ isContractPublished: !!publiclyRegisteredContract,
395
+ isContractUpdated: !!isContractUpdated,
396
+ updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined
397
+ };
217
398
  }
218
- async getPrivateEvents(contractAddress, eventDef, from, limit, recipients = []) {
219
- const events = await this.pxe.getPrivateEvents(contractAddress, eventDef.eventSelector, from, limit, recipients);
220
- const decodedEvents = events.map((event /** PrivateEvent */ )=>decodeFromAbi([
221
- eventDef.abiType
222
- ], event.packedEvent));
223
- return decodedEvents;
399
+ async getContractClassMetadata(id) {
400
+ const publiclyRegisteredContractClass = await this.aztecNode.getContractClass(id);
401
+ return {
402
+ isArtifactRegistered: !!await this.pxe.getContractArtifact(id),
403
+ isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass
404
+ };
224
405
  }
225
406
  }
@@ -1,2 +1,3 @@
1
- export { BaseWallet, type FeeOptions } from './base_wallet.js';
2
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXNlLXdhbGxldC9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsVUFBVSxFQUFFLEtBQUssVUFBVSxFQUFFLE1BQU0sa0JBQWtCLENBQUMifQ==
1
+ export { BaseWallet, type CompleteFeeOptionsConfig, type FeeOptions, type SimulateViaEntrypointOptions, } from './base_wallet.js';
2
+ export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';
3
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXNlLXdhbGxldC9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQ0wsVUFBVSxFQUNWLEtBQUssd0JBQXdCLEVBQzdCLEtBQUssVUFBVSxFQUNmLEtBQUssNEJBQTRCLEdBQ2xDLE1BQU0sa0JBQWtCLENBQUM7QUFDMUIsT0FBTyxFQUFFLGVBQWUsRUFBRSwyQkFBMkIsRUFBRSxtQ0FBbUMsRUFBRSxNQUFNLFlBQVksQ0FBQyJ9
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/base-wallet/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,UAAU,EAAE,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/base-wallet/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,KAAK,wBAAwB,EAC7B,KAAK,UAAU,EACf,KAAK,4BAA4B,GAClC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,eAAe,EAAE,2BAA2B,EAAE,mCAAmC,EAAE,MAAM,YAAY,CAAC"}
@@ -1 +1,2 @@
1
1
  export { BaseWallet } from './base_wallet.js';
2
+ export { simulateViaNode, buildMergedSimulationResult, extractOptimizablePublicStaticCalls } from './utils.js';
@@ -0,0 +1,50 @@
1
+ import type { AztecNode } from '@aztec/aztec.js/node';
2
+ import { TxSimulationResultWithAppOffset } from '@aztec/aztec.js/wallet';
3
+ import type { ChainInfo } from '@aztec/entrypoints/interfaces';
4
+ import type { ContractNameResolver } from '@aztec/pxe/client/lazy';
5
+ import { type FunctionCall } from '@aztec/stdlib/abi';
6
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
7
+ import type { GasSettings } from '@aztec/stdlib/gas';
8
+ import { type BlockHeader, type ExecutionPayload, TxSimulationResult } from '@aztec/stdlib/tx';
9
+ /**
10
+ * Splits an execution payload into a leading prefix of public static calls
11
+ * (eligible for direct node simulation) and the remaining calls.
12
+ *
13
+ * Only a leading run of public static calls is eligible for optimization.
14
+ * Any non-public-static call may enqueue public state mutations
15
+ * (e.g. private calls can enqueue public calls), so all calls that follow
16
+ * must go through the normal simulation path to see the correct state.
17
+ *
18
+ */
19
+ export declare function extractOptimizablePublicStaticCalls(payload: ExecutionPayload): {
20
+ /** Leading public static calls eligible for direct node simulation. */
21
+ optimizableCalls: FunctionCall[];
22
+ /** All remaining calls. */
23
+ remainingCalls: FunctionCall[];
24
+ };
25
+ /**
26
+ * Simulates public static calls by splitting them into batches of MAX_ENQUEUED_CALLS_PER_CALL
27
+ * and sending each batch directly to the node.
28
+ *
29
+ * @param node - The Aztec node to simulate on.
30
+ * @param publicStaticCalls - Array of public static function calls to optimize.
31
+ * @param from - The account address making the calls.
32
+ * @param chainInfo - Chain information (chainId and version).
33
+ * @param gasSettings - Gas settings for the transaction.
34
+ * @param blockHeader - Block header to use as anchor.
35
+ * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
36
+ * @returns Array of TxSimulationResult, one per batch.
37
+ */
38
+ export declare function simulateViaNode(node: AztecNode, publicStaticCalls: FunctionCall[], from: AztecAddress, chainInfo: ChainInfo, gasSettings: GasSettings, blockHeader: BlockHeader, skipFeeEnforcement: boolean | undefined, getContractName: ContractNameResolver): Promise<TxSimulationResult[]>;
39
+ /**
40
+ * Merges simulation results from the optimized (public static) and normal paths.
41
+ * Since optimized calls are always a leading prefix, return values are simply
42
+ * concatenated: optimized first, then normal.
43
+ * Stats are taken from the normal result only (the optimized path doesn't produce them).
44
+ *
45
+ * @param optimizedResults - Results from optimized public static call batches.
46
+ * @param normalResult - Result from normal simulation (null if all calls were optimized).
47
+ * @returns A single TxSimulationResult with return values in original call order.
48
+ */
49
+ export declare function buildMergedSimulationResult(optimizedResults: TxSimulationResult[], normalResult: TxSimulationResultWithAppOffset | null): TxSimulationResultWithAppOffset;
50
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbHMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXNlLXdhbGxldC91dGlscy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssRUFBRSxTQUFTLEVBQUUsTUFBTSxzQkFBc0IsQ0FBQztBQUN0RCxPQUFPLEVBQUUsK0JBQStCLEVBQUUsTUFBTSx3QkFBd0IsQ0FBQztBQUV6RSxPQUFPLEtBQUssRUFBRSxTQUFTLEVBQUUsTUFBTSwrQkFBK0IsQ0FBQztBQUkvRCxPQUFPLEtBQUssRUFBRSxvQkFBb0IsRUFBRSxNQUFNLHdCQUF3QixDQUFDO0FBR25FLE9BQU8sRUFBRSxLQUFLLFlBQVksRUFBb0IsTUFBTSxtQkFBbUIsQ0FBQztBQUN4RSxPQUFPLEtBQUssRUFBRSxZQUFZLEVBQUUsTUFBTSw2QkFBNkIsQ0FBQztBQUNoRSxPQUFPLEtBQUssRUFBRSxXQUFXLEVBQUUsTUFBTSxtQkFBbUIsQ0FBQztBQVFyRCxPQUFPLEVBQ0wsS0FBSyxXQUFXLEVBQ2hCLEtBQUssZ0JBQWdCLEVBT3JCLGtCQUFrQixFQUNuQixNQUFNLGtCQUFrQixDQUFDO0FBRTFCOzs7Ozs7Ozs7R0FTRztBQUNILHdCQUFnQixtQ0FBbUMsQ0FBQyxPQUFPLEVBQUUsZ0JBQWdCLEdBQUc7SUFDOUUsdUVBQXVFO0lBQ3ZFLGdCQUFnQixFQUFFLFlBQVksRUFBRSxDQUFDO0lBQ2pDLDJCQUEyQjtJQUMzQixjQUFjLEVBQUUsWUFBWSxFQUFFLENBQUM7Q0FDaEMsQ0FPQTtBQXVHRDs7Ozs7Ozs7Ozs7O0dBWUc7QUFDSCx3QkFBc0IsZUFBZSxDQUNuQyxJQUFJLEVBQUUsU0FBUyxFQUNmLGlCQUFpQixFQUFFLFlBQVksRUFBRSxFQUNqQyxJQUFJLEVBQUUsWUFBWSxFQUNsQixTQUFTLEVBQUUsU0FBUyxFQUNwQixXQUFXLEVBQUUsV0FBVyxFQUN4QixXQUFXLEVBQUUsV0FBVyxFQUN4QixrQkFBa0IscUJBQWdCLEVBQ2xDLGVBQWUsRUFBRSxvQkFBb0IsR0FDcEMsT0FBTyxDQUFDLGtCQUFrQixFQUFFLENBQUMsQ0F3Qi9CO0FBRUQ7Ozs7Ozs7OztHQVNHO0FBQ0gsd0JBQWdCLDJCQUEyQixDQUN6QyxnQkFBZ0IsRUFBRSxrQkFBa0IsRUFBRSxFQUN0QyxZQUFZLEVBQUUsK0JBQStCLEdBQUcsSUFBSSxHQUNuRCwrQkFBK0IsQ0FxQmpDIn0=
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/base-wallet/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,+BAA+B,EAAE,MAAM,wBAAwB,CAAC;AAEzE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAI/D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAGnE,OAAO,EAAE,KAAK,YAAY,EAAoB,MAAM,mBAAmB,CAAC;AACxE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAQrD,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,gBAAgB,EAOrB,kBAAkB,EACnB,MAAM,kBAAkB,CAAC;AAE1B;;;;;;;;;GASG;AACH,wBAAgB,mCAAmC,CAAC,OAAO,EAAE,gBAAgB,GAAG;IAC9E,uEAAuE;IACvE,gBAAgB,EAAE,YAAY,EAAE,CAAC;IACjC,2BAA2B;IAC3B,cAAc,EAAE,YAAY,EAAE,CAAC;CAChC,CAOA;AAuGD;;;;;;;;;;;;GAYG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,SAAS,EACf,iBAAiB,EAAE,YAAY,EAAE,EACjC,IAAI,EAAE,YAAY,EAClB,SAAS,EAAE,SAAS,EACpB,WAAW,EAAE,WAAW,EACxB,WAAW,EAAE,WAAW,EACxB,kBAAkB,qBAAgB,EAClC,eAAe,EAAE,oBAAoB,GACpC,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAwB/B;AAED;;;;;;;;;GASG;AACH,wBAAgB,2BAA2B,CACzC,gBAAgB,EAAE,kBAAkB,EAAE,EACtC,YAAY,EAAE,+BAA+B,GAAG,IAAI,GACnD,+BAA+B,CAqBjC"}
@@ -0,0 +1,133 @@
1
+ import { TxSimulationResultWithAppOffset } from '@aztec/aztec.js/wallet';
2
+ import { MAX_ENQUEUED_CALLS_PER_CALL } from '@aztec/constants';
3
+ import { makeTuple } from '@aztec/foundation/array';
4
+ import { Fr } from '@aztec/foundation/curves/bn254';
5
+ import { displayDebugLogs } from '@aztec/pxe/client/lazy';
6
+ import { generateSimulatedProvingResult } from '@aztec/pxe/simulator';
7
+ import { ClaimedLengthArray, CountedPublicCallRequest, PrivateCircuitPublicInputs, PublicCallRequest } from '@aztec/stdlib/kernel';
8
+ import { ChonkProof } from '@aztec/stdlib/proofs';
9
+ import { HashedValues, PrivateCallExecutionResult, PrivateExecutionResult, Tx, TxContext, TxSimulationResult } from '@aztec/stdlib/tx';
10
+ /**
11
+ * Splits an execution payload into a leading prefix of public static calls
12
+ * (eligible for direct node simulation) and the remaining calls.
13
+ *
14
+ * Only a leading run of public static calls is eligible for optimization.
15
+ * Any non-public-static call may enqueue public state mutations
16
+ * (e.g. private calls can enqueue public calls), so all calls that follow
17
+ * must go through the normal simulation path to see the correct state.
18
+ *
19
+ */ export function extractOptimizablePublicStaticCalls(payload) {
20
+ const splitIndex = payload.calls.findIndex((call)=>!call.isPublicStatic());
21
+ const boundary = splitIndex === -1 ? payload.calls.length : splitIndex;
22
+ return {
23
+ optimizableCalls: payload.calls.slice(0, boundary),
24
+ remainingCalls: payload.calls.slice(boundary)
25
+ };
26
+ }
27
+ /**
28
+ * Simulates a batch of public static calls by bypassing account entrypoint and private execution,
29
+ * directly constructing a minimal Tx and calling node.simulatePublicCalls.
30
+ *
31
+ * @param node - The Aztec node to simulate on.
32
+ * @param publicStaticCalls - Array of public static function calls (max MAX_ENQUEUED_CALLS_PER_CALL).
33
+ * @param from - The account address making the calls.
34
+ * @param chainInfo - Chain information (chainId and version).
35
+ * @param gasSettings - Gas settings for the transaction.
36
+ * @param blockHeader - Block header to use as anchor.
37
+ * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
38
+ * @returns TxSimulationResult with public return values.
39
+ */ async function simulateBatchViaNode(node, publicStaticCalls, from, chainInfo, gasSettings, blockHeader, skipFeeEnforcement, getContractName) {
40
+ const txContext = new TxContext(chainInfo.chainId, chainInfo.version, gasSettings);
41
+ const publicFunctionCalldata = [];
42
+ for (const call of publicStaticCalls){
43
+ const calldata = await HashedValues.fromCalldata([
44
+ call.selector.toField(),
45
+ ...call.args
46
+ ]);
47
+ publicFunctionCalldata.push(calldata);
48
+ }
49
+ const publicCallRequests = makeTuple(MAX_ENQUEUED_CALLS_PER_CALL, (i)=>{
50
+ const call = publicStaticCalls[i];
51
+ if (!call) {
52
+ return CountedPublicCallRequest.empty();
53
+ }
54
+ const publicCallRequest = new PublicCallRequest(from, call.to, call.isStatic, publicFunctionCalldata[i].hash);
55
+ // Counter starts at 1 (minRevertibleSideEffectCounter) so all calls are revertible
56
+ return new CountedPublicCallRequest(publicCallRequest, i + 1);
57
+ });
58
+ const publicCallRequestsArray = new ClaimedLengthArray(publicCallRequests, publicStaticCalls.length);
59
+ const publicInputs = PrivateCircuitPublicInputs.from({
60
+ ...PrivateCircuitPublicInputs.empty(),
61
+ anchorBlockHeader: blockHeader,
62
+ txContext: txContext,
63
+ publicCallRequests: publicCallRequestsArray,
64
+ startSideEffectCounter: new Fr(0),
65
+ endSideEffectCounter: new Fr(publicStaticCalls.length + 1)
66
+ });
67
+ // Minimal entrypoint structure — no real private execution, just public call requests
68
+ const emptyEntrypoint = new PrivateCallExecutionResult(Buffer.alloc(0), Buffer.alloc(0), new Map(), publicInputs, [], new Map(), [], [], [], [], []);
69
+ const privateResult = new PrivateExecutionResult(emptyEntrypoint, Fr.random(), publicFunctionCalldata);
70
+ const provingResult = await generateSimulatedProvingResult(privateResult, (_contractAddress, _functionSelector)=>Promise.resolve(''), node, 1);
71
+ provingResult.publicInputs.feePayer = from;
72
+ const tx = await Tx.create({
73
+ data: provingResult.publicInputs,
74
+ chonkProof: ChonkProof.empty(),
75
+ contractClassLogFields: [],
76
+ publicFunctionCalldata: publicFunctionCalldata
77
+ });
78
+ const publicOutput = await node.simulatePublicCalls(tx, skipFeeEnforcement);
79
+ if (publicOutput.revertReason) {
80
+ throw publicOutput.revertReason;
81
+ }
82
+ // Display debug logs from the public simulation.
83
+ await displayDebugLogs(publicOutput.debugLogs, getContractName);
84
+ return new TxSimulationResult(privateResult, provingResult.publicInputs, publicOutput, undefined);
85
+ }
86
+ /**
87
+ * Simulates public static calls by splitting them into batches of MAX_ENQUEUED_CALLS_PER_CALL
88
+ * and sending each batch directly to the node.
89
+ *
90
+ * @param node - The Aztec node to simulate on.
91
+ * @param publicStaticCalls - Array of public static function calls to optimize.
92
+ * @param from - The account address making the calls.
93
+ * @param chainInfo - Chain information (chainId and version).
94
+ * @param gasSettings - Gas settings for the transaction.
95
+ * @param blockHeader - Block header to use as anchor.
96
+ * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
97
+ * @returns Array of TxSimulationResult, one per batch.
98
+ */ export async function simulateViaNode(node, publicStaticCalls, from, chainInfo, gasSettings, blockHeader, skipFeeEnforcement = true, getContractName) {
99
+ const batches = [];
100
+ for(let i = 0; i < publicStaticCalls.length; i += MAX_ENQUEUED_CALLS_PER_CALL){
101
+ batches.push(publicStaticCalls.slice(i, i + MAX_ENQUEUED_CALLS_PER_CALL));
102
+ }
103
+ const results = [];
104
+ for (const batch of batches){
105
+ const result = await simulateBatchViaNode(node, batch, from, chainInfo, gasSettings, blockHeader, skipFeeEnforcement, getContractName);
106
+ results.push(result);
107
+ }
108
+ return results;
109
+ }
110
+ /**
111
+ * Merges simulation results from the optimized (public static) and normal paths.
112
+ * Since optimized calls are always a leading prefix, return values are simply
113
+ * concatenated: optimized first, then normal.
114
+ * Stats are taken from the normal result only (the optimized path doesn't produce them).
115
+ *
116
+ * @param optimizedResults - Results from optimized public static call batches.
117
+ * @param normalResult - Result from normal simulation (null if all calls were optimized).
118
+ * @returns A single TxSimulationResult with return values in original call order.
119
+ */ export function buildMergedSimulationResult(optimizedResults, normalResult) {
120
+ const optimizedReturnValues = optimizedResults.flatMap((r)=>r.publicOutput?.publicReturnValues ?? []);
121
+ const normalReturnValues = normalResult?.publicOutput?.publicReturnValues ?? [];
122
+ const allReturnValues = [
123
+ ...optimizedReturnValues,
124
+ ...normalReturnValues
125
+ ];
126
+ const baseResult = normalResult ?? optimizedResults[0];
127
+ const mergedPublicOutput = baseResult.publicOutput ? {
128
+ ...baseResult.publicOutput,
129
+ publicReturnValues: allReturnValues
130
+ } : undefined;
131
+ const merged = new TxSimulationResult(baseResult.privateExecutionResult, baseResult.publicInputs, mergedPublicOutput, normalResult?.stats);
132
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(merged, normalResult?.appCallOffset ?? 0);
133
+ }