-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathinvariant.ts
More file actions
853 lines (783 loc) · 27.4 KB
/
invariant.ts
File metadata and controls
853 lines (783 loc) · 27.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
import type { EventEmitter } from "node:events";
import { resolve } from "node:path";
import type { Simnet } from "@stacks/clarinet-sdk";
import type { ContractInterfaceFunction } from "@stacks/clarinet-sdk-wasm";
import { Cl, cvToJSON, cvToString } from "@stacks/transactions";
import { dim, green, red, underline, yellow } from "ansicolor";
import fc from "fast-check";
import { DialerRegistry, PostDialerError, PreDialerError } from "./dialer";
import { reporter } from "./heatstroke";
import type { Statistics } from "./heatstroke.types";
import type { LocalContext } from "./invariant.types";
import {
getFailureFilePath,
loadFailures,
persistFailure,
} from "./persistence";
import {
argsToCV,
functionToArbitrary,
getContractNameFromContractId,
getFunctionsListForContract,
LOG_DIVIDER,
} from "./shared";
import type { EnrichedContractInterfaceFunction } from "./shared.types";
import {
buildTraitReferenceMap,
enrichInterfaceWithTraitData,
extractProjectTraitImplementations,
getNonTestableTraitFunctions,
isTraitReferenceFunction,
} from "./traits";
import type { ImplementedTraitType } from "./traits.types";
/**
* Runs invariant testing on the target contract and logs the progress. Reports
* the test results through a custom reporter.
* @param simnet The Simnet instance.
* @param resetSession Resets the simnet session to a clean state.
* @param rendezvousList The list of contract IDs for each target contract.
* @param rendezvousAllFunctions The map of all function interfaces for each
* target contract.
* @param seed The seed for reproducible invariant testing.
* @param runs The number of test runs.
* @param dial The path to the dialer file.
* @param bail Stop execution after the first failure and prevent further
* shrinking.
* @param regr Whether to run regression tests only.
* @param radio The custom logging event emitter.
* @returns void
*/
export const checkInvariants = async (
simnet: Simnet,
resetSession: () => Promise<void>,
rendezvousList: string[],
rendezvousAllFunctions: Map<string, ContractInterfaceFunction[]>,
seed: number | undefined,
runs: number | undefined,
dial: string | undefined,
bail: boolean,
regr: boolean,
radio: EventEmitter,
) => {
// The Rendezvous identifier is the first one in the list. Only one contract
// can be fuzzed at a time.
const rendezvousContractId = rendezvousList[0];
// A map where the keys are the Rendezvous identifiers and the values are
// arrays of their SUT (System Under Test) functions. This map will be used
// to access the SUT functions for each Rendezvous contract afterwards.
const rendezvousSutFunctions = filterSutFunctions(rendezvousAllFunctions);
// A map where the keys are the Rendezvous identifiers and the values are
// arrays of their invariant functions. This map will be used to access the
// invariant functions for each Rendezvous contract afterwards.
const rendezvousInvariantFunctions = filterInvariantFunctions(
rendezvousAllFunctions,
);
const sutFunctions = rendezvousSutFunctions.get(rendezvousContractId)!;
const traitReferenceSutFunctions = sutFunctions.filter(
isTraitReferenceFunction,
);
const invariantFunctions =
rendezvousInvariantFunctions.get(rendezvousContractId)!;
const traitReferenceInvariantFunctions = invariantFunctions.filter(
isTraitReferenceFunction,
);
const targetContractName =
getContractNameFromContractId(rendezvousContractId);
const sutTraitReferenceMap = buildTraitReferenceMap(sutFunctions);
const invariantTraitReferenceMap = buildTraitReferenceMap(invariantFunctions);
const enrichedSutFunctionsInterfaces =
traitReferenceSutFunctions.length > 0
? enrichInterfaceWithTraitData(
simnet.getContractAST(targetContractName),
sutTraitReferenceMap,
sutFunctions,
rendezvousContractId,
)
: rendezvousSutFunctions;
const enrichedInvariantFunctionsInterfaces =
traitReferenceInvariantFunctions.length > 0
? enrichInterfaceWithTraitData(
simnet.getContractAST(targetContractName),
invariantTraitReferenceMap,
invariantFunctions,
rendezvousContractId,
)
: rendezvousInvariantFunctions;
// Map all the project/requirement contracts to the traits they implement.
const projectTraitImplementations =
extractProjectTraitImplementations(simnet);
// Extract SUT functions with missing trait implementations. These functions
// will be skipped during invariant testing. Otherwise, the invariant testing
// routine can fail during argument generation.
const sutFunctionsWithMissingTraits = getNonTestableTraitFunctions(
enrichedSutFunctionsInterfaces,
sutTraitReferenceMap,
projectTraitImplementations,
rendezvousContractId,
);
// Extract invariant functions with missing trait implementations. These
// functions will be skipped during invariant testing. Otherwise, the
// invariant testing routine can fail during argument generation.
const invariantFunctionsWithMissingTraits = getNonTestableTraitFunctions(
enrichedInvariantFunctionsInterfaces,
invariantTraitReferenceMap,
projectTraitImplementations,
rendezvousContractId,
);
// Emit warnings for functions with missing trait implementations
emitMissingTraitWarnings(
radio,
sutFunctionsWithMissingTraits,
invariantFunctionsWithMissingTraits,
);
// Filter out functions with missing trait implementations from the enriched
// map.
const executableSutFunctions = new Map([
[
rendezvousContractId,
enrichedSutFunctionsInterfaces
.get(rendezvousContractId)!
.filter((f) => !sutFunctionsWithMissingTraits.includes(f.name)),
],
]);
// Filter out functions with missing trait implementations from the enriched
// map.
const executableInvariantFunctions = new Map([
[
rendezvousContractId,
enrichedInvariantFunctionsInterfaces
.get(rendezvousContractId)!
.filter((f) => !invariantFunctionsWithMissingTraits.includes(f.name)),
],
]);
const functions = getFunctionsListForContract(
executableSutFunctions,
rendezvousContractId,
);
const invariants = getFunctionsListForContract(
executableInvariantFunctions,
rendezvousContractId,
);
if (functions?.length === 0) {
radio.emit(
"logMessage",
red(
`No public functions found for the "${targetContractName}" contract. Without public functions, no state transitions can happen inside the contract, and the invariant test is not meaningful.\n`,
),
);
return;
}
if (invariants?.length === 0) {
radio.emit(
"logMessage",
red(
`No invariant functions found for the "${targetContractName}" contract. Beware, for your contract may be exposed to unforeseen issues.\n`,
),
);
return;
}
if (regr) {
// Run regression tests only.
radio.emit(
"logMessage",
`Regressions loaded from: ${resolve(
getFailureFilePath(rendezvousContractId),
)}`,
);
radio.emit(
"logMessage",
`Loading ${targetContractName} contract regressions...\n`,
);
const regressions = loadFailures(rendezvousContractId, "invariant");
radio.emit(
"logMessage",
`Found ${underline(
`${regressions.length} regressions`,
)} for the ${targetContractName} contract.\n`,
);
for (const regression of regressions) {
emitInvariantRegressionTestHeader(
radio,
targetContractName,
regression.seed,
regression.numRuns,
regression.dial,
regression.timestamp,
);
await resetSession();
await invariantTest({
simnet,
targetContractName,
rendezvousContractId,
runs: regression.numRuns < 100 ? 100 : regression.numRuns,
seed: regression.seed,
bail,
dial: regression.dial,
radio,
functions,
invariants,
projectTraitImplementations,
});
}
} else {
// Run fresh invariant tests using user-provided configuration.
radio.emit(
"logMessage",
`Starting fresh round of invariant testing for the ${targetContractName} contract using user-provided configuration...\n`,
);
await invariantTest({
simnet,
targetContractName,
rendezvousContractId,
runs,
seed,
bail,
dial,
radio,
functions,
invariants,
projectTraitImplementations,
});
}
};
/**
* The configuration for an invariant test.
*/
interface InvariantTestConfig {
simnet: Simnet;
targetContractName: string;
rendezvousContractId: string;
runs: number | undefined;
seed: number | undefined;
bail: boolean;
dial: string | undefined;
radio: EventEmitter;
}
/**
* The context to run an invariant test with.
*/
interface InvariantTestContext {
/** SUT functions for the target contract. */
functions: EnrichedContractInterfaceFunction[];
/** Invariant functions for the target contract. */
invariants: EnrichedContractInterfaceFunction[];
/** Project trait implementations. */
projectTraitImplementations: Record<string, ImplementedTraitType[]>;
}
/**
* Runs an invariant test.
* @param config The union of the configuration and context for the invariant
* test.
* @returns A promise that resolves when the invariant test is complete.
*/
const invariantTest = async (
config: InvariantTestConfig & InvariantTestContext,
) => {
const {
simnet,
targetContractName,
rendezvousContractId,
runs,
seed,
bail,
dial,
radio,
functions,
invariants,
projectTraitImplementations,
} = config;
// Derive accounts and addresses from simnet.
const simnetAccounts = simnet.getAccounts();
const eligibleAccounts = new Map(
[...simnetAccounts].filter(([key]) => key !== "faucet"),
);
const simnetAddresses = [...simnetAccounts.values()];
/**
* The dialer registry, which is used to keep track of all the custom dialers
* registered by the user using the `--dial` flag.
*/
const dialerRegistry =
dial !== undefined ? new DialerRegistry(dial) : undefined;
if (dialerRegistry !== undefined) {
dialerRegistry.registerDialers();
}
const statistics: Statistics = {
sut: {
successful: new Map<string, number>(),
failed: new Map<string, number>(),
},
invariant: {
successful: new Map<string, number>(),
failed: new Map<string, number>(),
},
};
// Initialize the statistics for the SUT functions.
for (const functionInterface of functions) {
statistics.sut!.successful.set(functionInterface.name, 0);
statistics.sut!.failed.set(functionInterface.name, 0);
}
// Initialize the statistics for the invariant functions.
for (const functionInterface of invariants) {
statistics.invariant!.successful.set(functionInterface.name, 0);
statistics.invariant!.failed.set(functionInterface.name, 0);
}
const radioReporter = async (runDetails: any) => {
reporter(runDetails, radio, "invariant", statistics);
// Persist failures for regression testing.
if (runDetails.failed) {
persistFailure(runDetails, "invariant", rendezvousContractId, dial);
}
};
// Set up local context to track SUT function call counts.
const localContext = initializeLocalContext(rendezvousContractId, functions);
// Set up context in simnet by initializing state for SUT.
initializeClarityContext(simnet, rendezvousContractId, functions);
await fc.assert(
fc.asyncProperty(
fc
.record({
// The target contract identifier. It is a constant value equal
// to the first contract in the list. The arbitrary is still needed,
// being used for reporting purposes in `heatstroke.ts`.
rendezvousContractId: fc.constant(rendezvousContractId),
invariantCaller: fc.constantFrom(...eligibleAccounts.entries()),
canMineBlocks: fc.boolean(),
})
.chain((r) =>
fc
.record({
selectedFunctions: fc.array(fc.constantFrom(...functions), {
minLength: 1, // At least one function must be selected.
}),
selectedInvariant: fc.constantFrom(...invariants),
})
.map((selectedFunctions) => ({ ...r, ...selectedFunctions })),
)
.chain((r) =>
fc
.record({
sutCallers: fc.array(
fc.constantFrom(...eligibleAccounts.entries()),
{
minLength: r.selectedFunctions.length,
maxLength: r.selectedFunctions.length,
},
),
selectedFunctionsArgsList: fc.tuple(
...r.selectedFunctions.map((selectedFunction) =>
fc.tuple(
...functionToArbitrary(
selectedFunction,
simnetAddresses,
projectTraitImplementations,
),
),
),
),
invariantArgs: fc.tuple(
...functionToArbitrary(
r.selectedInvariant,
simnetAddresses,
projectTraitImplementations,
),
),
})
.map((args) => ({ ...r, ...args })),
)
.chain((r) =>
fc
.record({
burnBlocks: r.canMineBlocks
? // This arbitrary produces integers with a maximum value
// inversely proportional to the number of runs:
// - Fewer runs result in a higher maximum burn blocks,
// allowing more blocks to be mined.
// - More runs result in a lower maximum burn blocks, as more
// blocks are mined overall.
fc.integer({
min: 1,
max: Math.ceil(100_000 / (runs || 100)),
})
: fc.constant(0),
})
.map((burnBlocks) => ({ ...r, ...burnBlocks })),
),
async (r) => {
const selectedFunctionsArgsCV = r.selectedFunctions.map(
(selectedFunction, index) =>
argsToCV(selectedFunction, r.selectedFunctionsArgsList[index]),
);
const selectedInvariantArgsCV = argsToCV(
r.selectedInvariant,
r.invariantArgs,
);
for (const [index, selectedFunction] of r.selectedFunctions.entries()) {
const [sutCallerWallet, sutCallerAddress] = r.sutCallers[index];
const printedFunctionArgs = r.selectedFunctionsArgsList[index]
.map((arg) => {
try {
return typeof arg === "object"
? JSON.stringify(arg)
: (arg as any).toString();
} catch {
return "[Circular]";
}
})
.join(" ");
try {
if (dialerRegistry !== undefined) {
await dialerRegistry.executePreDialers({
selectedFunction: selectedFunction,
functionCall: undefined,
clarityValueArguments: selectedFunctionsArgsCV[index],
});
}
} catch (error: any) {
throw new PreDialerError(error.message);
}
try {
const functionCall = simnet.callPublicFn(
r.rendezvousContractId,
selectedFunction.name,
selectedFunctionsArgsCV[index],
sutCallerAddress,
);
const functionCallResultJson = cvToJSON(functionCall.result);
// Reaching this point means the function call went through, but it
// may still have returned an error result. Get the result, convert
// it to Clarity string format, and report it to improve the user
// experiance by providing important information about the function
// call during the run.
const selectedFunctionClarityResult = cvToString(
functionCall.result,
);
if (functionCallResultJson.success) {
statistics.sut!.successful.set(
selectedFunction.name,
statistics.sut!.successful.get(selectedFunction.name)! + 1,
);
localContext[r.rendezvousContractId][selectedFunction.name]++;
simnet.callPublicFn(
r.rendezvousContractId,
"update-context",
[
Cl.stringAscii(selectedFunction.name),
Cl.uint(
localContext[r.rendezvousContractId][selectedFunction.name],
),
],
simnet.deployer,
);
// Function call passed.
radio.emit(
"logMessage",
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
dim(`${sutCallerWallet} `) +
`${targetContractName} ` +
`${underline(selectedFunction.name)} ` +
`${printedFunctionArgs} ` +
green(selectedFunctionClarityResult),
);
try {
if (dialerRegistry !== undefined) {
await dialerRegistry.executePostDialers({
selectedFunction: selectedFunction,
functionCall: functionCall,
clarityValueArguments: selectedFunctionsArgsCV[index],
});
}
} catch (error: any) {
throw new PostDialerError(error.message);
}
} else {
// Function call failed.
statistics.sut!.failed.set(
selectedFunction.name,
statistics.sut!.failed.get(selectedFunction.name)! + 1,
);
radio.emit(
"logMessage",
dim(
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${sutCallerWallet} ` +
`${targetContractName} ` +
`${underline(selectedFunction.name)} ` +
`${printedFunctionArgs} ` +
red(selectedFunctionClarityResult),
),
);
}
} catch (error: any) {
if (
error instanceof PreDialerError ||
error instanceof PostDialerError
) {
throw error;
} else {
const displayedError =
error &&
typeof error === "string" &&
error.toLowerCase().includes("runtime")
? "(runtime)"
: "(unknown)";
// If the function call fails with a runtime error, log a dimmed
// message. Since the public function result is only logged and
// does not affect the run, there's no need to throw an error.
radio.emit(
"logMessage",
dim(
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${sutCallerWallet} ` +
`${targetContractName} ` +
`${underline(selectedFunction.name)} ` +
`${printedFunctionArgs} ` +
red(displayedError),
),
);
}
}
}
const printedInvariantArgs = r.invariantArgs
.map((arg) => {
try {
return typeof arg === "object"
? JSON.stringify(arg)
: arg.toString();
} catch {
return "[Circular]";
}
})
.join(" ");
const [invariantCallerWallet, invariantCallerAddress] =
r.invariantCaller;
try {
const { result: invariantCallResult } = simnet.callReadOnlyFn(
r.rendezvousContractId,
r.selectedInvariant.name,
selectedInvariantArgsCV,
invariantCallerAddress,
);
const invariantCallResultJson = cvToJSON(invariantCallResult);
const invariantCallClarityResult = cvToString(invariantCallResult);
if (invariantCallResultJson.value === true) {
statistics.invariant!.successful.set(
r.selectedInvariant.name,
statistics.invariant!.successful.get(r.selectedInvariant.name)! +
1,
);
radio.emit(
"logMessage",
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${dim(invariantCallerWallet)} ` +
`${green("[PASS]")} ` +
`${targetContractName} ` +
`${underline(r.selectedInvariant.name)} ` +
`${printedInvariantArgs} ` +
green(invariantCallClarityResult),
);
} else {
statistics.invariant!.failed.set(
r.selectedInvariant.name,
statistics.invariant!.failed.get(r.selectedInvariant.name)! + 1,
);
radio.emit(
"logMessage",
red(
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${invariantCallerWallet} ` +
`[FAIL] ` +
`${targetContractName} ` +
`${underline(r.selectedInvariant.name)} ` +
`${printedInvariantArgs} ` +
red(invariantCallClarityResult),
),
);
// Invariant call went through, but returned something other than
// `true`. Create a custom error to distinguish this case from
// runtime errors.
throw new FalsifiedInvariantError(
`Invariant failed for ${targetContractName} contract: "${r.selectedInvariant.name}" returned ${invariantCallClarityResult}`,
invariantCallClarityResult,
);
}
} catch (error: any) {
// Log errors that aren't already handled as falsified invariants.
// This prevents duplicate error messages for the same failure.
if (!(error instanceof FalsifiedInvariantError)) {
radio.emit(
"logMessage",
red(
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${invariantCallerWallet} ` +
`[FAIL] ` +
`${targetContractName} ` +
`${underline(r.selectedInvariant.name)} ` +
printedInvariantArgs,
),
);
}
// Re-throw the error for fast-check to catch and process.
throw error;
}
if (r.canMineBlocks) {
simnet.mineEmptyBurnBlocks(r.burnBlocks);
}
},
),
{
endOnFailure: bail,
numRuns: runs,
reporter: radioReporter,
seed: seed,
verbose: true,
},
);
};
/**
* Emits warnings for functions that reference traits without eligible
* implementations.
*/
const emitMissingTraitWarnings = (
radio: EventEmitter,
sutFunctions: string[],
invariantFunctions: string[],
): void => {
if (sutFunctions.length === 0 && invariantFunctions.length === 0) {
return;
}
if (sutFunctions.length > 0) {
const functionList = sutFunctions.map((fn) => ` - ${fn}`).join("\n");
radio.emit(
"logMessage",
yellow(
`\nWarning: The following SUT functions reference traits without eligible implementations and will be skipped:\n\n${functionList}\n`,
),
);
}
if (invariantFunctions.length > 0) {
const functionList = invariantFunctions.map((fn) => ` - ${fn}`).join("\n");
radio.emit(
"logMessage",
yellow(
`\nWarning: The following invariant functions reference traits without eligible implementations and will be skipped:\n\n${functionList}\n`,
),
);
}
radio.emit(
"logMessage",
yellow(
`Note: You can add contracts implementing traits either as project contracts or as Clarinet requirements.\n`,
),
);
};
/**
* Initializes the local context, setting the number of times each function
* has been called to zero.
* @param contractId The contract identifier.
* @param functions The SUT functions for the contract.
* @returns The initialized local context.
*/
export const initializeLocalContext = (
contractId: string,
functions: EnrichedContractInterfaceFunction[],
): LocalContext => ({
[contractId]: Object.fromEntries(functions.map((f) => [f.name, 0])),
});
/**
* Initializes the Clarity context by calling update-context for each SUT
* function.
* @param simnet The Simnet instance.
* @param contractId The contract identifier.
* @param functions The SUT functions for the contract.
*/
export const initializeClarityContext = (
simnet: Simnet,
contractId: string,
functions: EnrichedContractInterfaceFunction[],
) => {
functions.forEach((fn) => {
const { result: initialize } = simnet.callPublicFn(
contractId,
"update-context",
[Cl.stringAscii(fn.name), Cl.uint(0)],
simnet.deployer,
);
const jsonResult = cvToJSON(initialize);
if (!jsonResult.value || !jsonResult.success) {
throw new Error(
`Failed to initialize the context for function: ${fn.name}.`,
);
}
});
};
/**
* Filter the System Under Test (`SUT`) functions from the map of all contract
* functions.
*
* The SUT functions are the ones that have `public` access since they are
* capable of changing the contract state, and they are not test functions.
* @param allFunctionsMap The map containing all the functions for each
* Rendezvous contract.
* @returns A map containing the filtered SUT functions for each Rendezvous
* contract.
*/
const filterSutFunctions = (
allFunctionsMap: Map<string, ContractInterfaceFunction[]>,
) =>
new Map(
Array.from(allFunctionsMap, ([contractId, functions]) => [
contractId,
functions.filter(
(f) =>
f.access === "public" &&
f.name !== "update-context" &&
!f.name.startsWith("test-"),
),
]),
);
const filterInvariantFunctions = (
allFunctionsMap: Map<string, ContractInterfaceFunction[]>,
) =>
new Map(
Array.from(allFunctionsMap, ([contractId, functions]) => [
contractId,
functions.filter(
({ access, name }) =>
access === "read_only" && name.startsWith("invariant-"),
),
]),
);
export class FalsifiedInvariantError extends Error {
readonly clarityError: string;
constructor(message: string, clarityError: string) {
super(message);
this.clarityError = clarityError;
}
}
const emitInvariantRegressionTestHeader = (
radio: EventEmitter,
targetContractName: string,
seed: number,
numRuns: number,
dial: string | undefined,
timestamp: number,
) => {
radio.emit("logMessage", LOG_DIVIDER);
radio.emit(
"logMessage",
`
Running ${underline(
timestamp,
)} regression test for the ${targetContractName} contract with:
- Seed: ${seed}
- Runs: ${numRuns}
- Dial: ${dial ?? "none (default)"}
`,
);
};