@aztec/simulator 5.0.0-private.20260319 → 5.0.0-rc.2

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 (106) hide show
  1. package/dest/client.d.ts +1 -3
  2. package/dest/client.d.ts.map +1 -1
  3. package/dest/client.js +0 -2
  4. package/dest/private/acvm_wasm.d.ts +1 -1
  5. package/dest/private/acvm_wasm.d.ts.map +1 -1
  6. package/dest/private/acvm_wasm.js +3 -1
  7. package/dest/private/circuit_recording/circuit_recorder.d.ts +36 -23
  8. package/dest/private/circuit_recording/circuit_recorder.d.ts.map +1 -1
  9. package/dest/private/circuit_recording/circuit_recorder.js +65 -69
  10. package/dest/private/circuit_recording/file_circuit_recorder.d.ts +7 -19
  11. package/dest/private/circuit_recording/file_circuit_recorder.d.ts.map +1 -1
  12. package/dest/private/circuit_recording/file_circuit_recorder.js +38 -42
  13. package/dest/private/circuit_recording/simulator_recorder_wrapper.d.ts +1 -1
  14. package/dest/private/circuit_recording/simulator_recorder_wrapper.d.ts.map +1 -1
  15. package/dest/private/circuit_recording/simulator_recorder_wrapper.js +11 -14
  16. package/dest/public/avm/avm_simulator.js +1 -1
  17. package/dest/public/avm/calldata.d.ts +1 -1
  18. package/dest/public/avm/calldata.d.ts.map +1 -1
  19. package/dest/public/avm/calldata.js +3 -2
  20. package/dest/public/avm/fixtures/base_avm_simulation_tester.d.ts +2 -1
  21. package/dest/public/avm/fixtures/base_avm_simulation_tester.d.ts.map +1 -1
  22. package/dest/public/avm/fixtures/base_avm_simulation_tester.js +18 -3
  23. package/dest/public/avm/fixtures/utils.d.ts +1 -1
  24. package/dest/public/avm/fixtures/utils.d.ts.map +1 -1
  25. package/dest/public/avm/fixtures/utils.js +4 -1
  26. package/dest/public/avm/opcodes/contract.d.ts +3 -2
  27. package/dest/public/avm/opcodes/contract.d.ts.map +1 -1
  28. package/dest/public/avm/opcodes/contract.js +5 -1
  29. package/dest/public/avm/opcodes/ec_add.d.ts +2 -4
  30. package/dest/public/avm/opcodes/ec_add.d.ts.map +1 -1
  31. package/dest/public/avm/opcodes/ec_add.js +13 -27
  32. package/dest/public/contracts_db_checkpoint.d.ts +2 -2
  33. package/dest/public/contracts_db_checkpoint.d.ts.map +1 -1
  34. package/dest/public/contracts_db_checkpoint.js +1 -1
  35. package/dest/public/fixtures/amm_test.js +2 -2
  36. package/dest/public/fixtures/bulk_test.d.ts +1 -1
  37. package/dest/public/fixtures/bulk_test.d.ts.map +1 -1
  38. package/dest/public/fixtures/bulk_test.js +33 -6
  39. package/dest/public/fixtures/custom_bytecode_tester.d.ts +1 -1
  40. package/dest/public/fixtures/custom_bytecode_tester.d.ts.map +1 -1
  41. package/dest/public/fixtures/custom_bytecode_tester.js +2 -2
  42. package/dest/public/fixtures/custom_bytecode_tests.d.ts +3 -1
  43. package/dest/public/fixtures/custom_bytecode_tests.d.ts.map +1 -1
  44. package/dest/public/fixtures/custom_bytecode_tests.js +61 -1
  45. package/dest/public/fixtures/opcode_spammer.d.ts +1 -1
  46. package/dest/public/fixtures/opcode_spammer.d.ts.map +1 -1
  47. package/dest/public/fixtures/opcode_spammer.js +2 -10
  48. package/dest/public/fixtures/public_tx_simulation_tester.d.ts +1 -1
  49. package/dest/public/fixtures/public_tx_simulation_tester.d.ts.map +1 -1
  50. package/dest/public/fixtures/public_tx_simulation_tester.js +4 -2
  51. package/dest/public/fixtures/token_test.js +3 -3
  52. package/dest/public/fixtures/utils.d.ts +1 -1
  53. package/dest/public/fixtures/utils.d.ts.map +1 -1
  54. package/dest/public/fixtures/utils.js +16 -15
  55. package/dest/public/hinting_db_sources.d.ts +1 -1
  56. package/dest/public/hinting_db_sources.d.ts.map +1 -1
  57. package/dest/public/hinting_db_sources.js +1 -1
  58. package/dest/public/public_db_sources.d.ts +6 -3
  59. package/dest/public/public_db_sources.d.ts.map +1 -1
  60. package/dest/public/public_db_sources.js +16 -10
  61. package/dest/public/public_processor/public_processor.d.ts +4 -3
  62. package/dest/public/public_processor/public_processor.d.ts.map +1 -1
  63. package/dest/public/public_processor/public_processor.js +78 -34
  64. package/dest/public/public_processor/public_processor_metrics.d.ts +4 -1
  65. package/dest/public/public_processor/public_processor_metrics.d.ts.map +1 -1
  66. package/dest/public/public_processor/public_processor_metrics.js +8 -0
  67. package/dest/public/public_tx_simulator/contract_provider_for_cpp.d.ts +1 -1
  68. package/dest/public/public_tx_simulator/contract_provider_for_cpp.d.ts.map +1 -1
  69. package/dest/public/public_tx_simulator/contract_provider_for_cpp.js +5 -4
  70. package/dest/public/public_tx_simulator/public_tx_context.d.ts +7 -3
  71. package/dest/public/public_tx_simulator/public_tx_context.d.ts.map +1 -1
  72. package/dest/public/public_tx_simulator/public_tx_context.js +8 -10
  73. package/dest/public/public_tx_simulator/public_tx_simulator.d.ts +6 -2
  74. package/dest/public/public_tx_simulator/public_tx_simulator.d.ts.map +1 -1
  75. package/dest/public/public_tx_simulator/public_tx_simulator.js +12 -7
  76. package/dest/public/state_manager/state_manager.js +1 -1
  77. package/package.json +16 -15
  78. package/src/client.ts +0 -2
  79. package/src/private/acvm_wasm.ts +4 -1
  80. package/src/private/circuit_recording/circuit_recorder.ts +84 -78
  81. package/src/private/circuit_recording/file_circuit_recorder.ts +38 -48
  82. package/src/private/circuit_recording/simulator_recorder_wrapper.ts +9 -15
  83. package/src/public/avm/avm_simulator.ts +1 -1
  84. package/src/public/avm/calldata.ts +3 -2
  85. package/src/public/avm/fixtures/base_avm_simulation_tester.ts +23 -3
  86. package/src/public/avm/fixtures/utils.ts +4 -1
  87. package/src/public/avm/opcodes/contract.ts +5 -1
  88. package/src/public/avm/opcodes/ec_add.ts +12 -31
  89. package/src/public/avm/opcodes/external_calls.ts +1 -1
  90. package/src/public/contracts_db_checkpoint.ts +1 -1
  91. package/src/public/fixtures/amm_test.ts +2 -2
  92. package/src/public/fixtures/bulk_test.ts +31 -6
  93. package/src/public/fixtures/custom_bytecode_tester.ts +2 -2
  94. package/src/public/fixtures/custom_bytecode_tests.ts +139 -1
  95. package/src/public/fixtures/opcode_spammer.ts +4 -8
  96. package/src/public/fixtures/public_tx_simulation_tester.ts +4 -10
  97. package/src/public/fixtures/token_test.ts +3 -3
  98. package/src/public/fixtures/utils.ts +18 -20
  99. package/src/public/hinting_db_sources.ts +1 -0
  100. package/src/public/public_db_sources.ts +21 -14
  101. package/src/public/public_processor/public_processor.ts +98 -41
  102. package/src/public/public_processor/public_processor_metrics.ts +12 -0
  103. package/src/public/public_tx_simulator/contract_provider_for_cpp.ts +5 -4
  104. package/src/public/public_tx_simulator/public_tx_context.ts +8 -10
  105. package/src/public/public_tx_simulator/public_tx_simulator.ts +11 -7
  106. package/src/public/state_manager/state_manager.ts +1 -1
