ic-mops 0.31.1 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/cli.ts +14 -0
  2. package/commands/bench/bench-canister.mo +87 -0
  3. package/commands/bench/user-bench.mo +14 -0
  4. package/commands/bench.ts +335 -0
  5. package/commands/publish.ts +4 -0
  6. package/commands/sources.ts +4 -4
  7. package/declarations/bench/bench.did +26 -0
  8. package/declarations/bench/bench.did.d.ts +26 -0
  9. package/declarations/bench/bench.did.js +26 -0
  10. package/declarations/bench/index.d.ts +50 -0
  11. package/declarations/bench/index.js +41 -0
  12. package/dist/cli.js +13 -0
  13. package/dist/commands/bench/bench-canister.mo +87 -0
  14. package/dist/commands/bench/user-bench.mo +14 -0
  15. package/dist/commands/bench.d.ts +11 -0
  16. package/dist/commands/bench.js +275 -0
  17. package/dist/commands/publish.js +4 -0
  18. package/dist/commands/sources.d.ts +2 -1
  19. package/dist/commands/sources.js +4 -4
  20. package/dist/declarations/bench/bench.did +26 -0
  21. package/dist/declarations/bench/bench.did.d.ts +26 -0
  22. package/dist/declarations/bench/bench.did.js +26 -0
  23. package/dist/declarations/bench/index.d.ts +50 -0
  24. package/dist/declarations/bench/index.js +41 -0
  25. package/dist/helpers/get-dfx-version.d.ts +1 -0
  26. package/dist/helpers/get-dfx-version.js +9 -0
  27. package/dist/helpers/get-moc-path.d.ts +1 -0
  28. package/dist/helpers/get-moc-path.js +11 -0
  29. package/dist/helpers/get-moc-version.d.ts +1 -0
  30. package/dist/helpers/get-moc-version.js +7 -0
  31. package/dist/package.json +81 -80
  32. package/dist/resolve-packages.js +1 -1
  33. package/dist/vessel.d.ts +2 -1
  34. package/dist/vessel.js +9 -7
  35. package/helpers/get-dfx-version.ts +10 -0
  36. package/helpers/get-moc-path.ts +12 -0
  37. package/helpers/get-moc-version.ts +8 -0
  38. package/package.json +81 -80
  39. package/resolve-packages.ts +1 -1
  40. package/tsconfig.json +2 -0
  41. package/vessel.ts +10 -8
package/dist/cli.js CHANGED
@@ -22,6 +22,7 @@ import { bump } from './commands/bump.js';
22
22
  import { sync } from './commands/sync.js';
23
23
  import { outdated } from './commands/outdated.js';
24
24
  import { update } from './commands/update.js';
25
+ import { bench } from './commands/bench.js';
25
26
  import { transferOwnership } from './commands/transfer-ownership.js';
26
27
  // import {docs} from './commands/docs.js';
27
28
  program.name('mops');
@@ -178,6 +179,18 @@ program
178
179
  .action(async (filter, options) => {
179
180
  await test(filter, options);
180
181
  });
182
+ // bench
183
+ program
184
+ .command('bench [filter]')
185
+ .description('Run benchmarks')
186
+ .addOption(new Option('--save', 'Save benchmark results to .bench/<filename>.json'))
187
+ .addOption(new Option('--compare', 'Run benchmark and compare results with .bench/<filename>.json'))
188
+ .addOption(new Option('--gc <gc>', 'Garbage collector').choices(['copying', 'compacting', 'generational', 'incremental']).default('incremental'))
189
+ // .addOption(new Option('--force-gc', 'Force GC'))
190
+ .addOption(new Option('--verbose', 'Show more information'))
191
+ .action(async (filter, options) => {
192
+ await bench(filter, options);
193
+ });
181
194
  // template
182
195
  program
183
196
  .command('template')
