@aztec/simulator 5.0.0-rc.1 → 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 (37) 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/circuit_recording/circuit_recorder.d.ts +36 -23
  5. package/dest/private/circuit_recording/circuit_recorder.d.ts.map +1 -1
  6. package/dest/private/circuit_recording/circuit_recorder.js +65 -69
  7. package/dest/private/circuit_recording/file_circuit_recorder.d.ts +7 -19
  8. package/dest/private/circuit_recording/file_circuit_recorder.d.ts.map +1 -1
  9. package/dest/private/circuit_recording/file_circuit_recorder.js +38 -42
  10. package/dest/private/circuit_recording/simulator_recorder_wrapper.d.ts +1 -1
  11. package/dest/private/circuit_recording/simulator_recorder_wrapper.d.ts.map +1 -1
  12. package/dest/private/circuit_recording/simulator_recorder_wrapper.js +11 -14
  13. package/dest/public/avm/fixtures/base_avm_simulation_tester.js +1 -1
  14. package/dest/public/avm/fixtures/utils.js +1 -1
  15. package/dest/public/fixtures/amm_test.js +2 -2
  16. package/dest/public/fixtures/bulk_test.js +2 -2
  17. package/dest/public/fixtures/custom_bytecode_tester.d.ts +1 -1
  18. package/dest/public/fixtures/custom_bytecode_tester.d.ts.map +1 -1
  19. package/dest/public/fixtures/custom_bytecode_tester.js +2 -2
  20. package/dest/public/fixtures/token_test.js +3 -3
  21. package/dest/public/fixtures/utils.js +1 -1
  22. package/dest/public/public_tx_simulator/contract_provider_for_cpp.js +2 -2
  23. package/dest/public/state_manager/state_manager.js +1 -1
  24. package/package.json +16 -16
  25. package/src/client.ts +0 -2
  26. package/src/private/circuit_recording/circuit_recorder.ts +84 -78
  27. package/src/private/circuit_recording/file_circuit_recorder.ts +38 -48
  28. package/src/private/circuit_recording/simulator_recorder_wrapper.ts +9 -15
  29. package/src/public/avm/fixtures/base_avm_simulation_tester.ts +1 -1
  30. package/src/public/avm/fixtures/utils.ts +1 -1
  31. package/src/public/fixtures/amm_test.ts +2 -2
  32. package/src/public/fixtures/bulk_test.ts +2 -2
  33. package/src/public/fixtures/custom_bytecode_tester.ts +2 -2
  34. package/src/public/fixtures/token_test.ts +3 -3
  35. package/src/public/fixtures/utils.ts +1 -1
  36. package/src/public/public_tx_simulator/contract_provider_for_cpp.ts +2 -2
  37. package/src/public/state_manager/state_manager.ts +1 -1