package/src/client.ts CHANGED
@@ -1,6 +1,4 @@
1
1
  export * from './private/acvm/index.js';
2
2
  export { WASMSimulator } from './private/acvm_wasm.js';
3
- export { SimulatorRecorderWrapper } from './private/circuit_recording/simulator_recorder_wrapper.js';
4
- export { MemoryCircuitRecorder } from './private/circuit_recording/memory_circuit_recorder.js';
5
3
  export { type CircuitSimulator, type DecodedError } from './private/circuit_simulator.js';
6
4
  export * from './common/index.js';
@@ -10,6 +10,8 @@ import type { ACVMWitness } from './acvm/acvm_types.js';
10
10
  import type { ACVMSuccess } from './acvm_native.js';
11
11
  import { type CircuitSimulator, enrichNoirError } from './circuit_simulator.js';
12
12
 
13
+ let wasmInitPromise: Promise<unknown> | undefined;
14
+
13
15
  export class WASMSimulator implements CircuitSimulator {
14
16
  protected log: Logger;
15
17
 
@@ -23,7 +25,8 @@ export class WASMSimulator implements CircuitSimulator {
23
25
  // is a no-op.
24
26
  if (typeof initAbi === 'function') {
25
27
  /** @ts-expect-error The node bundle doesn't include these default imports, so TS complains */
26
- await Promise.all([initAbi(), initACVM()]);
28
+ wasmInitPromise ??= Promise.all([initAbi(), initACVM()]);
29
+ await wasmInitPromise;
27
30
  }
28
31
  }
29
32
 
@@ -3,6 +3,8 @@ import { type Logger, type LoggerBindings, resolveLogger } from '@aztec/foundati
3
3
  import { Timer } from '@aztec/foundation/timer';
4
4
  import type { ForeignCallHandler, ForeignCallInput, ForeignCallOutput } from '@aztec/noir-acvm_js';
5
5
 
6
+ import { AsyncLocalStorage } from 'node:async_hooks';
7
+
6
8
  import type { ACIRCallback } from '../acvm/acvm.js';
7
9
  import type { ACVMWitness } from '../acvm/acvm_types.js';
8
10
 
@@ -43,10 +45,23 @@ export class CircuitRecording {
43
45
  }
44
46
  }
