@aztec/simulator 0.55.0 → 0.56.0

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 (171) hide show
  1. package/dest/avm/avm_execution_environment.d.ts +0 -8
  2. package/dest/avm/avm_execution_environment.d.ts.map +1 -1
  3. package/dest/avm/avm_execution_environment.js +1 -19
  4. package/dest/avm/avm_gas.d.ts +2 -2
  5. package/dest/avm/avm_gas.d.ts.map +1 -1
  6. package/dest/avm/avm_gas.js +31 -115
  7. package/dest/avm/avm_machine_state.d.ts.map +1 -1
  8. package/dest/avm/avm_machine_state.js +6 -6
  9. package/dest/avm/avm_memory_types.d.ts +35 -7
  10. package/dest/avm/avm_memory_types.d.ts.map +1 -1
  11. package/dest/avm/avm_memory_types.js +25 -11
  12. package/dest/avm/avm_simulator.d.ts.map +1 -1
  13. package/dest/avm/avm_simulator.js +5 -6
  14. package/dest/avm/bytecode_utils.d.ts +1 -2
  15. package/dest/avm/bytecode_utils.d.ts.map +1 -1
  16. package/dest/avm/bytecode_utils.js +3 -17
  17. package/dest/avm/fixtures/index.d.ts +4 -16
  18. package/dest/avm/fixtures/index.d.ts.map +1 -1
  19. package/dest/avm/fixtures/index.js +9 -25
  20. package/dest/avm/journal/index.d.ts +0 -1
  21. package/dest/avm/journal/index.d.ts.map +1 -1
  22. package/dest/avm/journal/index.js +1 -2
  23. package/dest/avm/journal/journal.d.ts +4 -4
  24. package/dest/avm/journal/journal.d.ts.map +1 -1
  25. package/dest/avm/journal/journal.js +14 -13
  26. package/dest/avm/opcodes/bitwise.d.ts +10 -4
  27. package/dest/avm/opcodes/bitwise.d.ts.map +1 -1
  28. package/dest/avm/opcodes/bitwise.js +17 -11
  29. package/dest/avm/opcodes/commitment.js +2 -2
  30. package/dest/avm/opcodes/comparators.js +2 -2
  31. package/dest/avm/opcodes/conversion.d.ts +3 -2
  32. package/dest/avm/opcodes/conversion.d.ts.map +1 -1
  33. package/dest/avm/opcodes/conversion.js +18 -11
  34. package/dest/avm/opcodes/environment_getters.d.ts +27 -63
  35. package/dest/avm/opcodes/environment_getters.d.ts.map +1 -1
  36. package/dest/avm/opcodes/environment_getters.js +75 -80
  37. package/dest/avm/opcodes/hashing.d.ts +7 -5
  38. package/dest/avm/opcodes/hashing.d.ts.map +1 -1
  39. package/dest/avm/opcodes/hashing.js +40 -24
  40. package/dest/avm/opcodes/index.d.ts +3 -0
  41. package/dest/avm/opcodes/index.d.ts.map +1 -1
  42. package/dest/avm/opcodes/index.js +4 -1
  43. package/dest/avm/opcodes/instruction_impl.d.ts +0 -26
  44. package/dest/avm/opcodes/instruction_impl.d.ts.map +1 -1
  45. package/dest/avm/opcodes/instruction_impl.js +1 -51
  46. package/dest/avm/opcodes/memory.d.ts +7 -2
  47. package/dest/avm/opcodes/memory.d.ts.map +1 -1
  48. package/dest/avm/opcodes/memory.js +23 -6
  49. package/dest/avm/opcodes/multi_scalar_mul.d.ts.map +1 -1
  50. package/dest/avm/opcodes/multi_scalar_mul.js +7 -6
  51. package/dest/avm/serialization/bytecode_serialization.d.ts.map +1 -1
  52. package/dest/avm/serialization/bytecode_serialization.js +5 -24
  53. package/dest/avm/serialization/instruction_serialization.d.ts +48 -60
  54. package/dest/avm/serialization/instruction_serialization.d.ts.map +1 -1
  55. package/dest/avm/serialization/instruction_serialization.js +50 -63
  56. package/dest/avm/test_utils.d.ts +8 -8
  57. package/dest/avm/test_utils.d.ts.map +1 -1
  58. package/dest/avm/test_utils.js +15 -15
  59. package/dest/client/simulator.d.ts +1 -1
  60. package/dest/client/test_utils.d.ts.map +1 -1
  61. package/dest/client/test_utils.js +12 -6
  62. package/dest/client/unconstrained_execution.d.ts +2 -2
  63. package/dest/client/unconstrained_execution.d.ts.map +1 -1
  64. package/dest/client/unconstrained_execution.js +3 -3
  65. package/dest/public/enqueued_call_simulator.d.ts +43 -0
  66. package/dest/public/enqueued_call_simulator.d.ts.map +1 -0
  67. package/dest/public/enqueued_call_simulator.js +155 -0
  68. package/dest/public/enqueued_calls_processor.d.ts +44 -0
  69. package/dest/public/enqueued_calls_processor.d.ts.map +1 -0
  70. package/dest/public/enqueued_calls_processor.js +218 -0
  71. package/dest/public/execution.d.ts +4 -9
  72. package/dest/public/execution.d.ts.map +1 -1
  73. package/dest/public/execution.js +5 -10
  74. package/dest/public/executor.d.ts +3 -5
  75. package/dest/public/executor.d.ts.map +1 -1
  76. package/dest/public/executor.js +5 -9
  77. package/dest/public/hints_builder.d.ts +4 -3
  78. package/dest/public/hints_builder.d.ts.map +1 -1
  79. package/dest/public/hints_builder.js +4 -4
  80. package/dest/public/index.d.ts +3 -2
  81. package/dest/public/index.d.ts.map +1 -1
  82. package/dest/public/index.js +3 -3
  83. package/dest/public/public_db_sources.d.ts +17 -24
  84. package/dest/public/public_db_sources.d.ts.map +1 -1
  85. package/dest/public/public_db_sources.js +58 -65
  86. package/dest/public/public_kernel.d.ts +3 -9
  87. package/dest/public/public_kernel.d.ts.map +1 -1
  88. package/dest/public/public_kernel.js +13 -40
  89. package/dest/public/public_kernel_circuit_simulator.d.ts +5 -11
  90. package/dest/public/public_kernel_circuit_simulator.d.ts.map +1 -1
  91. package/dest/public/public_kernel_tail_simulator.d.ts +19 -0
  92. package/dest/public/public_kernel_tail_simulator.d.ts.map +1 -0
  93. package/dest/public/public_kernel_tail_simulator.js +45 -0
  94. package/dest/public/public_processor.d.ts +8 -5
  95. package/dest/public/public_processor.d.ts.map +1 -1
  96. package/dest/public/public_processor.js +31 -48
  97. package/dest/public/public_processor_metrics.d.ts +3 -3
  98. package/dest/public/public_processor_metrics.d.ts.map +1 -1
  99. package/dest/public/public_processor_metrics.js +1 -1
  100. package/dest/public/side_effect_trace.d.ts.map +1 -1
  101. package/dest/public/side_effect_trace.js +4 -8
  102. package/package.json +9 -9
  103. package/src/avm/avm_execution_environment.ts +1 -21
  104. package/src/avm/avm_gas.ts +30 -114
  105. package/src/avm/avm_machine_state.ts +5 -5
  106. package/src/avm/avm_memory_types.ts +31 -9
  107. package/src/avm/avm_simulator.ts +4 -5
  108. package/src/avm/bytecode_utils.ts +2 -17
  109. package/src/avm/fixtures/index.ts +12 -44
  110. package/src/avm/journal/index.ts +0 -1
  111. package/src/avm/journal/journal.ts +13 -18
  112. package/src/avm/opcodes/bitwise.ts +14 -10
  113. package/src/avm/opcodes/commitment.ts +1 -1
  114. package/src/avm/opcodes/comparators.ts +2 -2
  115. package/src/avm/opcodes/conversion.ts +19 -10
  116. package/src/avm/opcodes/environment_getters.ts +72 -99
  117. package/src/avm/opcodes/hashing.ts +47 -22
  118. package/src/avm/opcodes/index.ts +3 -0
  119. package/src/avm/opcodes/instruction_impl.ts +0 -62
  120. package/src/avm/opcodes/memory.ts +20 -6
  121. package/src/avm/opcodes/multi_scalar_mul.ts +6 -6
  122. package/src/avm/serialization/bytecode_serialization.ts +11 -33
  123. package/src/avm/serialization/instruction_serialization.ts +5 -18
  124. package/src/avm/test_utils.ts +20 -16
  125. package/src/client/test_utils.ts +36 -9
  126. package/src/client/unconstrained_execution.ts +3 -8
  127. package/src/public/enqueued_call_simulator.ts +336 -0
  128. package/src/public/enqueued_calls_processor.ts +388 -0
  129. package/src/public/execution.ts +5 -12
  130. package/src/public/executor.ts +4 -12
  131. package/src/public/hints_builder.ts +14 -12
  132. package/src/public/index.ts +3 -2
  133. package/src/public/public_db_sources.ts +62 -67
  134. package/src/public/public_kernel.ts +15 -49
  135. package/src/public/public_kernel_circuit_simulator.ts +6 -10
  136. package/src/public/public_kernel_tail_simulator.ts +106 -0
  137. package/src/public/public_processor.ts +61 -86
  138. package/src/public/public_processor_metrics.ts +3 -3
  139. package/src/public/side_effect_trace.ts +5 -12
  140. package/dest/avm/journal/host_storage.d.ts +0 -13
  141. package/dest/avm/journal/host_storage.d.ts.map +0 -1
  142. package/dest/avm/journal/host_storage.js +0 -13
  143. package/dest/avm/opcodes/context_getters.d.ts +0 -15
  144. package/dest/avm/opcodes/context_getters.d.ts.map +0 -1
  145. package/dest/avm/opcodes/context_getters.js +0 -19
  146. package/dest/public/abstract_phase_manager.d.ts +0 -93
  147. package/dest/public/abstract_phase_manager.d.ts.map +0 -1
  148. package/dest/public/abstract_phase_manager.js +0 -285
  149. package/dest/public/app_logic_phase_manager.d.ts +0 -25
  150. package/dest/public/app_logic_phase_manager.d.ts.map +0 -1
  151. package/dest/public/app_logic_phase_manager.js +0 -52
  152. package/dest/public/phase_manager_factory.d.ts +0 -18
  153. package/dest/public/phase_manager_factory.d.ts.map +0 -1
  154. package/dest/public/phase_manager_factory.js +0 -56
  155. package/dest/public/setup_phase_manager.d.ts +0 -25
  156. package/dest/public/setup_phase_manager.d.ts.map +0 -1
  157. package/dest/public/setup_phase_manager.js +0 -39
  158. package/dest/public/tail_phase_manager.d.ts +0 -23
  159. package/dest/public/tail_phase_manager.d.ts.map +0 -1
  160. package/dest/public/tail_phase_manager.js +0 -50
  161. package/dest/public/teardown_phase_manager.d.ts +0 -27
  162. package/dest/public/teardown_phase_manager.d.ts.map +0 -1
  163. package/dest/public/teardown_phase_manager.js +0 -56
  164. package/src/avm/journal/host_storage.ts +0 -14
  165. package/src/avm/opcodes/context_getters.ts +0 -23
  166. package/src/public/abstract_phase_manager.ts +0 -522
  167. package/src/public/app_logic_phase_manager.ts +0 -81
  168. package/src/public/phase_manager_factory.ts +0 -126
  169. package/src/public/setup_phase_manager.ts +0 -61
  170. package/src/public/tail_phase_manager.ts +0 -127
  171. package/src/public/teardown_phase_manager.ts +0 -86
