@aztec/native 0.0.1-commit.b655e406 → 0.0.1-commit.b9865e97

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.
package/dest/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export * from './native_module.js';
2
2
  export { type RoundtripDuration, MsgpackChannel } from './msgpack_channel.js';
3
- //# sourceMappingURL=index.d.ts.map
3
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxjQUFjLG9CQUFvQixDQUFDO0FBQ25DLE9BQU8sRUFBRSxLQUFLLGlCQUFpQixFQUFFLGNBQWMsRUFBRSxNQUFNLHNCQUFzQixDQUFDIn0=
@@ -22,4 +22,4 @@ export declare class MsgpackChannel<M extends number = number, Req extends Messa
22
22
  }>;
23
23
  }
24
24
  export {};
25
- //# sourceMappingURL=msgpack_channel.d.ts.map
25
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXNncGFja19jaGFubmVsLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvbXNncGFja19jaGFubmVsLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQU1BLE1BQU0sV0FBVyxlQUFlO0lBQzlCLElBQUksQ0FBQyxHQUFHLEVBQUUsTUFBTSxHQUFHLFVBQVUsR0FBRyxPQUFPLENBQUMsTUFBTSxHQUFHLFVBQVUsQ0FBQyxDQUFDO0NBQzlEO0FBRUQsTUFBTSxNQUFNLGlCQUFpQixHQUFHO0lBQzlCLFVBQVUsRUFBRSxNQUFNLENBQUM7SUFDbkIsTUFBTSxFQUFFLE1BQU0sQ0FBQztJQUNmLFVBQVUsRUFBRSxNQUFNL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,MAAM,EACzB,GAAG,SAAS,WAAW,CAAC,CAAC,CAAC,GAAG,GAAG,EAChC,IAAI,SAAS,WAAW,CAAC,CAAC,CAAC,GAAG,GAAG;IAYd,OAAO,CAAC,IAAI;IAV/B,mCAAmC;IACnC,OAAO,CAAC,OAAO,CAKZ;IAEH,OAAO,CAAC,KAAK,CAAK;IAElB,YAA2B,IAAI,EAAE,eAAe,EAAI;IAEvC,WAAW,CAAC,CAAC,SAAS,CAAC,EAClC,OAAO,EAAE,CAAC,EACV,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,GACX,OAAO,CAAC;QAAE,QAAQ,EAAE,iBAAiB,CAAC;QAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,CAAA;KAAE,CAAC,CA0D7D;CACF"}
@@ -1,4 +1,4 @@
1
- import { Fr } from '@aztec/foundation/fields';
1
+ import { Fr } from '@aztec/foundation/curves/bn254';
2
2
  import { MessageHeader, TypedMessage } from '@aztec/foundation/message';
3
3
  import { Encoder, addExtension } from 'msgpackr';
4
4
  import { isAnyArrayBuffer } from 'util/types';
@@ -1,16 +1,115 @@
1
+ import { type LogLevel, type Logger } from '@aztec/foundation/log';
1
2
  import type { MessageReceiver } from './msgpack_channel.js';
2
3
  interface NativeClassCtor {
3
4
  new (...args: unknown[]): MessageReceiver;
4
5
  }
5
- export declare const NativeWorldState: NativeClassCtor;
6
6
  export declare const NativeLMDBStore: NativeClassCtor;