45
47
 
48
+ /** Inputs needed to open a recording for a single circuit execution. */
49
+ export type RecordingMetadata = {
50
+ input: ACVMWitness;
51
+ bytecode: Buffer;
52
+ circuitName: string;
53
+ functionName: string;
54
+ };
55
+
46
56
  /**
47
57
  * Class responsible for recording circuit inputs necessary to replay the circuit. These inputs are the initial witness
48
58
  * map and the oracle calls made during the circuit execution/witness generation.
49
59
  *
60
+ * The active recording for an execution lives in `AsyncLocalStorage`, so each (possibly nested) circuit execution owns
61
+ * its own recording and concurrent or re-entrant executions cannot corrupt one another's state. Nested executions
62
+ * (`aztec_prv_callPrivateFunction`, utility calls) re-enter {@link record}, which links the child to the recording
63
+ * active in the enclosing async context and lets ALS restore the parent automatically when the child completes.
64
+ *
50
65
  * Example recording object:
51
66
  * ```json
52
67
  * {
@@ -91,37 +106,44 @@ export class CircuitRecording {
91
106
  export class CircuitRecorder {
92
107
  protected readonly logger: Logger;
93
108
 
94
- protected recording?: CircuitRecording;
95
-
96
- private stackDepth: number = 0;
97
- private newCircuit: boolean = true;
109
+ readonly #recordings = new AsyncLocalStorage<CircuitRecording>();
98
110
 
99
111
  protected constructor(loggerOrBindings?: Logger | LoggerBindings) {
100
112
  this.logger = resolveLogger('simulator:acvm:recording', loggerOrBindings);
101
113
  }
102
114
 
103
115
  /**
104
- * Initializes a new circuit recording session.
105
- * @param recordDir - Directory to store the recording
106
- * @param input - Circuit input witness
107
- * @param circuitBytecode - Compiled circuit bytecode
108
- * @param circuitName - Name of the circuit
109
- * @param functionName - Name of the circuit function (defaults to 'main'). This is meaningful only for
110
- * contracts as protocol circuits artifacts always contain a single entrypoint function called 'main'.
116
+ * Records a single circuit execution. Opens a recording for the circuit (linked as a child of the recording active
117
+ * in the current async context, if any), runs `fn` within that recording's context, and finalizes it. The recording
118
+ * is returned alongside the result so callers can derive per-circuit stats (e.g. oracle timings).
119
+ *
120
+ * Recorder bookkeeping never alters execution: if `fn` throws, the error is attached to the recording and re-thrown
121
+ * unchanged.
122
+ * @param metadata - Identifies the circuit and its initial witness.
123
+ * @param fn - Runs the circuit execution; its oracle calls are recorded into this recording.
111
124
  */