@@ -0,0 +1,87 @@
1
+ import Nat64 "mo:base/Nat64";
2
+ import Nat "mo:base/Nat";
3
+ import Debug "mo:base/Debug";
4
+ import ExperimentalInternetComputer "mo:base/ExperimentalInternetComputer";
5
+ import Prim "mo:prim";
6
+ import Bench "mo:bench";
7
+
8
+ import UserBench "./user-bench";
9
+
10
+ actor class() {
11
+ var benchOpt : ?Bench.Bench = null;
12
+
13
+ public func init() : async Bench.BenchSchema {
14
+ let bench = UserBench.init();
15
+ benchOpt := ?bench;
16
+ bench.getSchema();
17
+ };
18
+
19
+ public query func getSchema() : async Bench.BenchSchema {
20
+ let ?bench = benchOpt else Debug.trap("bench not initialized");
21
+ bench.getSchema();
22
+ };
23
+
24
+ func _getStats() : Bench.BenchResult {
25
+ {
26
+ instructions = 0;
27
+ rts_heap_size = Prim.rts_heap_size();
28
+ rts_memory_size = Prim.rts_memory_size();
29
+ rts_total_allocation = Prim.rts_total_allocation();
30
+ rts_mutator_instructions = Prim.rts_mutator_instructions();
31
+ rts_collector_instructions = Prim.rts_collector_instructions();
32
+ }
33
+ };
34
+
35
+ func _diffStats(before : Bench.BenchResult, after : Bench.BenchResult) : Bench.BenchResult {
36
+ {
37
+ instructions = after.instructions - before.instructions;
38
+ rts_heap_size = after.rts_heap_size - before.rts_heap_size;
39
+ rts_memory_size = after.rts_memory_size - before.rts_memory_size;
40
+ rts_total_allocation = after.rts_total_allocation - before.rts_total_allocation;
41
+ rts_mutator_instructions = after.rts_mutator_instructions - before.rts_mutator_instructions;
42
+ rts_collector_instructions = after.rts_collector_instructions - before.rts_collector_instructions;
43
+ }
44
+ };
45
+
46
+ func _runCell(rowIndex : Nat, colIndex : Nat) : Bench.BenchResult {
47
+ let ?bench = benchOpt else Debug.trap("bench not initialized");
48
+ let statsBefore = _getStats();
49
+
50
+ let instructions = Nat64.toNat(ExperimentalInternetComputer.countInstructions(func() {
51
+ bench.runCell(rowIndex, colIndex);
52
+ }));
53
+
54
+ let statsAfter = _getStats();
55
+ _diffStats(statsBefore, { statsAfter with instructions });
56
+ };
57
+
58
+ func _runCellAwait(rowIndex : Nat, colIndex : Nat) : async Bench.BenchResult {
59
+ let ?bench = benchOpt else Debug.trap("bench not initialized");
60
+ let statsBefore = _getStats();
61
+
62
+ let instructions = Nat64.toNat(ExperimentalInternetComputer.countInstructions(func() {
63
+ bench.runCell(rowIndex, colIndex);
64
+ }));
65
+
66
+ await (func() : async () {})();
67
+
68
+ let statsAfter = _getStats();
69
+ _diffStats(statsBefore, { statsAfter with instructions });
70
+ };
71
+
72
+ public query func getStats() : async Bench.BenchResult {
73
+ _getStats();
74
+ };
75
+
76
+ public query func runCellQuery(rowIndex : Nat, colIndex : Nat) : async Bench.BenchResult {
77
+ _runCell(rowIndex, colIndex);
78
+ };
79
+
80
+ public func runCellUpdate(rowIndex : Nat, colIndex : Nat) : async Bench.BenchResult {
81
+ _runCell(rowIndex, colIndex);
82
+ };
83
+
84
+ public func runCellUpdateAwait(rowIndex : Nat, colIndex : Nat) : async Bench.BenchResult {
85
+ await _runCellAwait(rowIndex, colIndex);
86
+ };
87
+ };
@@ -0,0 +1,14 @@
1
+ import Nat "mo:base/Nat";
2
+ import Iter "mo:base/Iter";
3
+ import Buffer "mo:base/Buffer";
4
+ import Vector "mo:vector/Class";
5
+ import Bench "mo:bench";
6
+
7
+ // placeholder file that will be replaced with the *.bench.mo file
8
+ module {
9
+ public func init() : Bench.Bench {
10
+ let bench = Bench.Bench();
11
+ // benchmark code goes here...
12
+ bench;
13
+ };
14
+ };
@@ -0,0 +1,11 @@
1
+ type BenchOptions = {
2
+ dfx?: string;
3
+ moc?: string;
4
+ gc?: 'copying' | 'compacting' | 'generational' | 'incremental';
5
+ forceGc?: boolean;
6
+ save?: boolean;
7
+ compare?: boolean;
8
+ verbose?: boolean;
9
+ };
10
+ export declare function bench(filter?: string, options?: BenchOptions): Promise<boolean>;
11
+ export {};
@@ -0,0 +1,275 @@
1
+ import { execSync } from 'node:child_process';
2
+ import path from 'node:path';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import chalk from 'chalk';
6
+ import { globSync } from 'glob';
7
+ import { markdownTable } from 'markdown-table';
8
+ import logUpdate from 'log-update';
9
+ import { getRootDir } from '../mops.js';
10
+ import { parallel } from '../parallel.js';
11
+ import { createActor } from '../declarations/bench/index.js';
12
+ import { absToRel } from './test/utils.js';
13
+ import { getMocVersion } from '../helpers/get-moc-version.js';
14
+ import { getDfxVersion } from '../helpers/get-dfx-version.js';
15
+ import { getMocPath } from '../helpers/get-moc-path.js';
16
+ import { sources } from './sources.js';
17
+ import { execaCommand } from 'execa';
18
+ let ignore = [
19
+ '**/node_modules/**',
20
+ '**/.mops/**',
21
+ '**/.vessel/**',
22
+ '**/.git/**',
23
+ ];
24
+ let globConfig = {
25
+ nocase: true,
26
+ ignore: ignore,
27
+ };
28
+ export async function bench(filter = '', options = {}) {
29
+ let defaultOptions = {
30
+ moc: getMocVersion(),
31
+ dfx: getDfxVersion(),
32
+ gc: 'incremental',
33
+ forceGc: true,
34
+ save: false,
35
+ compare: false,
36
+ verbose: false,
37
+ };
38
+ options = { ...defaultOptions, ...options };
39
+ options.verbose && console.log(options);
40
+ let rootDir = getRootDir();
41
+ let globStr = '**/bench?(mark)/**/*.bench.mo';
42
+ if (filter) {
43
+ globStr = `**/bench?(mark)/**/*${filter}*.mo`;
44
+ }
45
+ let files = globSync(path.join(rootDir, globStr), globConfig);
46
+ if (!files.length) {
47
+ if (filter) {
48
+ console.log(`No benchmark files found for filter '${filter}'`);
49
+ return false;
50
+ }
51
+ console.log('No *.bench.mo files found');
52
+ console.log('Put your benchmark code in \'bench\' directory in *.bench.mo files');
53
+ return false;
54
+ }
55
+ files.sort();
56
+ let benchDir = `${getRootDir()}/.mops/.bench/`;
57
+ fs.rmSync(benchDir, { recursive: true, force: true });
58
+ fs.mkdirSync(benchDir, { recursive: true });
59
+ console.log('Benchmark files:');
60
+ for (let file of files) {
61
+ console.log(chalk.gray(`• ${absToRel(file)}`));
62
+ }
63
+ console.log('');
64
+ console.log('='.repeat(50));
65
+ console.log('');
66
+ console.log('Starting dfx replica...');
67
+ startDfx(options.verbose);
68
+ console.log('Deploying canisters...');
69
+ await parallel(os.cpus().length, files, async (file) => {
70
+ try {
71
+ await deployBenchFile(file, options);
72
+ }
73
+ catch (err) {
74
+ console.error('Unexpected error. Stopping dfx replica...');
75
+ stopDfx(options.verbose);
76
+ throw err;
77
+ }
78
+ });
79
+ await parallel(1, files, async (file) => {
80
+ console.log('\n' + '—'.repeat(50));
81
+ console.log(`\nRunning ${chalk.gray(absToRel(file))}...`);
82
+ console.log('');
83
+ try {
84
+ await runBenchFile(file, options);
85
+ }
86
+ catch (err) {
87
+ console.error('Unexpected error. Stopping dfx replica...');
88
+ stopDfx(options.verbose);
89
+ throw err;
90
+ }
91
+ });
92
+ console.log('Stopping dfx replica...');
93
+ stopDfx(options.verbose);
94
+ fs.rmSync(benchDir, { recursive: true, force: true });
95
+ return true;
96
+ }
97
+ function getMocArgs(options) {
98
+ let args = '';
99
+ if (options.forceGc) {
100
+ args += ' --force-gc';
101
+ }
102
+ if (options.gc) {
103
+ args += ` --${options.gc}-gc`;
104
+ }
105
+ return args;
106
+ }
107
+ function dfxJson(canisterName, options = {}) {
108
+ options || console.log(options);
109
+ let canisters = {};
110
+ if (canisterName) {
111
+ canisters[canisterName] = {
112
+ type: 'custom',
113
+ wasm: 'canister.wasm',
114
+ candid: 'canister.did',
115
+ };
116
+ }
117
+ return {
118
+ version: 1,
119
+ canisters,
120
+ defaults: {
121
+ build: {
122
+ packtool: 'mops sources',
123
+ },
124
+ },
125
+ networks: {
126
+ local: {
127
+ type: 'ephemeral',
128
+ bind: '127.0.0.1:4944',
129
+ },
130
+ },
131
+ };
132
+ }
133
+ function startDfx(verbose = false) {
134
+ stopDfx(verbose);
135
+ let dir = path.join(getRootDir(), '.mops/.bench');
136
+ fs.writeFileSync(path.join(dir, 'dfx.json'), JSON.stringify(dfxJson(''), null, 2));
137
+ execSync('dfx start --background --clean' + (verbose ? '' : ' -qqqq'), { cwd: dir, stdio: ['inherit', verbose ? 'inherit' : 'ignore', 'inherit'] });
138
+ }
139
+ function stopDfx(verbose = false) {
140
+ let dir = path.join(getRootDir(), '.mops/.bench');
141
+ execSync('dfx stop' + (verbose ? '' : ' -qqqq'), { cwd: dir, stdio: ['pipe', verbose ? 'inherit' : 'ignore', 'pipe'] });
142
+ }
143
+ async function deployBenchFile(file, options = {}) {
144
+ let rootDir = getRootDir();
145
+ let tempDir = path.join(rootDir, '.mops/.bench/', path.parse(file).name);
146
+ let canisterName = path.parse(file).name;
147
+ // prepare temp files
148
+ fs.mkdirSync(tempDir, { recursive: true });
149
+ fs.writeFileSync(path.join(tempDir, 'dfx.json'), JSON.stringify(dfxJson(canisterName, options), null, 2));
150
+ fs.cpSync(new URL('./bench/bench-canister.mo', import.meta.url), path.join(tempDir, 'canister.mo'));
151
+ fs.cpSync(file, path.join(tempDir, 'user-bench.mo'));
152
+ // build canister
153
+ let mocPath = getMocPath();
154
+ let mocArgs = getMocArgs(options);
155
+ options.verbose && console.time(`build ${canisterName}`);
156
+ await execaCommand(`${mocPath} -c --idl canister.mo ${mocArgs} ${(await sources({ cwd: tempDir })).join(' ')}`, { cwd: tempDir, stdio: options.verbose ? 'pipe' : ['pipe', 'ignore', 'pipe'] });
157
+ options.verbose && console.timeEnd(`build ${canisterName}`);
158
+ // deploy canister
159
+ options.verbose && console.time(`deploy ${canisterName}`);
160
+ await execaCommand(`dfx deploy ${canisterName} --mode reinstall --yes --identity anonymous`, { cwd: tempDir, stdio: options.verbose ? 'pipe' : ['pipe', 'ignore', 'pipe'] });
161
+ options.verbose && console.timeEnd(`deploy ${canisterName}`);
162
+ // init bench
163
+ options.verbose && console.time(`init ${canisterName}`);
164
+ let canisterId = execSync(`dfx canister id ${canisterName}`, { cwd: tempDir }).toString().trim();
165
+ let actor = await createActor(canisterId, {
166
+ agentOptions: {
167
+ host: 'http://127.0.0.1:4944',
168
+ },
169
+ });
170
+ await actor.init();
171
+ options.verbose && console.timeEnd(`init ${canisterName}`);
172
+ }
173
+ async function runBenchFile(file, options = {}) {
174
+ let rootDir = getRootDir();
175
+ let tempDir = path.join(rootDir, '.mops/.bench/', path.parse(file).name);
176
+ let canisterName = path.parse(file).name;
177
+ let canisterId = execSync(`dfx canister id ${canisterName}`, { cwd: tempDir }).toString().trim();
178
+ let actor = await createActor(canisterId, {
179
+ agentOptions: {
180
+ host: 'http://127.0.0.1:4944',
181
+ },
182
+ });
183
+ let schema = await actor.getSchema();
184
+ // load previous results
185
+ let prevResults;
186
+ let resultsJsonFile = path.join(rootDir, '.bench', `${path.parse(file).name}.json`);
187
+ if (options.compare) {
188
+ if (fs.existsSync(resultsJsonFile)) {
189
+ let prevResultsJson = JSON.parse(fs.readFileSync(resultsJsonFile).toString());
190
+ prevResults = new Map(prevResultsJson.results);
191
+ }
192
+ else {
193
+ console.log(chalk.yellow(`No previous results found "${resultsJsonFile}"`));
194
+ }
195
+ }
196
+ let results = new Map();
197
+ let formatNumber = (n) => {
198
+ return n.toLocaleString('en-US').replaceAll(',', '_');
199
+ };
200
+ let getTable = (prop) => {
201
+ let resArr = [['', ...schema.cols]];
202
+ for (let [_rowIndex, row] of schema.rows.entries()) {
203
+ let curRow = [row];
204
+ for (let [_colIndex, col] of schema.cols.entries()) {
205
+ let res = results.get(`${row}:${col}`);
206
+ if (res) {
207
+ // compare with previous results
208
+ let diff = '';
209
+ if (options.compare && prevResults) {
210
+ let prevRes = prevResults.get(`${row}:${col}`);
211
+ if (prevRes) {
212
+ let percent = (Number(res[prop]) - Number(prevRes[prop])) / Number(prevRes[prop]) * 100;
213
+ let sign = percent > 0 ? '+' : '';
214
+ let percentText = percent == 0 ? '0%' : sign + percent.toFixed(2) + '%';
215
+ // diff = ' (' + (percent > 0 ? chalk.red(percentText) : chalk.green(percentText)) + ')'; // alignment is broken
216
+ diff = ' (' + percentText + ')';
217
+ }
218
+ else {
219
+ diff = chalk.yellow(' (no previous results)');
220
+ }
221
+ }
222
+ // add to table
223
+ curRow.push(formatNumber(res[prop]) + diff);
224
+ }
225
+ else {
226
+ curRow.push('');
227
+ }
228
+ }
229
+ resArr.push(curRow);
230
+ }
231
+ return markdownTable(resArr, { align: ['l', ...'r'.repeat(schema.cols.length)] });
232
+ };
233
+ let printResults = () => {
234
+ logUpdate(`
235
+ \n${chalk.bold(schema.name)}
236
+ ${schema.description ? '\n' + chalk.gray(schema.description) : ''}
237
+ \n\n${chalk.blue('Instructions')}\n\n${getTable('instructions')}
238
+ \n\n${chalk.blue('Heap')}\n\n${getTable('rts_heap_size')}
239
+ `);
240
+ };
241
+ printResults();
242
+ // run all cells
243
+ for (let [rowIndex, row] of schema.rows.entries()) {
244
+ for (let [colIndex, col] of schema.cols.entries()) {
245
+ // let res = await actor.runCellQuery(BigInt(rowIndex), BigInt(colIndex));
246
+ // let res = await actor.runCellUpdate(BigInt(rowIndex), BigInt(colIndex));
247
+ let res = await actor.runCellUpdateAwait(BigInt(rowIndex), BigInt(colIndex));
248
+ results.set(`${row}:${col}`, res);
249
+ printResults();
250
+ }
251
+ }
252
+ logUpdate.done();
253
+ // save results
254
+ if (options.save) {
255
+ console.log(`Saving results to ${chalk.gray(absToRel(resultsJsonFile))}`);
256
+ let json = {
257
+ version: 1,
258
+ moc: options.moc,
259
+ dfx: options.dfx,
260
+ gc: options.gc,
261
+ forceGc: options.forceGc,
262
+ results: Array.from(results.entries()),
263
+ };
264
+ fs.mkdirSync(path.dirname(resultsJsonFile), { recursive: true });
265
+ fs.writeFileSync(resultsJsonFile, JSON.stringify(json, (_, val) => {
266
+ if (typeof val === 'bigint') {
267
+ return Number(val);
268
+ }
269
+ else {
270
+ return val;
271
+ }
272
+ }, 2));
273
+ }
274
+ return { schema, results };
275
+ }
@@ -176,6 +176,10 @@ export async function publish(options = {}) {
176
176
  '!tests/**',
177
177
  '!**/*.test.mo',
178
178
  '!**/*.Test.mo',
179
+ '!bench/**',
180
+ '!benchmark/**',
181
+ '!**/*.bench.mo',
182
+ '!**/*.Bench.mo',
179
183
  ];