7
+ /**
8
+ * Contract provider interface for callbacks to fetch contract data.
9
+ * These callbacks are invoked by C++ during simulation when contract data is needed.
10
+ */
11
+ export interface ContractProvider {
12
+ /**
13
+ * Fetch a contract instance by address.
14
+ * @param address - The contract address as a string (hex format)
15
+ * @returns Promise resolving to msgpack-serialized ContractInstanceHint buffer, or undefined if not found
16
+ */
17
+ getContractInstance(address: string): Promise<Buffer | undefined>;
18
+ /**
19
+ * Fetch a contract class by class ID.
20
+ * @param classId - The contract class ID as a string (hex format)
21
+ * @returns Promise resolving to msgpack-serialized ContractClassHint buffer, or undefined if not found
22
+ */
23
+ getContractClass(classId: string): Promise<Buffer | undefined>;
24
+ /**
25
+ * Add contracts from deployment data.
26
+ * @param contractDeploymentData - Msgpack-serialized ContractDeploymentData buffer
27
+ * @returns Promise that resolves when contracts are added
28
+ */
29
+ addContracts(contractDeploymentData: Buffer): Promise<void>;
30
+ /**
31
+ * Fetch the bytecode commitment for a contract class.
32
+ * @param classId - The contract class ID as a string (hex format)
33
+ * @returns Promise resolving to msgpack-serialized Fr buffer, or undefined if not found
34
+ */
35
+ getBytecodeCommitment(classId: string): Promise<Buffer | undefined>;
36
+ /**
37
+ * Fetch the debug function name for a contract function.
38
+ * @param address - The contract address as a string (hex format)
39
+ * @param selector - The function selector as a string (hex format)
40
+ * @returns Promise resolving to function name string, or undefined if not found
41
+ */
42
+ getDebugFunctionName(address: string, selector: string): Promise<string | undefined>;
43
+ /**
44
+ * Create a new checkpoint for the contract database state.
45
+ * Enables rollback to current state in case of a revert.
46
+ * @returns Promise that resolves when checkpoint is created
47
+ */
48
+ createCheckpoint(): Promise<void>;
49
+ /**
50
+ * Commit the current checkpoint, accepting its state as latest.
51
+ * @returns Promise that resolves when checkpoint is committed
52
+ */
53
+ commitCheckpoint(): Promise<void>;
54
+ /**
55
+ * Revert the current checkpoint, discarding its state and rolling back.
56
+ * @returns Promise that resolves when checkpoint is reverted
57
+ */
58
+ revertCheckpoint(): Promise<void>;
59
+ }
60
+ /**
61
+ * Cancellation token handle used to cancel C++ AVM simulation.
62
+ * The token is created via createCancellationToken() and can be cancelled via cancelSimulation().
63
+ * Pass it to avmSimulate to enable cancellation support.
64
+ */
65
+ export type CancellationToken = any;
66
+ /**
67
+ * Create a new cancellation token for C++ simulation.
68
+ * This token can be passed to avmSimulate and later cancelled via cancelSimulation().
69
+ * @returns A handle to a cancellation token
70
+ */
71
+ export declare function createCancellationToken(): CancellationToken;
72
+ /**
73
+ * Signal cancellation to a C++ simulation.
74
+ * The simulation will stop at the next opcode or before the next WorldState write.
75
+ * @param token - The cancellation token previously passed to avmSimulate
76
+ */
77
+ export declare function cancelSimulation(token: CancellationToken): void;
78
+ /**
79
+ * Maximum number of concurrent AVM simulations. Each simulation spawns a dedicated OS thread,
80
+ * so this controls resource usage. Defaults to 4. Set to 0 for unlimited.
81
+ */
82
+ export declare const AVM_MAX_CONCURRENT_SIMULATIONS: number;
83
+ /**
84
+ * AVM simulation function that takes serialized inputs and a contract provider.
85
+ * The contract provider enables C++ to callback to TypeScript for contract data during simulation.
86
+ *
87
+ * Simulations run on dedicated std::threads (not the libuv thread pool), so there is no risk
88
+ * of libuv thread pool exhaustion or deadlock from C++ BlockingCall callbacks.
89
+ * Concurrency is limited by AVM_MAX_CONCURRENT_SIMULATIONS (default 4, 0 = unlimited).
90
+ *
91
+ * @param inputs - Msgpack-serialized AvmFastSimulationInputs buffer
92
+ * @param contractProvider - Object with callbacks for fetching contract instances and classes
93
+ * @param wsdbIpcPath - IPC path of the running aztec-wsdb process. The C++ AVM connects per
94
+ * simulation and constructs an IPC-backed merkle DB.
95
+ * @param logLevel - Optional log level to control C++ verbosity (only used if loggerFunction is provided)
96
+ * @param logger - Optional logger object for C++ logging callbacks
97
+ * @param cancellationToken - Optional token to enable cancellation support
98
+ * @returns Promise resolving to msgpack-serialized AvmCircuitPublicInputs buffer
99
+ */
100
+ export declare function avmSimulate(inputs: Buffer, contractProvider: ContractProvider, wsdbIpcPath: string, logLevel?: LogLevel, logger?: Logger, cancellationToken?: CancellationToken): Promise<Buffer>;
7
101
  /**
8
102
  * AVM simulation function that uses pre-collected hints from TypeScript simulation.
9
103
  * All contract data and merkle tree hints are included in the AvmCircuitInputs, so no runtime
10
104
  * callbacks to TS or WS pointer are needed.
105
+ *
106
+ * Simulations run on dedicated std::threads (not the libuv thread pool).
107
+ * Concurrency is limited by AVM_MAX_CONCURRENT_SIMULATIONS (default 4, 0 = unlimited).
108
+ *
11
109
  * @param inputs - Msgpack-serialized AvmCircuitInputs (AvmProvingInputs in C++) buffer
110
+ * @param logLevel - Log level to control C++ verbosity
12
111
  * @returns Promise resolving to msgpack-serialized simulation results buffer
13
112
  */