@@ -31,4 +31,4 @@ export declare function executeCustomBytecode(contract: ContractInstanceWithAddr
31
31
  * @returns The execution result
32
32
  */
33
33
  export declare function deployAndExecuteCustomBytecode(bytecode: Buffer, tester: PublicTxSimulationTester, txLabel?: string, contractName?: string, deployer?: AztecAddress, calldata?: any[]): Promise<PublicTxResult>;
34
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY3VzdG9tX2J5dGVjb2RlX3Rlc3Rlci5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL3B1YmxpYy9maXh0dXJlcy9jdXN0b21fYnl0ZWNvZGVfdGVzdGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUNBLE9BQU8sS0FBSyxFQUFFLGNBQWMsRUFBRSxNQUFNLG1CQUFtQixDQUFDO0FBQ3hELE9BQU8sRUFBRSxZQUFZLEVBQUUsTUFBTSw2QkFBNkIsQ0FBQztBQUMzRCxPQUFPLEtBQUssRUFBRSwyQkFBMkIsRUFBRSxNQUFNLHdCQUF3QixDQUFDO0FBRTFFLE9BQU8sRUFBRSx3QkFBd0IsRUFBRSxNQUFNLGtDQUFrQyxDQUFDO0FBRTVFOzs7Ozs7O0dBT0c7QUFDSCx3QkFBc0Isb0JBQW9CLENBQ3hDLFFBQVEsRUFBRSxNQUFNLEVBQ2hCLE1BQU0sRUFBRSx3QkFBd0IsRUFDaEMsWUFBWSxHQUFFLE1BQWlDLEVBQy9DLFFBQVEsR0FB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MAAM,EAChB,MAAM,EAAE,wBAAwB,EAChC,YAAY,GAAE,MAAiC,EAC/C,QAAQ,GAAE,YAA0C,GACnD,OAAO,CAAC,2BAA2B,CAAC,CAiBtC;AAED;;;;;;;GAOG;AACH,wBAAsB,qBAAqB,CACzC,QAAQ,EAAE,2BAA2B,EACrC,MAAM,EAAE,wBAAwB,EAChC,OAAO,GAAE,MAA6B,EACtC,QAAQ,GAAE,GAAG,EAAO,GACnB,OAAO,CAAC,cAAc,CAAC,CAQzB;AAED;;;;;;;;;GASG;AACH,wBAAsB,8BAA8B,CAClD,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,wBAAwB,EAChC,OAAO,GAAE,MAA6B,EACtC,YAAY,GAAE,MAAiC,EAC/C,QAAQ,GAAE,YAA0C,EACpD,QAAQ,GAAE,GAAG,EAAO,GACnB,OAAO,CAAC,cAAc,CAAC,CAGzB"}
1
+ {"version":3,"file":"custom_bytecode_tester.d.ts","sourceRoot":"","sources":["../../../src/public/fixtures/custom_bytecode_tester.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AAE1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAE5E;;;;;;;GAOG;AACH,wBAAsB,oBAAoB,CACxC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,wBAAwB,EAChC,YAAY,GAAE,MAAiC,EAC/C,QAAQ,GAAE,YAAgD,GACzD,OAAO,CAAC,2BAA2B,CAAC,CAiBtC;AAED;;;;;;;GAOG;AACH,wBAAsB,qBAAqB,CACzC,QAAQ,EAAE,2BAA2B,EACrC,MAAM,EAAE,wBAAwB,EAChC,OAAO,GAAE,MAA6B,EACtC,QAAQ,GAAE,GAAG,EAAO,GACnB,OAAO,CAAC,cAAc,CAAC,CAQzB;AAED;;;;;;;;;GASG;AACH,wBAAsB,8BAA8B,CAClD,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,wBAAwB,EAChC,OAAO,GAAE,MAA6B,EACtC,YAAY,GAAE,MAAiC,EAC/C,QAAQ,GAAE,YAAgD,EAC1D,QAAQ,GAAE,GAAG,EAAO,GACnB,OAAO,CAAC,cAAc,CAAC,CAGzB"}
@@ -7,7 +7,7 @@ import { AztecAddress } from '@aztec/stdlib/aztec-address';
7
7
  * @param contractName - The name of the contract
8
8
  * @param deployer - The deployer address
9
9
  * @returns The deployed contract instance
10
- */ export async function deployCustomBytecode(bytecode, tester, contractName = 'CustomBytecodeContract', deployer = AztecAddress.fromNumber(42)) {
10
+ */ export async function deployCustomBytecode(bytecode, tester, contractName = 'CustomBytecodeContract', deployer = AztecAddress.fromNumberUnsafe(42)) {
11
11
  const contractArtifact = emptyContractArtifact();
12
12
  contractArtifact.name = contractName;
13
13
  contractArtifact.functions = [
@@ -47,7 +47,7 @@ import { AztecAddress } from '@aztec/stdlib/aztec-address';
47
47
  * @param deployer - The deployer address
48
48
  * @param calldata - The calldata to use
49
49
  * @returns The execution result
50
- */ export async function deployAndExecuteCustomBytecode(bytecode, tester, txLabel = 'CustomBytecodeTest', contractName = 'CustomBytecodeContract', deployer = AztecAddress.fromNumber(42), calldata = []) {
50
+ */ export async function deployAndExecuteCustomBytecode(bytecode, tester, txLabel = 'CustomBytecodeTest', contractName = 'CustomBytecodeContract', deployer = AztecAddress.fromNumberUnsafe(42), calldata = []) {
51
51
  const testContract = await deployCustomBytecode(bytecode, tester, contractName, deployer);
52
52
  return await executeCustomBytecode(testContract, tester, txLabel, calldata);
53
53
  }
@@ -3,9 +3,9 @@ import { Timer } from '@aztec/foundation/timer';
3
3
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
4
4
  export async function tokenTest(tester, logger, tokenArtifact, expectToBeTrue, options = {}) {
5
5
  const timer = new Timer();
6
- const admin = AztecAddress.fromNumber(42);
7
- const sender = AztecAddress.fromNumber(111);
8
- const receiver = AztecAddress.fromNumber(222);
6
+ const admin = AztecAddress.fromNumberUnsafe(42);
7
+ const sender = AztecAddress.fromNumberUnsafe(111);
8
+ const receiver = AztecAddress.fromNumberUnsafe(222);
9
9
  const token = await setUpToken(tester, tokenArtifact, admin, expectToBeTrue);
10
10
  const mintAmount = 100n;
11
11
  // EXECUTE! This means that if using AvmProvingTester subclass, it will PROVE the transaction!
@@ -159,7 +159,7 @@ export async function addNewContractInstanceToTx(tx, contractInstance, skipNulli
159
159
  contractInstance.deployer.toField()
160
160
  ];
161
161
  const contractInstanceLog = new PrivateLog(padArrayEnd(logFields, Fr.ZERO, PRIVATE_LOG_SIZE_IN_FIELDS), logFields.length);
162
- const contractAddressNullifier = await siloNullifier(AztecAddress.fromNumber(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS), contractInstance.address.toField());
162
+ const contractAddressNullifier = await siloNullifier(AztecAddress.fromNumberUnsafe(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS), contractInstance.address.toField());
163
163
  const accumulatedData = tx.data.forPublic ? tx.data.forPublic.revertibleAccumulatedData : tx.data.forRollup.end;
164
164
  if (!skipNullifierInsertion) {
165
165
  const nextNullifierIndex = countAccumulatedItems(accumulatedData.nullifiers);
@@ -13,7 +13,7 @@ export class ContractProviderForCpp {
13
13
  this.globalVariables = globalVariables;
14
14
  this.getContractInstance = async (address)=>{
15
15
  this.log.trace(`Contract provider callback: getContractInstance(${address})`);
16
- const aztecAddr = AztecAddress.fromString(address);
16
+ const aztecAddr = AztecAddress.fromStringUnsafe(address);
17
17
  const instance = await this.contractsDB.getContractInstance(aztecAddr, this.globalVariables.timestamp);
18
18
  if (!instance) {
19
19
  this.log.debug(`Contract instance not found: ${address}`);
@@ -58,7 +58,7 @@ export class ContractProviderForCpp {
58
58
  this.getDebugFunctionName = async (address, selector)=>{
59
59
  this.log.trace(`Contract provider callback: getDebugFunctionName(${address}, ${selector})`);
60
60
  // Parse address and selector strings
61
- const aztecAddr = AztecAddress.fromString(address);
61
+ const aztecAddr = AztecAddress.fromStringUnsafe(address);
62
62
  const selectorFr = Fr.fromString(selector);
63
63
  const functionSelector = FunctionSelector.fromFieldOrUndefined(selectorFr);
64
64
  if (!functionSelector) {
@@ -287,7 +287,7 @@ import { PublicStorage } from './public_storage.js';
287
287
  // Nullifier check! We do this regardless of whether or not the instance exists,
288
288
  // as even for non-existence, we need to generate nullifier check hints.
289
289
  // This will internally decide whether to check the nullifier tree or not depending on doMerkleOperations.
290
- const nullifierExistsInTree = await this.checkNullifierExists(AztecAddress.fromNumber(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS), contractAddress.toField());
290
+ const nullifierExistsInTree = await this.checkNullifierExists(AztecAddress.fromNumberUnsafe(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS), contractAddress.toField());
291
291
  assert(exists == nullifierExistsInTree, `Contract instance for address ${contractAddress} in DB: ${exists} != nullifier tree: ${nullifierExistsInTree}. This is a bug!`);
292
292
  if (!exists) {
293
293
  this.log.debug(`Contract instance NOT FOUND (address=${contractAddress})`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/simulator",
3
- "version": "5.0.0-rc.1",
3
+ "version": "5.0.0-rc.2",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  "./server": "./dest/server.js",
@@ -64,26 +64,26 @@
64
64
  ]
65
65
  },
66
66
  "dependencies": {
67
- "@aztec/constants": "5.0.0-rc.1",
68
- "@aztec/foundation": "5.0.0-rc.1",
69
- "@aztec/native": "5.0.0-rc.1",
70
- "@aztec/noir-acvm_js": "5.0.0-rc.1",
71
- "@aztec/noir-noirc_abi": "5.0.0-rc.1",
72
- "@aztec/noir-protocol-circuits-types": "5.0.0-rc.1",
73
- "@aztec/noir-types": "5.0.0-rc.1",
74
- "@aztec/protocol-contracts": "5.0.0-rc.1",
75
- "@aztec/standard-contracts": "5.0.0-rc.1",
76
- "@aztec/stdlib": "5.0.0-rc.1",
77
- "@aztec/telemetry-client": "5.0.0-rc.1",
78
- "@aztec/world-state": "5.0.0-rc.1",
67
+ "@aztec/constants": "5.0.0-rc.2",
68
+ "@aztec/foundation": "5.0.0-rc.2",
69
+ "@aztec/native": "5.0.0-rc.2",
70
+ "@aztec/noir-acvm_js": "5.0.0-rc.2",
71
+ "@aztec/noir-noirc_abi": "5.0.0-rc.2",
72
+ "@aztec/noir-protocol-circuits-types": "5.0.0-rc.2",
73
+ "@aztec/noir-types": "5.0.0-rc.2",
74
+ "@aztec/protocol-contracts": "5.0.0-rc.2",
75
+ "@aztec/standard-contracts": "5.0.0-rc.2",
76
+ "@aztec/stdlib": "5.0.0-rc.2",
77
+ "@aztec/telemetry-client": "5.0.0-rc.2",
78
+ "@aztec/world-state": "5.0.0-rc.2",
79
79
  "lodash.clonedeep": "^4.5.0",
80
80
  "lodash.merge": "^4.6.2",
81
81
  "tslib": "^2.4.0"
82
82
  },
83
83
  "devDependencies": {
84
- "@aztec/kv-store": "5.0.0-rc.1",
85
- "@aztec/noir-contracts.js": "5.0.0-rc.1",
86
- "@aztec/noir-test-contracts.js": "5.0.0-rc.1",
84
+ "@aztec/kv-store": "5.0.0-rc.2",
85
+ "@aztec/noir-contracts.js": "5.0.0-rc.2",
86
+ "@aztec/noir-test-contracts.js": "5.0.0-rc.2",
87
87
  "@jest/globals": "^30.0.0",
88
88
  "@types/jest": "^30.0.0",
89
89
  "@types/lodash.clonedeep": "^4.5.7",
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';
@@ -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: [] };
@@ -149,7 +149,7 @@ export abstract class BaseAvmSimulationTester {
149
149
 
150
150
  private async insertContractAddressNullifier(contractAddress: AztecAddress) {
151
151
  const contractAddressNullifier = await siloNullifier(
152
- AztecAddress.fromNumber(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS),
152
+ AztecAddress.fromNumberUnsafe(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS),
153
153
  contractAddress.toField(),
154
154
  );
155
155
  await this.merkleTrees.sequentialInsert(MerkleTreeId.NULLIFIER_TREE, [contractAddressNullifier.toBuffer()]);
@@ -146,7 +146,7 @@ export async function createContractClassAndInstance(
146
146
  });
147
147
 
148
148
  const contractAddressNullifier = await siloNullifier(
149
- AztecAddress.fromNumber(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS),
149
+ AztecAddress.fromNumberUnsafe(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS),
150
150
  contractInstance.address.toField(),
151
151
  );
152
152
 
@@ -25,8 +25,8 @@ export async function ammTest(
25
25
  ) {
26
26
  const timer = new Timer();
27
27
 
28
- const admin = AztecAddress.fromNumber(42);
29
- const sender = AztecAddress.fromNumber(111);
28
+ const admin = AztecAddress.fromNumberUnsafe(42);
29
+ const sender = AztecAddress.fromNumberUnsafe(111);
30
30
 
31
31
  logger.debug(`Deploying tokens`);
32
32
  const token0 = await setUpToken(tester, tokenArtifact, admin, expectToBeTrue, /*seed=*/ 0);
@@ -13,7 +13,7 @@ export async function bulkTest(
13
13
  ) {
14
14
  const timer = new Timer();
15
15
 
16
- const deployer = AztecAddress.fromNumber(42);
16
+ const deployer = AztecAddress.fromNumberUnsafe(42);
17
17
  const avmTestContract = await tester.registerAndDeployContract(
18
18
  /*constructorArgs=*/ [],
19
19
  deployer,
@@ -114,7 +114,7 @@ export async function megaBulkTest(
114
114
  ) {
115
115
  const timer = new Timer();
116
116
 
117
- const deployer = AztecAddress.fromNumber(42);
117
+ const deployer = AztecAddress.fromNumberUnsafe(42);
118
118
  const avmTestContract = await tester.registerAndDeployContract(
119
119
  /*constructorArgs=*/ [],
120
120
  deployer,
@@ -17,7 +17,7 @@ export async function deployCustomBytecode(
17
17
  bytecode: Buffer,
18
18
  tester: PublicTxSimulationTester,
19
19
  contractName: string = 'CustomBytecodeContract',
20
- deployer: AztecAddress = AztecAddress.fromNumber(42),
20
+ deployer: AztecAddress = AztecAddress.fromNumberUnsafe(42),
21
21
  ): Promise<ContractInstanceWithAddress> {
22
22
  const contractArtifact = emptyContractArtifact();
23
23
  contractArtifact.name = contractName;
@@ -75,7 +75,7 @@ export async function deployAndExecuteCustomBytecode(
75
75
  tester: PublicTxSimulationTester,
76
76
  txLabel: string = 'CustomBytecodeTest',
77
77
  contractName: string = 'CustomBytecodeContract',
78
- deployer: AztecAddress = AztecAddress.fromNumber(42),
78
+ deployer: AztecAddress = AztecAddress.fromNumberUnsafe(42),
79
79
  calldata: any[] = [],
80
80
  ): Promise<PublicTxResult> {
81
81
  const testContract = await deployCustomBytecode(bytecode, tester, contractName, deployer);