112
- start(input: ACVMWitness, circuitBytecode: Buffer, circuitName: string, functionName: string): Promise<void> {
113
- if (this.newCircuit) {
114
- const parentRef = this.recording;
115
- this.recording = new CircuitRecording(
116
- circuitName,
117
- functionName,
118
- sha512(circuitBytecode).toString('hex'),
119
- Object.fromEntries(input),
120
- );
121
- this.recording.setParent(parentRef);
122
- }
125
+ record<T>(metadata: RecordingMetadata, fn: () => Promise<T>): Promise<{ result: T; recording: CircuitRecording }> {
126
+ const parent = this.#recordings.getStore();
127
+ const recording = new CircuitRecording(
128
+ metadata.circuitName,
129
+ metadata.functionName,
130
+ sha512(metadata.bytecode).toString('hex'),
131
+ Object.fromEntries(metadata.input),
132
+ );
133
+ recording.setParent(parent);
123
134
 
124
- return Promise.resolve();
135
+ return this.#recordings.run(recording, async () => {
136
+ await this.onStart(recording);
137
+ try {
138
+ const result = await fn();
139
+ await this.onFinish(recording);
140
+ return { result, recording };
141
+ } catch (error) {
142
+ recording.error = JSON.stringify(error);
143
+ await this.onError(recording, error);
144
+ throw error;
145
+ }
146
+ });
125
147
  }
126
148
 
127
149
  /**
@@ -147,7 +169,9 @@ export class CircuitRecorder {
147
169
  }
148
170
 
149
171
  /**
150
- * Wraps a user circuit callback to record all oracle calls.
172
+ * Wraps a user circuit callback to record all oracle calls. A nested circuit entered via an oracle (e.g.
173
+ * `aztec_prv_callPrivateFunction`) re-enters {@link record}, so its own oracle calls land on the child recording and
174
+ * this circuit's calls (including the entering oracle call itself) land on this recording once the child completes.
151
175
  * @param callback - The original circuit callback.
152
176
  * @returns A wrapped callback that records all oracle interactions which is to be provided to the ACVM.
153
177
  */
@@ -161,38 +185,16 @@ export class CircuitRecorder {
161
185
  throw new Error(`Oracle method ${name} not found when setting up recording callback`);
162
186
  }
163
187
 
164
- const isExternalCall = (name as keyof ACIRCallback) === 'aztec_prv_callPrivateFunction';
165
-
166
188
  recordingCallback[name as keyof ACIRCallback] = (...args: ForeignCallInput[]): ReturnType<typeof fn> => {
167
189
  const timer = new Timer();
168
- // If we're entering another circuit via `aztec_prv_callPrivateFunction`, we increase the stack depth and set the
169
- // newCircuit variable to ensure we are creating a new recording object.
170
- if (isExternalCall) {
171
- this.stackDepth++;
172
- this.newCircuit = true;
173
- }
174
190
  const result = fn.call(callback, ...args);
175
191
  if (result instanceof Promise) {
176
192
  return result.then(async r => {
177
- // Once we leave the nested circuit, we decrease the stack depth and set newCircuit to false
178
- // so that the parent circuit continues with its existing recording
179
- // Note: recording restoration is handled by finish()
180
- if (isExternalCall) {
181
- this.stackDepth--;
182
- this.newCircuit = false;
183
- }
184
- await this.recordCall(name, args, r, timer.ms(), this.stackDepth);
193
+ await this.recordCall(name, args, r, timer.ms());
185
194
  return r;
186
195
  }) as ReturnType<typeof fn>;
187
196
  }
188
- // Once we leave the nested circuit, we decrease the stack depth and set newCircuit to false
189
- // so that the parent circuit continues with its existing recording
190
- // Note: recording restoration is handled by finish()
191
- if (isExternalCall) {
192
- this.stackDepth--;
193
- this.newCircuit = false;
194
- }
195
- void this.recordCall(name, args, result, timer.ms(), this.stackDepth);
197
+ void this.recordCall(name, args, result, timer.ms());
196
198
  return result;
197
199
  };
198
200
  }
@@ -209,55 +211,59 @@ export class CircuitRecorder {
209
211
  return async (name: string, inputs: ForeignCallInput[]): Promise<ForeignCallOutput[]> => {
210
212
  const timer = new Timer();
211
213
  const result = await callback(name, inputs);
212
- await this.recordCall(name, inputs, result, timer.ms(), 0);
214
+ await this.recordCall(name, inputs, result, timer.ms());
213
215
  return result;
214
216
  };
215
217
  }
216
218
 
217
219
  /**
218
- * Records a single oracle/foreign call with its inputs and outputs.
220
+ * Records a single oracle/foreign call with its inputs and outputs against the recording active in the current
221
+ * async context.
219
222
  * @param name - Name of the call
220
223
  * @param inputs - Input arguments
221
224
  * @param outputs - Output results
222
225
  */