14
- export declare const avmSimulateWithHintedDbs: (inputs: Buffer) => Promise<Buffer>;
113
+ export declare function avmSimulateWithHintedDbs(inputs: Buffer, logLevel?: LogLevel): Promise<Buffer>;
15
114
  export {};
16
- //# sourceMappingURL=native_module.d.ts.map
115
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibmF0aXZlX21vZHVsZS5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL25hdGl2ZV9tb2R1bGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsT0FBTyxFQUFFLEtBQUssUUFBUSxFQUFhLEtBQUssTUFBTSxFQUFFLE1BQU0sdUJBQXVCLENBQUM7QUFLOUUsT0FBTyxLQUFLLEVBQUUsZUFBZSxFQUFFLE1BQU0sc0JBQXNCLENBQUM7QUFFNUQsVUFBVSxlQUFlO0lBQ3ZCLEtBQUssR0FBRyxJQUFJLEVBQUUsT0FBTyxFQUFFLEdBQUcsZUFBZSxDQUFDO0NBQzNDO0FBYUQsZUFBTyxNQUFNLGVBQWUsRUFBRSxlQUEyRCxDQUFDO0FBRTFGOzs7R0FHRztBQUNILE1BQU0sV0FBVyxnQkFBZ0I7SUFDL0I7Ozs7T0FJRztJQUNILG1CQUFtQixDQUFDLE9BQU8sRUFBRSxNQUFNLEdBQUcsT0FBTyxDQUFDLE1BQU0sR0FBRyxTQUFTLENBQUMsQ0FBQztJQUNsRTs7OztPQUlHO0lBQ0gsZ0JBQWdCLENBQUMsT0FBTyxFQUFFLE1BQU0sR0FBRyxPQUFPLENBQUMsTUFBTSxHQUFHLFNBQVMsQ0FBQyxDQUFDO0lBRS9EOzs7O09BSUc7SUFDSCxZQUFZLENBQUMsc0JBQXNCLEVBQUUsTUFBTSxHQUFHLE9BQU8sQ0FBQyxJQUFJLENBQ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dBQ3BDLE9BQU8sQ0FBQyxNQUFNLENBQUMsQ0FXakI7QUFFRDs7Ozs7Ozs7Ozs7R0FXRztBQUNILHdCQUFnQix3QkFBd0IsQ0FBQyxNQUFNLEVBQUUsTUFBTSxFQUFFLFFBQVEsR0FBRSxRQUFpQixHQUFHLE9BQU8sQ0FBQyxNQUFNLENBQUMsQ0FFckcifQ==
@@ -1 +1 @@
1
- {"version":3,"file":"native_module.d.ts","sourceRoot":"","sources":["../src/native_module.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,UAAU,eAAe;IACvB,KAAK,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,eAAe,CAAC;CAC3C;AA2BD,eAAO,MAAM,gBAAgB,EAAE,eAA4D,CAAC;AAC5F,eAAO,MAAM,eAAe,EAAE,eAA2D,CAAC;AAE1F;;;;;;GAMG;AACH,eAAO,MAAM,wBAAwB,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAErD,CAAC"}
1
+ {"version":3,"file":"native_module.d.ts","sourceRoot":"","sources":["../src/native_module.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,QAAQ,EAAa,KAAK,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAK9E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,UAAU,eAAe;IACvB,KAAK,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,eAAe,CAAC;CAC3C;AAaD,eAAO,MAAM,eAAe,EAAE,eAA2D,CAAC;AAE1F;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;;OAIG;IACH,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAClE;;;;OAIG;IACH,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CA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{ LogLevels } from '@aztec/foundation/log';
3
+ import { Semaphore } from '@aztec/foundation/queue';
1
4
  import { createRequire } from 'module';
2
- import { dirname, join } from 'path';
3
- import { fileURLToPath } from 'url';
4
5
  function loadNativeModule() {
5
- const __filename = fileURLToPath(import.meta.url);
6
- const __dirname = dirname(__filename);
7
- // Map Node.js platform/arch to build directory names
8
- const arch = process.arch === 'x64' ? 'amd64' : process.arch;
9
- const platform = process.platform === 'darwin' ? 'macos' : process.platform;
10
- const variant = `${arch}-${platform}`;
11
- const modulePath = join(__dirname, '..', 'build', variant, 'nodejs_module.node');
12
- try {
13
- const require = createRequire(import.meta.url);
14
- return require(modulePath);
15
- } catch (error) {
16
- throw new Error(`Failed to load native module for ${variant} from ${modulePath}. ` + `Supported: amd64-linux, arm64-linux, amd64-macos, arm64-macos. ` + `Error: ${error}`);
6
+ const require = createRequire(import.meta.url);
7
+ const napiPath = findNapiBinary();
8
+ if (!napiPath) {
9
+ throw new Error('NAPI binary not found for current platform.');
17
10
  }
11
+ return require(napiPath);
18
12
  }
19
13
  const nativeModule = loadNativeModule();
20
- export const NativeWorldState = nativeModule.WorldState;
21
14
  export const NativeLMDBStore = nativeModule.LMDBStore;
15
+ // Internal native functions with numeric log level
16
+ const nativeAvmSimulate = nativeModule.avmSimulate;
17
+ const nativeAvmSimulateWithHintedDbs = nativeModule.avmSimulateWithHintedDbs;
18
+ const nativeCreateCancellationToken = nativeModule.createCancellationToken;
19
+ const nativeCancelSimulation = nativeModule.cancelSimulation;
20
+ /**
21
+ * Create a new cancellation token for C++ simulation.
22
+ * This token can be passed to avmSimulate and later cancelled via cancelSimulation().
23
+ * @returns A handle to a cancellation token
24
+ */ export function createCancellationToken() {
25
+ return nativeCreateCancellationToken();
26
+ }
27
+ /**
28
+ * Signal cancellation to a C++ simulation.
29
+ * The simulation will stop at the next opcode or before the next WorldState write.
30
+ * @param token - The cancellation token previously passed to avmSimulate
31
+ */ export function cancelSimulation(token) {
32
+ nativeCancelSimulation(token);
33
+ }
34
+ /**
35
+ * Maximum number of concurrent AVM simulations. Each simulation spawns a dedicated OS thread,
36
+ * so this controls resource usage. Defaults to 4. Set to 0 for unlimited.
37
+ */ export const AVM_MAX_CONCURRENT_SIMULATIONS = parseInt(process.env.AVM_MAX_CONCURRENT_SIMULATIONS ?? '4', 10);
38
+ const avmSimulationSemaphore = AVM_MAX_CONCURRENT_SIMULATIONS > 0 ? new Semaphore(AVM_MAX_CONCURRENT_SIMULATIONS) : null;
39
+ async function withAvmConcurrencyLimit(fn) {
40
+ if (!avmSimulationSemaphore) {
41
+ return fn();
42
+ }
43
+ await avmSimulationSemaphore.acquire();
44
+ try {
45
+ return await fn();
46
+ } finally{
47
+ avmSimulationSemaphore.release();
48
+ }
49
+ }
50
+ /**
51
+ * AVM simulation function that takes serialized inputs and a contract provider.
52
+ * The contract provider enables C++ to callback to TypeScript for contract data during simulation.
53
+ *
54
+ * Simulations run on dedicated std::threads (not the libuv thread pool), so there is no risk
55
+ * of libuv thread pool exhaustion or deadlock from C++ BlockingCall callbacks.
56
+ * Concurrency is limited by AVM_MAX_CONCURRENT_SIMULATIONS (default 4, 0 = unlimited).
57
+ *
58
+ * @param inputs - Msgpack-serialized AvmFastSimulationInputs buffer
59
+ * @param contractProvider - Object with callbacks for fetching contract instances and classes
60
+ * @param wsdbIpcPath - IPC path of the running aztec-wsdb process. The C++ AVM connects per
61
+ * simulation and constructs an IPC-backed merkle DB.
62
+ * @param logLevel - Optional log level to control C++ verbosity (only used if loggerFunction is provided)
63
+ * @param logger - Optional logger object for C++ logging callbacks
64
+ * @param cancellationToken - Optional token to enable cancellation support
65
+ * @returns Promise resolving to msgpack-serialized AvmCircuitPublicInputs buffer
66
+ */ export function avmSimulate(inputs, contractProvider, wsdbIpcPath, logLevel = 'info', logger, cancellationToken) {
67
+ return withAvmConcurrencyLimit(()=>nativeAvmSimulate(inputs, contractProvider, wsdbIpcPath, LogLevels.indexOf(logLevel), logger ? (level, msg)=>logger[level](msg) : null, cancellationToken));
68
+ }
22
69
  /**
23
70
  * AVM simulation function that uses pre-collected hints from TypeScript simulation.
24
71
  * All contract data and merkle tree hints are included in the AvmCircuitInputs, so no runtime
25
72
  * callbacks to TS or WS pointer are needed.
73
+ *
74
+ * Simulations run on dedicated std::threads (not the libuv thread pool).
75
+ * Concurrency is limited by AVM_MAX_CONCURRENT_SIMULATIONS (default 4, 0 = unlimited).
76
+ *
26
77
  * @param inputs - Msgpack-serialized AvmCircuitInputs (AvmProvingInputs in C++) buffer
78
+ * @param logLevel - Log level to control C++ verbosity
27
79
  * @returns Promise resolving to msgpack-serialized simulation results buffer
28
- */ export const avmSimulateWithHintedDbs = nativeModule.avmSimulateWithHintedDbs;
80
+ */ export function avmSimulateWithHintedDbs(inputs, logLevel = 'info') {
81
+ return withAvmConcurrencyLimit(()=>nativeAvmSimulateWithHintedDbs(inputs, LogLevels.indexOf(logLevel)));
82
+ }
package/package.json CHANGED
@@ -1,31 +1,29 @@
1
1
  {
2
2
  "name": "@aztec/native",
3
- "version": "0.0.1-commit.b655e406",
3
+ "version": "0.0.1-commit.b9865e97",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./dest/index.js"
7
7
  },
8
8
  "scripts": {
9
- "build": "yarn clean && yarn generate && tsc -b",
10
- "build:dev": "tsc -b --watch",
11
- "build:cpp": "PROJECT=$(pwd); cd $(git rev-parse --show-toplevel)/barretenberg/cpp; cmake --preset ${PRESET:-clang16-pic} && cmake --build --preset ${PRESET:-clang16-pic} --target nodejs_module && cd $PROJECT && yarn generate",
12
- "clean:cpp": "rm -rf $(git rev-parse --show-toplevel)/barretenberg/cpp/build-pic",
9
+ "build": "yarn clean && ../scripts/tsc.sh",
10
+ "build:dev": "../scripts/tsc.sh --watch",
13
11
  "clean": "rm -rf ./dest .tsbuildinfo",
14
- "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}",
15
- "generate": "bash scripts/copy_modules.sh"
12
+ "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}"
16
13
  },
17
14
  "inherits": [
18
- "../package.common.json",
19
- "./package.local.json"
15
+ "../package.common.json"
20
16
  ],
21
17
  "dependencies": {
22
- "@aztec/foundation": "0.0.1-commit.b655e406",
18
+ "@aztec/bb.js": "0.0.1-commit.b9865e97",
19
+ "@aztec/foundation": "0.0.1-commit.b9865e97",
23
20
  "msgpackr": "^1.11.2"
24
21
  },
25
22
  "devDependencies": {
26
23
  "@jest/globals": "^30.0.0",
27
24
  "@types/jest": "^30.0.0",
28
25
  "@types/node": "^22.15.17",
26
+ "@typescript/native-preview": "7.0.0-dev.20260113.1",
29
27
  "jest": "^30.0.0",
30
28
  "ts-node": "^10.9.1",
31
29
  "typescript": "^5.3.3"
@@ -1,4 +1,4 @@
1
- import { Fr } from '@aztec/foundation/fields';
1
+ import { Fr } from '@aztec/foundation/curves/bn254';
2
2
  import { MessageHeader, TypedMessage } from '@aztec/foundation/message';
3
3
 
4
4
  import { Encoder, addExtension } from 'msgpackr';
@@ -1,6 +1,8 @@
1
+ import { findNapiBinary } from '@aztec/bb.js';
2
+ import { type LogLevel, LogLevels, type Logger } from '@aztec/foundation/log';
3
+ import { Semaphore } from '@aztec/foundation/queue';
4
+
1
5
  import { createRequire } from 'module';
2
- import { dirname, join } from 'path';
3
- import { fileURLToPath } from 'url';
4
6
 
5
7
  import type { MessageReceiver } from './msgpack_channel.js';
6
8
 
@@ -9,40 +11,190 @@ interface NativeClassCtor {
9
11
  }
10
12
 
11
13
  function loadNativeModule(): Record<string, NativeClassCtor> {
12
- const __filename = fileURLToPath(import.meta.url);
13
- const __dirname = dirname(__filename);
14
+ const require = createRequire(import.meta.url);
15
+ const napiPath = findNapiBinary();
16
+ if (!napiPath) {
17
+ throw new Error('NAPI binary not found for current platform.');
18
+ }
19
+ return require(napiPath);
20
+ }
21
+
22
+ const nativeModule: Record<string, NativeClassCtor | Function> = loadNativeModule();
23
+
24
+ export const NativeLMDBStore: NativeClassCtor = nativeModule.LMDBStore as NativeClassCtor;
25
+
26
+ /**
27
+ * Contract provider interface for callbacks to fetch contract data.
28
+ * These callbacks are invoked by C++ during simulation when contract data is needed.
29
+ */
30
+ export interface ContractProvider {
31
+ /**
32
+ * Fetch a contract instance by address.
33
+ * @param address - The contract address as a string (hex format)
34
+ * @returns Promise resolving to msgpack-serialized ContractInstanceHint buffer, or undefined if not found
35
+ */
36
+ getContractInstance(address: string): Promise<Buffer | undefined>;
37
+ /**
38
+ * Fetch a contract class by class ID.
39
+ * @param classId - The contract class ID as a string (hex format)
40
+ * @returns Promise resolving to msgpack-serialized ContractClassHint buffer, or undefined if not found
41
+ */
42
+ getContractClass(classId: string): Promise<Buffer | undefined>;
43
+
44
+ /**
45
+ * Add contracts from deployment data.
46
+ * @param contractDeploymentData - Msgpack-serialized ContractDeploymentData buffer
47
+ * @returns Promise that resolves when contracts are added
48
+ */
49
+ addContracts(contractDeploymentData: Buffer): Promise<void>;
50
+
51
+ /**
52
+ * Fetch the bytecode commitment for a contract class.
53
+ * @param classId - The contract class ID as a string (hex format)
54
+ * @returns Promise resolving to msgpack-serialized Fr buffer, or undefined if not found
55
+ */
56
+ getBytecodeCommitment(classId: string): Promise<Buffer | undefined>;
14
57
 
15
- // Map Node.js platform/arch to build directory names
16
- const arch = process.arch === 'x64' ? 'amd64' : process.arch;
17
- const platform = process.platform === 'darwin' ? 'macos' : process.platform;
18
- const variant = `${arch}-${platform}`;
58
+ /**
59
+ * Fetch the debug function name for a contract function.
60
+ * @param address - The contract address as a string (hex format)
61
+ * @param selector - The function selector as a string (hex format)
62
+ * @returns Promise resolving to function name string, or undefined if not found
63
+ */
64
+ getDebugFunctionName(address: string, selector: string): Promise<string | undefined>;
19
65
 
20
- const modulePath = join(__dirname, '..', 'build', variant, 'nodejs_module.node');
66
+ /**
67
+ * Create a new checkpoint for the contract database state.
68
+ * Enables rollback to current state in case of a revert.
69
+ * @returns Promise that resolves when checkpoint is created
70
+ */
71
+ createCheckpoint(): Promise<void>;
21
72
 
73
+ /**
74
+ * Commit the current checkpoint, accepting its state as latest.
75
+ * @returns Promise that resolves when checkpoint is committed
76
+ */
77
+ commitCheckpoint(): Promise<void>;
78
+
79
+ /**
80
+ * Revert the current checkpoint, discarding its state and rolling back.
81
+ * @returns Promise that resolves when checkpoint is reverted
82
+ */
83
+ revertCheckpoint(): Promise<void>;
84
+ }
85
+
86
+ // Internal native functions with numeric log level
87
+ const nativeAvmSimulate = nativeModule.avmSimulate as (
88
+ inputs: Buffer,
89
+ contractProvider: ContractProvider,
90
+ wsdbIpcPath: string,
91
+ logLevel: number,
92
+ logFunction?: any,
93
+ cancellationToken?: any,
94
+ ) => Promise<Buffer>;
95
+
96
+ const nativeAvmSimulateWithHintedDbs = nativeModule.avmSimulateWithHintedDbs as (
97
+ inputs: Buffer,
98
+ logLevel: number,
99
+ ) => Promise<Buffer>;
100
+
101
+ const nativeCreateCancellationToken = nativeModule.createCancellationToken as () => any;
102
+ const nativeCancelSimulation = nativeModule.cancelSimulation as (token: any) => void;
103
+
104
+ /**
105
+ * Cancellation token handle used to cancel C++ AVM simulation.
106
+ * The token is created via createCancellationToken() and can be cancelled via cancelSimulation().
107
+ * Pass it to avmSimulate to enable cancellation support.
108
+ */
109
+ export type CancellationToken = any;
110
+
111
+ /**
112
+ * Create a new cancellation token for C++ simulation.
113
+ * This token can be passed to avmSimulate and later cancelled via cancelSimulation().
114
+ * @returns A handle to a cancellation token
115
+ */
116
+ export function createCancellationToken(): CancellationToken {
117
+ return nativeCreateCancellationToken();
118
+ }
119
+
120
+ /**
121
+ * Signal cancellation to a C++ simulation.
122
+ * The simulation will stop at the next opcode or before the next WorldState write.
123
+ * @param token - The cancellation token previously passed to avmSimulate
124
+ */
125
+ export function cancelSimulation(token: CancellationToken): void {
126
+ nativeCancelSimulation(token);
127
+ }
128
+
129
+ /**
130
+ * Maximum number of concurrent AVM simulations. Each simulation spawns a dedicated OS thread,
131
+ * so this controls resource usage. Defaults to 4. Set to 0 for unlimited.
132
+ */
133
+ export const AVM_MAX_CONCURRENT_SIMULATIONS = parseInt(process.env.AVM_MAX_CONCURRENT_SIMULATIONS ?? '4', 10);
134
+ const avmSimulationSemaphore =
135
+ AVM_MAX_CONCURRENT_SIMULATIONS > 0 ? new Semaphore(AVM_MAX_CONCURRENT_SIMULATIONS) : null;
136
+
137
+ async function withAvmConcurrencyLimit<T>(fn: () => Promise<T>): Promise<T> {
138
+ if (!avmSimulationSemaphore) {
139
+ return fn();
140
+ }
141
+ await avmSimulationSemaphore.acquire();
22
142
  try {
23
- const require = createRequire(import.meta.url);
24
- return require(modulePath);
25
- } catch (error) {
26
- throw new Error(
27
- `Failed to load native module for ${variant} from ${modulePath}. ` +
28
- `Supported: amd64-linux, arm64-linux, amd64-macos, arm64-macos. ` +
29
- `Error: ${error}`,
30
- );
143
+ return await fn();
144
+ } finally {
145
+ avmSimulationSemaphore.release();
31
146
  }
32
147
  }
33
148
 
34
- const nativeModule: Record<string, NativeClassCtor | Function> = loadNativeModule();
35
-
36
- export const NativeWorldState: NativeClassCtor = nativeModule.WorldState as NativeClassCtor;
37
- export const NativeLMDBStore: NativeClassCtor = nativeModule.LMDBStore as NativeClassCtor;
149
+ /**
150
+ * AVM simulation function that takes serialized inputs and a contract provider.
151
+ * The contract provider enables C++ to callback to TypeScript for contract data during simulation.
152
+ *
153
+ * Simulations run on dedicated std::threads (not the libuv thread pool), so there is no risk
154
+ * of libuv thread pool exhaustion or deadlock from C++ BlockingCall callbacks.
155
+ * Concurrency is limited by AVM_MAX_CONCURRENT_SIMULATIONS (default 4, 0 = unlimited).
156
+ *
157
+ * @param inputs - Msgpack-serialized AvmFastSimulationInputs buffer
158
+ * @param contractProvider - Object with callbacks for fetching contract instances and classes
159
+ * @param wsdbIpcPath - IPC path of the running aztec-wsdb process. The C++ AVM connects per
160
+ * simulation and constructs an IPC-backed merkle DB.
161
+ * @param logLevel - Optional log level to control C++ verbosity (only used if loggerFunction is provided)
162
+ * @param logger - Optional logger object for C++ logging callbacks
163
+ * @param cancellationToken - Optional token to enable cancellation support
164
+ * @returns Promise resolving to msgpack-serialized AvmCircuitPublicInputs buffer
165
+ */
166
+ export function avmSimulate(
167
+ inputs: Buffer,
168
+ contractProvider: ContractProvider,
169
+ wsdbIpcPath: string,
170
+ logLevel: LogLevel = 'info',
171
+ logger?: Logger,
172
+ cancellationToken?: CancellationToken,
173
+ ): Promise<Buffer> {
174
+ return withAvmConcurrencyLimit(() =>
175
+ nativeAvmSimulate(
176
+ inputs,
177
+ contractProvider,
178
+ wsdbIpcPath,
179
+ LogLevels.indexOf(logLevel),
180
+ logger ? (level: LogLevel, msg: string) => logger[level](msg) : null,
181
+ cancellationToken,
182
+ ),
183
+ );
184
+ }
38
185
 
39
186
  /**
40
187
  * AVM simulation function that uses pre-collected hints from TypeScript simulation.
41
188
  * All contract data and merkle tree hints are included in the AvmCircuitInputs, so no runtime
42
189
  * callbacks to TS or WS pointer are needed.
190
+ *
191
+ * Simulations run on dedicated std::threads (not the libuv thread pool).
192
+ * Concurrency is limited by AVM_MAX_CONCURRENT_SIMULATIONS (default 4, 0 = unlimited).
193
+ *
43
194
  * @param inputs - Msgpack-serialized AvmCircuitInputs (AvmProvingInputs in C++) buffer
195
+ * @param logLevel - Log level to control C++ verbosity
44
196
  * @returns Promise resolving to msgpack-serialized simulation results buffer
45
197
  */
46
- export const avmSimulateWithHintedDbs: (inputs: Buffer) => Promise<Buffer> = nativeModule.avmSimulateWithHintedDbs as (
47
- inputs: Buffer,
48
- ) => Promise<Buffer>;
198
+ export function avmSimulateWithHintedDbs(inputs: Buffer, logLevel: LogLevel = 'info'): Promise<Buffer> {
199
+ return withAvmConcurrencyLimit(() => nativeAvmSimulateWithHintedDbs(inputs, LogLevels.indexOf(logLevel)));
200
+ }