180
184
  let files = config.package.files || ['**/*.mo'];
181
185
  files = [...files, ...defaultFiles];
@@ -1,3 +1,4 @@
1
- export declare function sources({ verbose }?: {
1
+ export declare function sources({ verbose, cwd }?: {
2
2
  verbose?: boolean | undefined;
3
+ cwd?: string | undefined;
3
4
  }): Promise<(string | undefined)[]>;
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import { checkConfigFile, formatDir, formatGithubDir, getDependencyType, readConfig } from '../mops.js';
4
4
  import { resolvePackages } from '../resolve-packages.js';
5
5
  // TODO: resolve conflicts
6
- export async function sources({ verbose = false } = {}) {
6
+ export async function sources({ verbose = false, cwd = process.cwd() } = {}) {
7
7
  if (!checkConfigFile()) {
8
8
  return [];
9
9
  }
@@ -13,13 +13,13 @@ export async function sources({ verbose = false } = {}) {
13
13
  let depType = getDependencyType(version);
14
14
  let pkgDir;
15
15
  if (depType === 'local') {
16
- pkgDir = path.relative(process.cwd(), version);
16
+ pkgDir = path.relative(cwd, version);
17
17
  }
18
18
  else if (depType === 'github') {
19
- pkgDir = path.relative(process.cwd(), formatGithubDir(name, version));
19
+ pkgDir = path.relative(cwd, formatGithubDir(name, version));
20
20
  }
21
21
  else if (depType === 'mops') {
22
- pkgDir = path.relative(process.cwd(), formatDir(name, version));
22
+ pkgDir = path.relative(cwd, formatDir(name, version));
23
23
  }
24
24
  else {
25
25
  return;
@@ -0,0 +1,26 @@
1
+ type anon_class_10_1 =
2
+ service {
3
+ getSchema: () -> (BenchSchema) query;
4
+ getStats: () -> (BenchResult) query;
5
+ init: () -> (BenchSchema);
6
+ runCellQuery: (nat, nat) -> (BenchResult) query;
7
+ runCellUpdate: (nat, nat) -> (BenchResult);
8
+ runCellUpdateAwait: (nat, nat) -> (BenchResult);
9
+ };
10
+ type BenchSchema =
11
+ record {
12
+ cols: vec text;
13
+ description: text;
14
+ name: text;
15
+ rows: vec text;
16
+ };
17
+ type BenchResult =
18
+ record {
19
+ instructions: int;
20
+ rts_collector_instructions: int;
21
+ rts_heap_size: int;
22
+ rts_memory_size: int;
23
+ rts_mutator_instructions: int;
24
+ rts_total_allocation: int;
25
+ };
26
+ service : () -> anon_class_10_1
@@ -0,0 +1,26 @@
1
+ import type { Principal } from '@dfinity/principal';
2
+ import type { ActorMethod } from '@dfinity/agent';
3
+
4
+ export interface BenchResult {
5
+ 'instructions' : bigint,
6
+ 'rts_memory_size' : bigint,
7
+ 'rts_total_allocation' : bigint,
8
+ 'rts_collector_instructions' : bigint,
9
+ 'rts_mutator_instructions' : bigint,
10
+ 'rts_heap_size' : bigint,
11
+ }
12
+ export interface BenchSchema {
13
+ 'cols' : Array<string>,
14
+ 'name' : string,
15
+ 'rows' : Array<string>,
16
+ 'description' : string,
17
+ }
18
+ export interface anon_class_10_1 {
19
+ 'getSchema' : ActorMethod<[], BenchSchema>,
20
+ 'getStats' : ActorMethod<[], BenchResult>,
21
+ 'init' : ActorMethod<[], BenchSchema>,
22
+ 'runCellQuery' : ActorMethod<[bigint, bigint], BenchResult>,
23
+ 'runCellUpdate' : ActorMethod<[bigint, bigint], BenchResult>,
24
+ 'runCellUpdateAwait' : ActorMethod<[bigint, bigint], BenchResult>,
25
+ }
26
+ export interface _SERVICE extends anon_class_10_1 {}
@@ -0,0 +1,26 @@
1
+ export const idlFactory = ({ IDL }) => {
2
+ const BenchSchema = IDL.Record({
3
+ 'cols' : IDL.Vec(IDL.Text),
4
+ 'name' : IDL.Text,
5
+ 'rows' : IDL.Vec(IDL.Text),
6
+ 'description' : IDL.Text,
7
+ });
8
+ const BenchResult = IDL.Record({
9
+ 'instructions' : IDL.Int,
10
+ 'rts_memory_size' : IDL.Int,
11
+ 'rts_total_allocation' : IDL.Int,
12
+ 'rts_collector_instructions' : IDL.Int,
13
+ 'rts_mutator_instructions' : IDL.Int,
14
+ 'rts_heap_size' : IDL.Int,
15
+ });
16
+ const anon_class_10_1 = IDL.Service({
17
+ 'getSchema' : IDL.Func([], [BenchSchema], ['query']),
18
+ 'getStats' : IDL.Func([], [BenchResult], ['query']),
19
+ 'init' : IDL.Func([], [BenchSchema], []),
20
+ 'runCellQuery' : IDL.Func([IDL.Nat, IDL.Nat], [BenchResult], ['query']),
21
+ 'runCellUpdate' : IDL.Func([IDL.Nat, IDL.Nat], [BenchResult], []),
22
+ 'runCellUpdateAwait' : IDL.Func([IDL.Nat, IDL.Nat], [BenchResult], []),
23
+ });
24
+ return anon_class_10_1;
25
+ };
26
+ export const init = ({ IDL }) => { return []; };
@@ -0,0 +1,50 @@
1
+ import type {
2
+ ActorSubclass,
3
+ HttpAgentOptions,
4
+ ActorConfig,
5
+ Agent,
6
+ } from "@dfinity/agent";
7
+ import type { Principal } from "@dfinity/principal";
8
+ import type { IDL } from "@dfinity/candid";
9
+
10
+ import { _SERVICE } from './bench.did';
11
+
12
+ export declare const idlFactory: IDL.InterfaceFactory;
13
+ export declare const canisterId: string;
14
+
15
+ export declare interface CreateActorOptions {
16
+ /**
17
+ * @see {@link Agent}
18
+ */
19
+ agent?: Agent;
20
+ /**
21
+ * @see {@link HttpAgentOptions}
22
+ */
23
+ agentOptions?: HttpAgentOptions;
24
+ /**
25
+ * @see {@link ActorConfig}
26
+ */
27
+ actorOptions?: ActorConfig;
28
+ }
29
+
30
+ /**
31
+ * Intializes an {@link ActorSubclass}, configured with the provided SERVICE interface of a canister.
32
+ * @constructs {@link ActorSubClass}
33
+ * @param {string | Principal} canisterId - ID of the canister the {@link Actor} will talk to
34
+ * @param {CreateActorOptions} options - see {@link CreateActorOptions}
35
+ * @param {CreateActorOptions["agent"]} options.agent - a pre-configured agent you'd like to use. Supercedes agentOptions
36
+ * @param {CreateActorOptions["agentOptions"]} options.agentOptions - options to set up a new agent
37
+ * @see {@link HttpAgentOptions}
38
+ * @param {CreateActorOptions["actorOptions"]} options.actorOptions - options for the Actor
39
+ * @see {@link ActorConfig}
40
+ */
41
+ export declare const createActor: (
42
+ canisterId: string | Principal,
43
+ options?: CreateActorOptions
44
+ ) => ActorSubclass<_SERVICE>;
45
+
46
+ /**
47
+ * Intialized Actor using default settings, ready to talk to a canister using its candid interface
48
+ * @constructs {@link ActorSubClass}
49
+ */
50
+ export declare const bench: ActorSubclass<_SERVICE>;
@@ -0,0 +1,41 @@
1
+ import { Actor, HttpAgent } from "@dfinity/agent";
2
+
3
+ // Imports and re-exports candid interface
4
+ import { idlFactory } from "./bench.did.js";
5
+ export { idlFactory } from "./bench.did.js";
6
+
7
+ /* CANISTER_ID is replaced by webpack based on node environment
8
+ * Note: canister environment variable will be standardized as
9
+ * process.env.CANISTER_ID_<CANISTER_NAME_UPPERCASE>
10
+ * beginning in dfx 0.15.0
11
+ */
12
+ export const canisterId =
13
+ process.env.CANISTER_ID_BENCH ||
14
+ process.env.BENCH_CANISTER_ID;
15
+
16
+ export const createActor = (canisterId, options = {}) => {
17
+ const agent = options.agent || new HttpAgent({ ...options.agentOptions });
18
+
19
+ if (options.agent && options.agentOptions) {
20
+ console.warn(
21
+ "Detected both agent and agentOptions passed to createActor. Ignoring agentOptions and proceeding with the provided agent."
22
+ );
23
+ }
24
+
25
+ // Fetch root key for certificate validation during development
26
+ if (process.env.DFX_NETWORK !== "ic") {
27
+ agent.fetchRootKey().catch((err) => {
28
+ console.warn(
29
+ "Unable to fetch root key. Check to ensure that your local replica is running"
30
+ );
31
+ console.error(err);
32
+ });
33
+ }
34
+
35
+ // Creates an actor with using the candid interface and the HttpAgent
36
+ return Actor.createActor(idlFactory, {
37
+ agent,
38
+ canisterId,
39
+ ...options.actorOptions,
40
+ });
41
+ };
@@ -0,0 +1 @@
1
+ export declare function getDfxVersion(): string;
@@ -0,0 +1,9 @@
1
+ import { execSync } from 'node:child_process';
2
+ export function getDfxVersion() {
3
+ try {
4
+ let res = execSync('dfx --version').toString();
5
+ return res.trim().split('dfx ')[1] || '';
6
+ }
7
+ catch { }
8
+ return '';
9
+ }
@@ -0,0 +1 @@
1
+ export declare function getMocPath(): string;
@@ -0,0 +1,11 @@
1
+ import { execSync } from 'node:child_process';
2
+ export function getMocPath() {
3
+ let mocPath = process.env.DFX_MOC_PATH;
4
+ if (!mocPath) {
5
+ mocPath = execSync('dfx cache show').toString().trim() + '/moc';
6
+ }
7
+ if (!mocPath) {
8
+ mocPath = 'moc';
9
+ }
10
+ return mocPath;
11
+ }
@@ -0,0 +1 @@
1
+ export declare function getMocVersion(): string;
@@ -0,0 +1,7 @@
1
+ import { execSync } from 'node:child_process';
2
+ import { getMocPath } from './get-moc-path.js';
3
+ export function getMocVersion() {
4
+ let mocPath = getMocPath();
5
+ let match = execSync(mocPath).toString().trim().match(/Motoko compiler ([^\s]+) .*/);
6
+ return match?.[1] || '';
7
+ }