223
- recordCall(name: string, inputs: unknown[], outputs: unknown, time: number, stackDepth: number): Promise<OracleCall> {
226
+ recordCall(name: string, inputs: unknown[], outputs: unknown, time: number): Promise<OracleCall> {
227
+ const recording = this.#recordings.getStore();
224
228
  const entry = {
225
229
  name,
226
230
  inputs,
227
231
  outputs,
228
232
  time,
229
- stackDepth,
233
+ stackDepth: depthOf(recording),
230
234
  };
231
- this.recording!.oracleCalls.push(entry);
235
+ // Outside any active recording context (e.g. a stray call after the scope closed, or a direct unit-test call)
236
+ // there is nowhere to record; return the entry without throwing into the execution path.
237
+ recording?.oracleCalls.push(entry);
232
238
  return Promise.resolve(entry);
233
239
  }
234
240
 
235
- /**
236
- * Finalizes the recording by resetting the state and returning the recording object.
237
- */
238
- finish(): Promise<CircuitRecording> {
239
- const result = this.recording;
240
- // If this is the top-level circuit recording, we reset the state for the next simulator call
241
- if (!result!.parent) {
242
- this.newCircuit = true;
243
- this.recording = undefined;
244
- } else {
245
- // For nested circuits (utility calls, nested contract calls), restore to parent recording
246
- // Note: we don't set newCircuit=false here because:
247
- // - For privateCallPrivateFunction, the callback wrapper will set it to false
248
- // - For utility calls, we want newCircuit to remain true so the next circuit creates its own recording
249
- this.recording = result!.parent;
250
- }
251
- return Promise.resolve(result!);
241
+ /** The recording active in the current async context, if any. */
242
+ protected currentRecording(): CircuitRecording | undefined {
243
+ return this.#recordings.getStore();
252
244
  }
253
245
 
254
- /**
255
- * Finalizes the recording by resetting the state and returning the recording object with an attached error.
256
- * @param error - The error that occurred during circuit execution
257
- */
258
- async finishWithError(error: unknown): Promise<CircuitRecording> {
259
- const result = await this.finish();
260
- result.error = JSON.stringify(error);
261
- return result;
246
+ /** Hook invoked when a recording opens, within the recording's context. Overridden to persist recordings. */
247
+ protected onStart(_recording: CircuitRecording): Promise<void> {
248
+ return Promise.resolve();
249
+ }
250
+
251
+ /** Hook invoked when a recording completes successfully, within the recording's context. */
252
+ protected onFinish(_recording: CircuitRecording): Promise<void> {
253
+ return Promise.resolve();
254
+ }
255
+
256
+ /** Hook invoked when a recording's execution throws, within the recording's context. */
257
+ protected onError(_recording: CircuitRecording, _error: unknown): Promise<void> {
258
+ return Promise.resolve();
259
+ }
260
+ }
261
+
262
+ /** Depth of a recording in the call tree: 0 for a top-level circuit, incremented per nested circuit. */
263
+ function depthOf(recording: CircuitRecording | undefined): number {
264
+ let depth = 0;
265
+ for (let ancestor = recording?.parent; ancestor; ancestor = ancestor.parent) {
266
+ depth++;
262
267
  }
268
+ return depth;
263
269
  }
@@ -3,11 +3,13 @@ import type { Logger } from '@aztec/foundation/log';
3
3
  import fs from 'fs/promises';
4
4
  import path from 'path';
5
5
 
6
- import type { ACVMWitness } from '../acvm/acvm_types.js';
7
6
  import { CircuitRecorder, type CircuitRecording } from './circuit_recorder.js';
8
7
 
8
+ /** Per-recording file state, keyed by recording so concurrent/nested executions don't share it. */
9
+ type RecordingFileState = { filePath: string; isFirstCall: boolean };
10
+
9
11
  export class FileCircuitRecorder extends CircuitRecorder {
10
- declare recording?: CircuitRecording & { filePath: string; isFirstCall: boolean };
12
+ readonly #fileState = new WeakMap<CircuitRecording, RecordingFileState>();
11
13
 
12
14
  constructor(
13
15
  private readonly recordDir: string,
@@ -16,16 +18,9 @@ export class FileCircuitRecorder extends CircuitRecorder {
16
18
  super(logger);
17
19
  }
18
20
 
19
- override async start(
20
- input: ACVMWitness,
21
- circuitBytecode: Buffer,
22
- circuitName: string,
23
- functionName: string = 'main',
24
- ) {
25
- await super.start(input, circuitBytecode, circuitName, functionName);
26
-
21
+ protected override async onStart(recording: CircuitRecording): Promise<void> {
27
22
  const recordingStringWithoutClosingBracket = JSON.stringify(
28
- { ...this.recording, isFirstCall: undefined, parent: undefined, oracleCalls: undefined, filePath: undefined },
23
+ { ...recording, parent: undefined, oracleCalls: undefined },
29
24
  null,
30
25
  2,
31
26
  ).slice(0, -2);
@@ -45,13 +40,13 @@ export class FileCircuitRecorder extends CircuitRecorder {
45
40
  }
46
41
  }
47
42
 
48
- this.recording!.isFirstCall = true;
49
- this.recording!.filePath = await FileCircuitRecorder.#computeFilePathAndStoreInitialRecording(
43
+ const filePath = await FileCircuitRecorder.#computeFilePathAndStoreInitialRecording(
50
44
  this.recordDir,
51
- this.recording!.circuitName,
52
- this.recording!.functionName,
45
+ recording.circuitName,
46
+ recording.functionName,
53
47
  recordingStringWithoutClosingBracket,
54
48
  );
49
+ this.#fileState.set(recording, { filePath, isFirstCall: true });
55
50
  }
56
51
 
57
52
  /**
@@ -95,53 +90,48 @@ export class FileCircuitRecorder extends CircuitRecorder {
95
90
  * @param inputs - Input arguments
96
91
  * @param outputs - Output results
97
92
  */
98
- override async recordCall(name: string, inputs: unknown[], outputs: unknown, time: number, stackDepth: number) {
99
- const entry = await super.recordCall(name, inputs, outputs, time, stackDepth);
100
- try {
101
- const prefix = this.recording!.isFirstCall ? ' ' : ' ,';
102
- this.recording!.isFirstCall = false;
103
- await fs.appendFile(this.recording!.filePath, prefix + JSON.stringify(entry) + '\n');
104
- } catch (err) {
105
- this.logger.error('Failed to log circuit call', { error: err });
93
+ override async recordCall(name: string, inputs: unknown[], outputs: unknown, time: number) {
94
+ const entry = await super.recordCall(name, inputs, outputs, time);
95
+ const recording = this.currentRecording();
96
+ const state = recording && this.#fileState.get(recording);
97
+ if (state) {
98
+ try {
99
+ const prefix = state.isFirstCall ? ' ' : ' ,';
100
+ state.isFirstCall = false;
101
+ await fs.appendFile(state.filePath, prefix + JSON.stringify(entry) + '\n');
102
+ } catch (err) {
103
+ this.logger.error('Failed to log circuit call', { error: err });
104
+ }
106
105
  }
107
106
  return entry;
108
107
  }
109
108
 
110
- /**
111
- * Finalizes the recording file by adding closing brackets. Without calling this method, the recording file is
112
- * incomplete and it fails to parse.
113
- */
114
- override async finish(): Promise<CircuitRecording> {
115
- // Finish sets the recording to undefined if we are at the topmost circuit,
116
- // so we save the current file path before that
117
- const filePath = this.recording!.filePath;
118
- const result = await super.finish();
109
+ /** Closes the recording file with the trailing brackets so the JSON parses. */
110
+ protected override async onFinish(recording: CircuitRecording): Promise<void> {
111
+ const state = this.#fileState.get(recording);
112
+ if (!state) {
113
+ return;
114
+ }
119
115
  try {
120
- await fs.appendFile(filePath, ' ]\n}\n');
116
+ await fs.appendFile(state.filePath, ' ]\n}\n');
121
117
  } catch (err) {
122
118
  this.logger.error('Failed to finalize recording file', { error: err });
123
119
  }
124
- return result!;
125
120
  }
126
121
 
127
- /**
128
- * Finalizes the recording file by adding the error and closing brackets. Without calling this method or `finish`,
129
- * the recording file is incomplete and it fails to parse.
130
- * @param error - The error that occurred during circuit execution
131
- */
132
- override async finishWithError(error: unknown): Promise<CircuitRecording> {
133
- // Finish sets the recording to undefined if we are at the topmost circuit,
134
- // so we save the current file path before that
135
- const filePath = this.recording!.filePath;
136
- const result = await super.finishWithError(error);
122
+ /** Closes the recording file with the execution error and trailing brackets so the JSON parses. */
123
+ protected override async onError(recording: CircuitRecording, error: unknown): Promise<void> {
124
+ const state = this.#fileState.get(recording);
125
+ if (!state) {
126
+ return;
127
+ }
137
128
  try {
138
- await fs.appendFile(filePath, ' ],\n');
139
- await fs.appendFile(filePath, ` "error": ${JSON.stringify(error)}\n`);
140
- await fs.appendFile(filePath, '}\n');
129
+ await fs.appendFile(state.filePath, ' ],\n');
130
+ await fs.appendFile(state.filePath, ` "error": ${JSON.stringify(error)}\n`);
131
+ await fs.appendFile(state.filePath, '}\n');
141
132
  } catch (err) {
142
133
  this.logger.error('Failed to finalize recording file with error', { error: err });
143
134
  }
144
- return result!;
145
135
  }
146
136
  }
147
137
 
@@ -58,24 +58,18 @@ export class SimulatorRecorderWrapper implements CircuitSimulator {
58
58
  functionName: string,
59
59
  callback: C,
60
60
  ): Promise<T> {
61
- // Start recording circuit execution
62
- await this.recorder.start(input, bytecode, contractName, functionName);
63
-
64
- // If callback was provided, we wrap it in a circuit recorder callback wrapper
61
+ // If a callback was provided, we wrap it so that its oracle calls are recorded. The wrapped callback reads the
62
+ // active recording lazily, so it picks up the recording opened by record() below.
65
63
  const wrappedCallback = this.recorder.wrapCallback(callback);
66
- let result: T;
67
- try {
68
- result = await simulateFn(wrappedCallback as C);
69
- } catch (error) {
70
- // If an error occurs, we finalize the recording file with the error
71
- await this.recorder.finishWithError(error);
72
- throw error;
73
- }
74
64
 
75
- // Witness generation is complete so we finish the circuit recorder
76
- const recording = await this.recorder.finish();
65
+ // record() opens a recording for this circuit, runs the simulation within it, and finalizes it. A simulation
66
+ // failure is re-thrown unchanged, so recorder bookkeeping never masks the underlying error.
67
+ const { result, recording } = await this.recorder.record(
68
+ { input, bytecode, circuitName: contractName, functionName },
69
+ () => simulateFn(wrappedCallback as C),
70
+ );
77
71
 
78
- (result as ACIRExecutionResult).oracles = recording.oracleCalls?.reduce(
72
+ (result as ACIRExecutionResult).oracles = recording.oracleCalls.reduce(
79
73
  (acc, { time, name }) => {
80
74
  if (!acc[name]) {
81
75
  acc[name] = { times: [] };
@@ -63,7 +63,7 @@ export class AvmSimulator implements AvmSimulatorInterface {
63
63
  public static async build(context: AvmContext): Promise<AvmSimulator> {
64
64
  const simulator = new AvmSimulator(context);
65
65
  const fnName = await context.persistableState.getPublicFunctionDebugName(context.environment);
66
- simulator.log = createLogger(`simulator:avm(f:${fnName})`);
66
+ simulator.log = createLogger(`simulator:avm(f:${fnName.slice(0, 128)})`);
67
67
 
68
68
  return simulator;
69
69
  }
@@ -33,13 +33,14 @@ export class LazyReaderMemory implements LazyReader {
33
33
  }
34
34
 
35
35
  public slice(start: number, end: number): Fr[] {
36
- const clampedEnd = Math.min(end, this.size);
36
+ const clampedEnd = Math.min(end, this.size, TaggedMemory.MAX_MEMORY_SIZE - this.offset);
37
37
  const length = Math.max(0, clampedEnd - start);
38
38
  return this.memory.getSlice(this.offset + start, length).map(word => word.toFr());
39
39
  }
40
40
 
41
41
  public readAll(): Fr[] {
42
- return this.memory.getSlice(this.offset, this.size).map(word => word.toFr());
42
+ const size = Math.min(this.size, TaggedMemory.MAX_MEMORY_SIZE - this.offset);
43
+ return this.memory.getSlice(this.offset, size).map(word => word.toFr());
43
44
  }
44
45
 
45
46
  public length(): number {
@@ -2,9 +2,10 @@ import { CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS } from '@aztec/constants';
2
2
  import { Fr } from '@aztec/foundation/curves/bn254';
3
3
  import { createLogger } from '@aztec/foundation/log';
4
4
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
5
- import { getCanonicalAuthRegistry } from '@aztec/protocol-contracts/auth-registry';
5
+ import { getCanonicalClassRegistry } from '@aztec/protocol-contracts/class-registry';
6
6
  import { computeFeePayerBalanceStorageSlot, getCanonicalFeeJuice } from '@aztec/protocol-contracts/fee-juice';
7
7
  import { getCanonicalInstanceRegistry } from '@aztec/protocol-contracts/instance-registry';
8
+ import { getStandardAuthRegistry } from '@aztec/standard-contracts/auth-registry';
8
9
  import type { ContractArtifact } from '@aztec/stdlib/abi';
9
10
  import { PublicDataWrite } from '@aztec/stdlib/avm';
10
11
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
@@ -91,7 +92,7 @@ export abstract class BaseAvmSimulationTester {
91
92
  }
92
93
 
93
94
  async registerAuthContract(): Promise<ContractInstanceWithAddress> {
94
- const authRegistry = await getCanonicalAuthRegistry();
95
+ const authRegistry = await getStandardAuthRegistry();
95
96
  const authRegistryContractClassPublic = {
96
97
  ...authRegistry.contractClass,
97
98
  privateFunctions: [],
@@ -102,9 +103,28 @@ export abstract class BaseAvmSimulationTester {
102
103
  authRegistryContractClassPublic,
103
104
  authRegistry.instance,
104
105
  );
106
+ // AuthRegistry is a standard contract (not a protocol contract), so the AVM enforces a
107
+ // deployment-nullifier check on every instance retrieval. Insert the nullifier here so
108
+ // calls to AuthRegistry don't EXCEPTIONAL_HALT during simulation.
109
+ await this.insertContractAddressNullifier(authRegistry.instance.address);
105
110
  return authRegistry.instance;
106
111
  }
107
112
 
113
+ async registerClassRegistryContract(): Promise<ContractInstanceWithAddress> {
114
+ const classRegistry = await getCanonicalClassRegistry();
115
+ const classRegistryContractClassPublic = {
116
+ ...classRegistry.contractClass,
117
+ privateFunctions: [],
118
+ utilityFunctions: [],
119
+ };
120
+ await this.contractDataSource.addNewContract(
121
+ classRegistry.artifact,
122
+ classRegistryContractClassPublic,
123
+ classRegistry.instance,
124
+ );
125
+ return classRegistry.instance;
126
+ }
127
+
108
128
  async registerInstanceRegistryContract(): Promise<ContractInstanceWithAddress> {
109
129
  const instanceRegistry = await getCanonicalInstanceRegistry();
110
130
  const instanceRegistryContractClassPublic = {
@@ -129,7 +149,7 @@ export abstract class BaseAvmSimulationTester {
129
149
 
130
150
  private async insertContractAddressNullifier(contractAddress: AztecAddress) {
131
151
  const contractAddressNullifier = await siloNullifier(
132
- AztecAddress.fromNumber(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS),
152
+ AztecAddress.fromNumberUnsafe(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS),
133
153
  contractAddress.toField(),
134
154
  );
135
155
  await this.merkleTrees.sequentialInsert(MerkleTreeId.NULLIFIER_TREE, [contractAddressNullifier.toBuffer()]);
@@ -128,22 +128,25 @@ export async function createContractClassAndInstance(
128
128
  const constructorAbi = getContractFunctionAbi('constructor', contractArtifact);
129
129
  const { publicKeys } = await deriveKeys(new Fr(seed));
130
130
  const initializationHash = await computeInitializationHash(constructorAbi, constructorArgs);
131
+ const immutablesHash = new Fr(seed + 1);
131
132
  const contractInstance =
132
133
  originalContractClassId === undefined
133
134
  ? await makeContractInstanceFromClassId(contractClass.id, seed, {
134
135
  deployer,
135
136
  initializationHash,
137
+ immutablesHash,
136
138
  publicKeys,
137
139
  })
138
140
  : await makeContractInstanceFromClassId(originalContractClassId, seed, {
139
141
  deployer,
140
142
  initializationHash,
141
143
  currentClassId: contractClass.id,
144
+ immutablesHash,
142
145
  publicKeys,
143
146
  });
144
147
 
145
148
  const contractAddressNullifier = await siloNullifier(
146
- AztecAddress.fromNumber(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS),
149
+ AztecAddress.fromNumberUnsafe(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS),
147
150
  contractInstance.address.toField(),
148
151
  );
149
152
 
@@ -9,6 +9,7 @@ export enum ContractInstanceMember {
9
9
  DEPLOYER,
10
10
  CLASS_ID,
11
11
  INIT_HASH,
12
+ IMMUTABLES_HASH,
12
13
  }
13
14
 
14
15
  export class GetContractInstance extends Instruction {
@@ -41,7 +42,7 @@ export class GetContractInstance extends Instruction {
41
42
  );
42
43
 
43
44
  if (!(this.memberEnum in ContractInstanceMember)) {
44
- throw new InstructionExecutionError(`Invalid GETCONSTRACTINSTANCE member enum ${this.memberEnum}`);
45
+ throw new InstructionExecutionError(`Invalid GETCONTRACTINSTANCE member enum ${this.memberEnum}`);
45
46
  }
46
47
 
47
48
  const operands = [this.addressOffset, this.dstOffset];
@@ -64,6 +65,9 @@ export class GetContractInstance extends Instruction {
64
65
  case ContractInstanceMember.INIT_HASH:
65
66
  memberValue = new Field(instance.initializationHash);
66
67
  break;
68
+ case ContractInstanceMember.IMMUTABLES_HASH:
69
+ memberValue = new Field(instance.immutablesHash);
70
+ break;
67
71
  }
68
72
  }
69
73