@@ -0,0 +1,388 @@
1
+ import {
2
+ type MerkleTreeOperations,
3
+ type NestedProcessReturnValues,
4
+ type ProcessedTx,
5
+ ProvingRequestType,
6
+ type PublicExecutionRequest,
7
+ type PublicKernelMergeRequest,
8
+ PublicKernelPhase,
9
+ type PublicProvingRequest,
10
+ type SimulationError,
11
+ type Tx,
12
+ } from '@aztec/circuit-types';
13
+ import {
14
+ EnqueuedCallData,
15
+ Fr,
16
+ Gas,
17
+ type GlobalVariables,
18
+ type Header,
19
+ type KernelCircuitPublicInputs,
20
+ NESTED_RECURSIVE_PROOF_LENGTH,
21
+ type PublicCallRequest,
22
+ PublicKernelCircuitPrivateInputs,
23
+ type PublicKernelCircuitPublicInputs,
24
+ PublicKernelData,
25
+ type VMCircuitPublicInputs,
26
+ makeEmptyProof,
27
+ makeEmptyRecursiveProof,
28
+ } from '@aztec/circuits.js';
29
+ import { type DebugLogger, createDebugLogger } from '@aztec/foundation/log';
30
+ import { Timer } from '@aztec/foundation/timer';
31
+ import { ProtocolCircuitVks, getVKIndex, getVKSiblingPath } from '@aztec/noir-protocol-circuits-types';
32
+
33
+ import { inspect } from 'util';
34
+
35
+ import { EnqueuedCallSimulator } from './enqueued_call_simulator.js';
36
+ import { type PublicExecutor } from './executor.js';
37
+ import { type WorldStateDB } from './public_db_sources.js';
38
+ import { type PublicKernelCircuitSimulator } from './public_kernel_circuit_simulator.js';
39
+ import { PublicKernelTailSimulator } from './public_kernel_tail_simulator.js';
40
+
41
+ const PhaseIsRevertible: Record<PublicKernelPhase, boolean> = {
42
+ [PublicKernelPhase.SETUP]: false,
43
+ [PublicKernelPhase.APP_LOGIC]: true,
44
+ [PublicKernelPhase.TEARDOWN]: true,
45
+ };
46
+
47
+ type PublicPhaseResult = {
48
+ /** The output of the public kernel circuit simulation for this phase */
49
+ publicKernelOutput: PublicKernelCircuitPublicInputs;
50
+ /** The collection of public proving requests */
51
+ provingRequests: PublicProvingRequest[];
52
+ /** Return values of simulating complete callstack */
53
+ returnValues: NestedProcessReturnValues[];
54
+ /** Gas used during the execution this phase */
55
+ gasUsed: Gas;
56
+ /** Time spent for the execution this phase */
57
+ durationMs: number;
58
+ /** Revert reason, if any */
59
+ revertReason?: SimulationError;
60
+ };
61
+
62
+ export type ProcessedPhase = {
63
+ phase: PublicKernelPhase;
64
+ durationMs: number;
65
+ revertReason?: SimulationError;
66
+ };
67
+
68
+ export type TxPublicCallsResult = {
69
+ /** The collection of public proving requests */
70
+ provingRequests: PublicProvingRequest[];
71
+ /** The output of the public kernel tail circuit simulation for this tx */
72
+ tailKernelOutput: KernelCircuitPublicInputs;
73
+ /** Return values of simulating complete callstack */
74
+ returnValues: NestedProcessReturnValues[];
75
+ /** Gas used during the execution this tx */
76
+ gasUsed: ProcessedTx['gasUsed'];
77
+ /** Revert reason, if any */
78
+ revertReason?: SimulationError;
79
+ processedPhases: ProcessedPhase[];
80
+ };
81
+
82
+ export class EnqueuedCallsProcessor {
83
+ private log: DebugLogger;
84
+
85
+ constructor(
86
+ private publicKernelSimulator: PublicKernelCircuitSimulator,
87
+ private globalVariables: GlobalVariables,
88
+ private worldStateDB: WorldStateDB,
89
+ private enqueuedCallSimulator: EnqueuedCallSimulator,
90
+ private publicKernelTailSimulator: PublicKernelTailSimulator,
91
+ ) {
92
+ this.log = createDebugLogger(`aztec:sequencer`);
93
+ }
94
+
95
+ static create(
96
+ db: MerkleTreeOperations,
97
+ publicExecutor: PublicExecutor,
98
+ publicKernelSimulator: PublicKernelCircuitSimulator,
99
+ globalVariables: GlobalVariables,
100
+ historicalHeader: Header,
101
+ worldStateDB: WorldStateDB,
102
+ ) {
103
+ const enqueuedCallSimulator = new EnqueuedCallSimulator(
104
+ db,
105
+ publicExecutor,
106
+ publicKernelSimulator,
107
+ globalVariables,
108
+ historicalHeader,
109
+ );
110
+
111
+ const publicKernelTailSimulator = PublicKernelTailSimulator.create(db, publicKernelSimulator);
112
+
113
+ return new EnqueuedCallsProcessor(
114
+ publicKernelSimulator,
115
+ globalVariables,
116
+ worldStateDB,
117
+ enqueuedCallSimulator,
118
+ publicKernelTailSimulator,
119
+ );
120
+ }
121
+
122
+ static getExecutionRequestsByPhase(tx: Tx, phase: PublicKernelPhase): PublicExecutionRequest[] {
123
+ switch (phase) {
124
+ case PublicKernelPhase.SETUP:
125
+ return tx.getNonRevertiblePublicExecutionRequests();
126
+ case PublicKernelPhase.APP_LOGIC:
127
+ return tx.getRevertiblePublicExecutionRequests();
128
+ case PublicKernelPhase.TEARDOWN: {
129
+ const request = tx.getPublicTeardownExecutionRequest();
130
+ return request ? [request] : [];
131
+ }
132
+ default:
133
+ throw new Error(`Unknown phase: ${phase}`);
134
+ }
135
+ }
136
+
137
+ static getCallRequestsByPhase(tx: Tx, phase: PublicKernelPhase): PublicCallRequest[] {
138
+ switch (phase) {
139
+ case PublicKernelPhase.SETUP:
140
+ return tx.data.getNonRevertiblePublicCallRequests();
141
+ case PublicKernelPhase.APP_LOGIC:
142
+ return tx.data.getRevertiblePublicCallRequests();
143
+ case PublicKernelPhase.TEARDOWN: {
144
+ const request = tx.data.getTeardownPublicCallRequest();
145
+ return request ? [request] : [];
146
+ }
147
+ default:
148
+ throw new Error(`Unknown phase: ${phase}`);
149
+ }
150
+ }
151
+
152
+ async process(tx: Tx): Promise<TxPublicCallsResult> {
153
+ this.log.verbose(`Processing tx ${tx.getTxHash()}`);
154
+
155
+ const phases: PublicKernelPhase[] = [
156
+ PublicKernelPhase.SETUP,
157
+ PublicKernelPhase.APP_LOGIC,
158
+ PublicKernelPhase.TEARDOWN,
159
+ ];
160
+ const processedPhases: ProcessedPhase[] = [];
161
+ const provingRequests: PublicProvingRequest[] = [];
162
+ const gasUsed: ProcessedTx['gasUsed'] = {};
163
+ let publicKernelOutput = tx.data.toPublicKernelCircuitPublicInputs();
164
+ let isFromPrivate = true;
165
+ let returnValues: NestedProcessReturnValues[] = [];
166
+ let revertReason: SimulationError | undefined;
167
+ for (let i = 0; i < phases.length; i++) {
168
+ const phase = phases[i];
169
+ const callRequests = EnqueuedCallsProcessor.getCallRequestsByPhase(tx, phase);
170
+ if (callRequests.length) {
171
+ const executionRequests = EnqueuedCallsProcessor.getExecutionRequestsByPhase(tx, phase);
172
+ const result = await this.processPhase(
173
+ tx,
174
+ callRequests,
175
+ executionRequests,
176
+ publicKernelOutput,
177
+ phase,
178
+ isFromPrivate,
179
+ ).catch(async err => {
180
+ await this.worldStateDB.rollbackToCommit();
181
+ throw err;
182
+ });
183
+
184
+ publicKernelOutput = result.publicKernelOutput;
185
+ isFromPrivate = false;
186
+
187
+ provingRequests.push(...result.provingRequests);
188
+ if (phase === PublicKernelPhase.APP_LOGIC) {
189
+ returnValues = result.returnValues;
190
+ }
191
+
192
+ gasUsed[phase] = result.gasUsed;
193
+
194
+ processedPhases.push({
195
+ phase,
196
+ durationMs: result.durationMs,
197
+ revertReason: result.revertReason,
198
+ });
199
+
200
+ revertReason ??= result.revertReason;
201
+ }
202
+ }
203
+
204
+ const { output: tailKernelOutput, provingRequest } = await this.publicKernelTailSimulator
205
+ .simulate(publicKernelOutput)
206
+ .catch(
207
+ // the abstract phase manager throws if simulation gives error in non-revertible phase
208
+ async err => {
209
+ await this.worldStateDB.rollbackToCommit();
210
+ throw err;
211
+ },
212
+ );
213
+ provingRequests.push(provingRequest);
214
+
215
+ return {
216
+ provingRequests: provingRequests,
217
+ tailKernelOutput,
218
+ returnValues,
219
+ gasUsed,
220
+ processedPhases,
221
+ revertReason,
222
+ };
223
+ }
224
+
225
+ private async processPhase(
226
+ tx: Tx,
227
+ callRequests: PublicCallRequest[],
228
+ executionRequests: PublicExecutionRequest[],
229
+ previousPublicKernelOutput: PublicKernelCircuitPublicInputs,
230
+ phase: PublicKernelPhase,
231
+ isFromPrivate: boolean,
232
+ ): Promise<PublicPhaseResult> {
233
+ this.log.debug(`Beginning processing in phase ${PublicKernelPhase[phase]} for tx ${tx.getTxHash()}`);
234
+
235
+ const phaseTimer = new Timer();
236
+ const provingRequests: PublicProvingRequest[] = [];
237
+ const returnValues: NestedProcessReturnValues[] = [];
238
+ let publicKernelOutput = previousPublicKernelOutput;
239
+ let gasUsed = Gas.empty();
240
+ let revertReason: SimulationError | undefined;
241
+ for (let i = callRequests.length - 1; i >= 0 && !revertReason; i--) {
242
+ const callRequest = callRequests[i];
243
+ const executionRequest = executionRequests[i];
244
+
245
+ // add new contracts to the contracts db so that their functions may be found and called
246
+ // TODO(#4073): This is catching only private deployments, when we add public ones, we'll
247
+ // have to capture contracts emitted in that phase as well.
248
+ // TODO(@spalladino): Should we allow emitting contracts in the fee preparation phase?
249
+ // TODO(#6464): Should we allow emitting contracts in the private setup phase?
250
+ // if so, this should only add contracts that were deployed during private app logic.
251
+ await this.worldStateDB.addNewContracts(tx);
252
+
253
+ const availableGas = this.getAvailableGas(tx, publicKernelOutput, phase);
254
+ const transactionFee = this.getTransactionFee(tx, publicKernelOutput, phase);
255
+
256
+ const enqueuedCallResult = await this.enqueuedCallSimulator.simulate(
257
+ callRequest,
258
+ executionRequest,
259
+ tx,
260
+ publicKernelOutput,
261
+ availableGas,
262
+ transactionFee,
263
+ phase,
264
+ );
265
+
266
+ if (enqueuedCallResult.revertReason && !PhaseIsRevertible[phase]) {
267
+ this.log.debug(
268
+ `Simulation error on ${executionRequest.contractAddress.toString()}:${
269
+ executionRequest.callContext.functionSelector
270
+ } with reason: ${enqueuedCallResult.revertReason}`,
271
+ );
272
+ throw enqueuedCallResult.revertReason;
273
+ }
274
+
275
+ provingRequests.push(...enqueuedCallResult.provingRequests);
276
+ returnValues.push(enqueuedCallResult.returnValues);
277
+ gasUsed = gasUsed.add(enqueuedCallResult.gasUsed);
278
+ revertReason ??= enqueuedCallResult.revertReason;
279
+
280
+ if (revertReason) {
281
+ // TODO(#6464): Should we allow emitting contracts in the private setup phase?
282
+ // if so, this is removing contracts deployed in private setup
283
+ await this.worldStateDB.removeNewContracts(tx);
284
+ await this.worldStateDB.rollbackToCheckpoint();
285
+ tx.filterRevertedLogs(publicKernelOutput);
286
+ } else {
287
+ // TODO(#6470): we should be adding contracts deployed in those logs to the publicContractsDB
288
+ tx.unencryptedLogs.addFunctionLogs([enqueuedCallResult.newUnencryptedLogs]);
289
+ }
290
+
291
+ const { output, provingRequest } = await this.runMergeKernelCircuit(
292
+ publicKernelOutput,
293
+ enqueuedCallResult.kernelOutput,
294
+ isFromPrivate,
295
+ );
296
+ publicKernelOutput = output;
297
+ isFromPrivate = false;
298
+ provingRequests.push(provingRequest);
299
+ }
300
+
301
+ if (phase === PublicKernelPhase.SETUP) {
302
+ await this.worldStateDB.checkpoint();
303
+ }
304
+
305
+ return {
306
+ publicKernelOutput,
307
+ provingRequests,
308
+ durationMs: phaseTimer.ms(),
309
+ gasUsed,
310
+ returnValues: revertReason ? [] : returnValues,
311
+ revertReason,
312
+ };
313
+ }
314
+
315
+ private getAvailableGas(
316
+ tx: Tx,
317
+ previousPublicKernelOutput: PublicKernelCircuitPublicInputs,
318
+ phase: PublicKernelPhase,
319
+ ) {
320
+ if (phase === PublicKernelPhase.TEARDOWN) {
321
+ return tx.data.constants.txContext.gasSettings.getTeardownLimits();
322
+ } else {
323
+ return tx.data.constants.txContext.gasSettings
324
+ .getLimits() // No need to subtract teardown limits since they are already included in end.gasUsed
325
+ .sub(previousPublicKernelOutput.end.gasUsed)
326
+ .sub(previousPublicKernelOutput.endNonRevertibleData.gasUsed);
327
+ }
328
+ }
329
+
330
+ private getTransactionFee(
331
+ tx: Tx,
332
+ previousPublicKernelOutput: PublicKernelCircuitPublicInputs,
333
+ phase: PublicKernelPhase,
334
+ ): Fr {
335
+ if (phase !== PublicKernelPhase.TEARDOWN) {
336
+ return Fr.ZERO;
337
+ } else {
338
+ const gasSettings = tx.data.constants.txContext.gasSettings;
339
+ const gasFees = this.globalVariables.gasFees;
340
+ // No need to add teardown limits since they are already included in end.gasUsed
341
+ const gasUsed = previousPublicKernelOutput.end.gasUsed.add(
342
+ previousPublicKernelOutput.endNonRevertibleData.gasUsed,
343
+ );
344
+ const txFee = gasSettings.inclusionFee.add(gasUsed.computeFee(gasFees));
345
+ this.log.debug(`Computed tx fee`, { txFee, gasUsed: inspect(gasUsed), gasFees: inspect(gasFees) });
346
+ return txFee;
347
+ }
348
+ }
349
+
350
+ private async runMergeKernelCircuit(
351
+ previousOutput: PublicKernelCircuitPublicInputs,
352
+ enqueuedCallData: VMCircuitPublicInputs,
353
+ isFromPrivate: boolean,
354
+ ): Promise<{ output: PublicKernelCircuitPublicInputs; provingRequest: PublicKernelMergeRequest }> {
355
+ const previousKernel = this.getPreviousKernelData(previousOutput, isFromPrivate);
356
+
357
+ // The proof is not used in simulation.
358
+ const vmProof = makeEmptyProof();
359
+ const callData = new EnqueuedCallData(enqueuedCallData, vmProof);
360
+
361
+ const inputs = new PublicKernelCircuitPrivateInputs(previousKernel, callData);
362
+
363
+ const output = await this.publicKernelSimulator.publicKernelCircuitMerge(inputs);
364
+
365
+ const provingRequest: PublicKernelMergeRequest = {
366
+ type: ProvingRequestType.PUBLIC_KERNEL_MERGE,
367
+ inputs,
368
+ };
369
+
370
+ return { output, provingRequest };
371
+ }
372
+
373
+ private getPreviousKernelData(
374
+ previousOutput: PublicKernelCircuitPublicInputs,
375
+ isFromPrivate: boolean,
376
+ ): PublicKernelData {
377
+ // The proof is not used in simulation.
378
+ const proof = makeEmptyRecursiveProof(NESTED_RECURSIVE_PROOF_LENGTH);
379
+
380
+ const vk = isFromPrivate
381
+ ? ProtocolCircuitVks.PrivateKernelTailToPublicArtifact
382
+ : ProtocolCircuitVks.PublicKernelMergeArtifact;
383
+ const vkIndex = getVKIndex(vk);
384
+ const siblingPath = getVKSiblingPath(vkIndex);
385
+
386
+ return new PublicKernelData(previousOutput, proof, vk, vkIndex, siblingPath);
387
+ }
388
+ }
@@ -13,8 +13,8 @@ import {
13
13
  type LogHash,
14
14
  type NoteHash,
15
15
  type Nullifier,
16
- PublicCallRequest,
17
16
  PublicCallStackItemCompressed,
17
+ PublicInnerCallRequest,
18
18
  type ReadRequest,
19
19
  RevertCode,
20
20
  type TreeLeafReadRequest,
@@ -89,7 +89,7 @@ export interface PublicExecutionResult {
89
89
  // TODO(dbanks12): add contract instance read requests
90
90
 
91
91
  /** The requests to call public functions made by this call. */
92
- publicCallRequests: PublicCallRequest[];
92
+ publicCallRequests: PublicInnerCallRequest[];
93
93
  /** The results of nested calls. */
94
94
  nestedExecutions: this[];
95
95
 
@@ -100,15 +100,8 @@ export interface PublicExecutionResult {
100
100
  functionName: string;
101
101
  }
102
102
 
103
- /**
104
- * Returns if the input is a public execution result and not just a public execution.
105
- * @param input - Public execution or public execution result.
106
- * @returns Whether the input is a public execution result and not just a public execution.
107
- */
108
- export function isPublicExecutionResult(
109
- input: PublicExecutionRequest | PublicExecutionResult,
110
- ): input is PublicExecutionResult {
111
- return 'executionRequest' in input && input.executionRequest !== undefined;
103
+ export function collectExecutionResults(result: PublicExecutionResult): PublicExecutionResult[] {
104
+ return [result, ...result.nestedExecutions.map(collectExecutionResults)].flat();
112
105
  }
113
106
 
114
107
  /**
@@ -146,5 +139,5 @@ export function resultToPublicCallRequest(result: PublicExecutionResult) {
146
139
  Gas.from(result.startGasLeft),
147
140
  Gas.from(result.endGasLeft),
148
141
  );
149
- return new PublicCallRequest(item, result.startSideEffectCounter.toNumber());
142
+ return new PublicInnerCallRequest(item, result.startSideEffectCounter.toNumber());
150
143
  }
@@ -9,11 +9,10 @@ import { AvmContext } from '../avm/avm_context.js';
9
9
  import { AvmExecutionEnvironment } from '../avm/avm_execution_environment.js';
10
10
  import { AvmMachineState } from '../avm/avm_machine_state.js';
11
11
  import { AvmSimulator } from '../avm/avm_simulator.js';
12
- import { HostStorage } from '../avm/journal/host_storage.js';
13
12
  import { AvmPersistableStateManager } from '../avm/journal/index.js';
14
- import { type CommitmentsDB, type PublicContractsDB, type PublicStateDB } from './db_interfaces.js';
15
13
  import { type PublicExecutionResult } from './execution.js';
16
14
  import { ExecutorMetrics } from './executor_metrics.js';
15
+ import { type WorldStateDB } from './public_db_sources.js';
17
16
  import { PublicSideEffectTrace } from './side_effect_trace.js';
18
17
 
19
18
  /**
@@ -22,13 +21,7 @@ import { PublicSideEffectTrace } from './side_effect_trace.js';
22
21
  export class PublicExecutor {
23
22
  metrics: ExecutorMetrics;
24
23
 
25
- constructor(
26
- private readonly publicStorageDB: PublicStateDB,
27
- private readonly contractsDb: PublicContractsDB,
28
- private readonly commitmentsDb: CommitmentsDB,
29
- private readonly header: Header,
30
- client: TelemetryClient,
31
- ) {
24
+ constructor(private readonly worldStateDB: WorldStateDB, private readonly header: Header, client: TelemetryClient) {
32
25
  this.metrics = new ExecutorMetrics(client, 'PublicExecutor');
33
26
  }
34
27
 
@@ -56,15 +49,14 @@ export class PublicExecutor {
56
49
  ): Promise<PublicExecutionResult> {
57
50
  const address = executionRequest.contractAddress;
58
51
  const selector = executionRequest.callContext.functionSelector;
59
- const fnName = (await this.contractsDb.getDebugFunctionName(address, selector)) ?? `${address}:${selector}`;
52
+ const fnName = (await this.worldStateDB.getDebugFunctionName(address, selector)) ?? `${address}:${selector}`;
60
53
 
61
54
  PublicExecutor.log.verbose(`[AVM] Executing public external function ${fnName}.`);
62
55
  const timer = new Timer();
63
56
 
64
- const hostStorage = new HostStorage(this.publicStorageDB, this.contractsDb, this.commitmentsDb);
65
57
  const trace = new PublicSideEffectTrace(startSideEffectCounter);
66
58
  const avmPersistableState = AvmPersistableStateManager.newWithPendingSiloedNullifiers(
67
- hostStorage,
59
+ this.worldStateDB,
68
60
  trace,
69
61
  pendingSiloedNullifiers.map(n => n.value),
70
62
  );
@@ -13,6 +13,7 @@ import {
13
13
  NOTE_HASH_TREE_HEIGHT,
14
14
  NULLIFIER_TREE_HEIGHT,
15
15
  type Nullifier,
16
+ type NullifierLeafPreimage,
16
17
  PUBLIC_DATA_TREE_HEIGHT,
17
18
  type PublicDataRead,
18
19
  type PublicDataTreeLeafPreimage,
@@ -27,6 +28,7 @@ import {
27
28
  } from '@aztec/circuits.js';
28
29
  import { makeTuple } from '@aztec/foundation/array';
29
30
  import { type Tuple } from '@aztec/foundation/serialize';
31
+ import { type IndexedTreeLeafPreimage } from '@aztec/foundation/trees';
30
32
  import { type MerkleTreeOperations } from '@aztec/world-state';
31
33
 
32
34
  export class HintsBuilder {
@@ -112,7 +114,8 @@ export class HintsBuilder {
112
114
  throw new Error(`Nullifier ${nullifier.toBigInt()} already exists in the tree.`);
113
115
  }
114
116
 
115
- return this.getMembershipWitnessWithPreimage<typeof NULLIFIER_TREE_HEIGHT>(
117
+ // Should find a way to stop casting IndexedTreeLeafPreimage as NullifierLeafPreimage
118
+ return this.getMembershipWitnessWithPreimage<typeof NULLIFIER_TREE_HEIGHT, NullifierLeafPreimage>(
116
119
  MerkleTreeId.NULLIFIER_TREE,
117
120
  NULLIFIER_TREE_HEIGHT,
118
121
  index,
@@ -125,23 +128,22 @@ export class HintsBuilder {
125
128
  throw new Error(`Cannot find the previous value index for public data ${leafSlot}.`);
126
129
  }
127
130
 
128
- const { membershipWitness, leafPreimage } = await this.getMembershipWitnessWithPreimage<
129
- typeof PUBLIC_DATA_TREE_HEIGHT
130
- >(MerkleTreeId.PUBLIC_DATA_TREE, PUBLIC_DATA_TREE_HEIGHT, res.index);
131
-
132
131
  // Should find a way to stop casting IndexedTreeLeafPreimage as PublicDataTreeLeafPreimage everywhere.
133
- return { membershipWitness, leafPreimage: leafPreimage as PublicDataTreeLeafPreimage };
132
+ return this.getMembershipWitnessWithPreimage<typeof PUBLIC_DATA_TREE_HEIGHT, PublicDataTreeLeafPreimage>(
133
+ MerkleTreeId.PUBLIC_DATA_TREE,
134
+ PUBLIC_DATA_TREE_HEIGHT,
135
+ res.index,
136
+ );
134
137
  }
135
138
 
136
- private async getMembershipWitnessWithPreimage<TREE_HEIGHT extends number>(
137
- treeId: IndexedTreeId,
138
- treeHeight: TREE_HEIGHT,
139
- index: bigint,
140
- ) {
139
+ private async getMembershipWitnessWithPreimage<
140
+ TREE_HEIGHT extends number,
141
+ LEAF_PREIMAGE extends IndexedTreeLeafPreimage = IndexedTreeLeafPreimage,
142
+ >(treeId: IndexedTreeId, treeHeight: TREE_HEIGHT, index: bigint) {
141
143
  const siblingPath = await this.db.getSiblingPath<TREE_HEIGHT>(treeId, index);
142
144
  const membershipWitness = new MembershipWitness(treeHeight, index, siblingPath.toTuple());
143
145
 
144
- const leafPreimage = await this.db.getLeafPreimage(treeId, index);
146
+ const leafPreimage = (await this.db.getLeafPreimage(treeId, index)) as LEAF_PREIMAGE;
145
147
  if (!leafPreimage) {
146
148
  throw new Error(`Cannot find the leaf preimage for tree ${treeId} at index ${index}.`);
147
149
  }
@@ -1,6 +1,6 @@
1
- export * from './abstract_phase_manager.js';
2
1
  export * from './db_interfaces.js';
3
- export { isPublicExecutionResult, type PublicExecutionResult } from './execution.js';
2
+ export * from './enqueued_calls_processor.js';
3
+ export { type PublicExecutionResult } from './execution.js';
4
4
  export { PublicExecutor } from './executor.js';
5
5
  export * from './fee_payment.js';
6
6
  export { HintsBuilder } from './hints_builder.js';
@@ -8,3 +8,4 @@ export * from './public_db_sources.js';
8
8
  export * from './public_kernel.js';
9
9
  export * from './public_kernel_circuit_simulator.js';
10
10
  export { PublicProcessor, PublicProcessorFactory } from './public_processor.js';
11
+ export { PublicSideEffectTrace } from './side_effect_trace.js';