This repository was archived by the owner on Apr 19, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtests.js
More file actions
1973 lines (1886 loc) · 65.6 KB
/
Copy pathtests.js
File metadata and controls
1973 lines (1886 loc) · 65.6 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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-nocheck
/**
* TMCTOL Comprehensive Test Suite
* Synchronized verbose in `/simulator/tests.md`
* Minimal output: statistics only
* @module tests
*/
import {
BigMath,
create_system,
PPB,
PRECISION,
Router,
User,
} from "./model.js";
/** @typedef {import("./model.js").SystemConfig} SystemConfig */
/**
* @param {bigint} price
* @returns {string}
*/
const formatPrice = (price) => (Number(price) / Number(PRECISION)).toFixed(9);
/**
* @param {bigint} supply
* @returns {string}
*/
const formatSupply = (supply) =>
(Number(supply) / Number(PRECISION)).toFixed(2);
/**
* @param {bigint} tokens
* @returns {string}
*/
const formatTokens = (tokens) =>
(Number(tokens) / Number(PRECISION)).toFixed(6);
/**
* @param {bigint} ppb
* @returns {string}
*/
const formatPPB = (ppb) => `${(Number(ppb) / 10000000).toFixed(2)}%`;
class TestFailure extends Error {
constructor(/** @type {string} */ message) {
super(message);
this.name = "TestFailure";
}
}
/**
* @param {boolean} condition
* @param {string} message
* @throws {TestFailure}
*/
const assert = (condition, message) => {
if (!condition) {
console.log(`ASSERT FAILED: ${message}, condition=${condition}`);
throw new TestFailure(message);
}
};
/**
* @param {bigint} actual
* @param {bigint} expected
* @param {bigint} tolerance
* @param {string} message
* @throws {TestFailure}
*/
const assertApprox = (actual, expected, tolerance, message) => {
const diff = actual > expected ? actual - expected : expected - actual;
const maxDiff = (expected * BigInt(tolerance)) / 1_000n;
if (diff > maxDiff) {
throw new TestFailure(
`${message} (Expected: ${expected}, Actual: ${actual}, Diff: ${diff})`,
);
}
};
const getTimestamp = (() => {
if (typeof performance !== "undefined" && performance.now) {
return () => BigInt(Math.floor(performance.now() * 1_000_000));
} else if (typeof Date !== "undefined") {
return () => BigInt(Date.now()) * 1_000_000n;
} else {
let counter = 0n;
return () => counter++;
}
})();
// Test section structure: [section, count_in_section]
const TEST_SECTIONS = [
[1, 4], // Mathematical Foundations
[2, 6], // System Parameters & Scaling
[3, 6], // Scaling Rules & Precision
[4, 8], // Core Component Tests
[5, 5], // Integration & System Flows
[6, 3], // System Invariants & Multi-Actor
[7, 6], // Advanced Integration Scenarios
[8, 3], // System Properties & Invariants
[9, 2], // Multi-User & Chaos Testing
[10, 5], // Emergent Properties & System Intelligence
[11, 4], // Economic Security & Attack Resistance
[12, 4], // Adaptive System Behaviors
];
let testCount = 0;
let passedTests = 0;
/** @type {Array<{test: number, code: string, name: string, error: string}>} */
let failedTests = [];
/**
* Get hierarchical test code (e.g., "1.1", "2.3", etc.)
* @param {number} testNum
* @returns {string}
*/
const getTestCode = (testNum) => {
let accumulated = 0;
for (const [section, count] of TEST_SECTIONS) {
if (testNum <= accumulated + count) {
const posInSection = testNum - accumulated;
return `${section}.${posInSection}`;
}
accumulated += count;
}
return `${testNum}`;
};
/**
* @param {string} name
* @param {() => void} fn
*/
const runTest = (name, fn) => {
testCount++;
const testCode = getTestCode(testCount);
const displayName = name.length > 50 ? name.substring(0, 47) + "..." : name;
const prefix = `[${testCount.toString().padStart(2)}] ${displayName.padEnd(50)} `;
try {
fn();
passedTests++;
console.log(prefix + "✅");
} catch (error) {
console.log(prefix + "❌");
const errorMsg =
error instanceof TestFailure
? error.message
: `${String(error)}\n${error instanceof Error ? error.stack : ""}`;
failedTests.push({
test: testCount,
code: testCode,
name,
error: errorMsg,
});
}
};
console.log("<TMCTOL Test Suite>");
// 1. FORMULA TESTS
runTest("Absolute Slope Formula Verification", () => {
const system = create_system({
tmc: {
price_initial: PRECISION,
slope: PRECISION,
mint_shares: {
user_ppb: 333_333_333n,
tol_ppb: 666_666_667n,
},
},
});
const minter = system.tmc;
assert(
minter.get_price() === minter.price_initial,
"Price equals initial at zero supply",
);
const test_supplies = [
{
supply: 1_000n * PRECISION,
expected_price: PRECISION + 1_000n * PRECISION,
},
{
supply: 10_000n * PRECISION,
expected_price: PRECISION + 10_000n * PRECISION,
},
{
supply: 100_000n * PRECISION,
expected_price: PRECISION + 100_000n * PRECISION,
},
];
for (const test of test_supplies) {
minter.supply = test.supply;
const actual_price = minter.get_price();
assert(
actual_price === test.expected_price,
`Price at supply ${formatSupply(test.supply)}`,
);
}
minter.supply = 0n;
});
runTest("Quadratic Integration for Minting", () => {
const system = create_system({
tmc: {
price_initial: PRECISION / 1_000n,
slope: PRECISION / 1_000n,
mint_shares: {
user_ppb: 333_333_333n,
tol_ppb: 666_666_667n,
},
},
});
const minter = system.tmc;
const foreign = 100n * PRECISION;
const calculated_mint = minter.calculate_mint(foreign);
const result = minter.mint_native(foreign);
assert(
result.total_minted === calculated_mint,
"Calculated mint matches actual",
);
});
runTest("Linear Price Doubling Property Verification", () => {
// Test that for parameters: price_initial = PRECISION / N, slope = PRECISION / N
// The system exhibits perfect linearity: doubling supply ≈ doubling price
const test_cases = [
{ N: 1000n, name: "N=1000" },
{ N: 333n, name: "N=333" },
{ N: 333_333n, name: "N=333333" },
{ N: 10_000n, name: "N=10000" },
];
for (const test of test_cases) {
const system = create_system({
tmc: {
price_initial: PRECISION / 1_000n,
slope: PRECISION / 1_000n,
mint_shares: {
user_ppb: 333_333_333n,
tol_ppb: 666_666_667n,
},
},
});
const tmc = system.tmc;
// Test at multiple supply points to verify linearity
const supply_points = [
10_000_000n * PRECISION, // Large supply where linear approximation holds
20_000_000n * PRECISION,
40_000_000n * PRECISION,
];
let previous_supply = 0n;
let previous_price = 0n;
for (const supply of supply_points) {
tmc.supply = supply;
const current_price = tmc.get_price();
if (previous_price > 0n) {
// For linear function P(S) = price_initial + (slope × S) / PRECISION
// With our parameters: P(S) = PRECISION/N + (PRECISION/N × S) / PRECISION
// = PRECISION/N + S/N = (PRECISION + S) / N
// When S >> PRECISION, P(S) ≈ S/N
// Therefore P(2S) / P(S) ≈ (2S/N) / (S/N) = 2
const supply_ratio = Number(supply) / Number(previous_supply);
const price_ratio = Number(current_price) / Number(previous_price);
// For linear function, price ratio should equal supply ratio
const ratio_difference = Math.abs(price_ratio - supply_ratio);
const tolerance = 0.001; // 0.1% tolerance
assert(
ratio_difference < tolerance,
`Linear price scaling for ${test.name}: supply_ratio=${supply_ratio.toFixed(4)}, price_ratio=${price_ratio.toFixed(4)}, difference=${ratio_difference.toFixed(6)}`,
);
}
previous_supply = supply;
previous_price = current_price;
}
// Additional verification: test the linear scaling property
// For linear function P(S) = price_initial + (slope × S) / PRECISION
// With our parameters: P(S) = PRECISION/N + (PRECISION/N × S) / PRECISION
// = PRECISION/N + S/N = (PRECISION + S) / N
// Test that doubling supply approximately doubles price
const base_supply = 10_000_000n * PRECISION;
const doubled_supply = 20_000_000n * PRECISION;
tmc.supply = base_supply;
const base_price = tmc.get_price();
tmc.supply = doubled_supply;
const doubled_price = tmc.get_price();
// Calculate the actual doubling ratio
const actual_ratio = Number(doubled_price) / Number(base_price);
const expected_ratio = 2.0; // Perfect linear doubling
const ratio_difference = Math.abs(actual_ratio - expected_ratio);
const tolerance = 0.01; // 1% tolerance for linear approximation
assert(
ratio_difference < tolerance,
`Linear doubling property for ${test.name}: actual_ratio=${actual_ratio.toFixed(4)}, expected=2.0, difference=${ratio_difference.toFixed(6)}`,
);
tmc.supply = 0n; // Reset
}
});
runTest("Zero Slope (Constant Price)", () => {
const system = create_system({
tmc: {
price_initial: PRECISION,
slope: 0n,
mint_shares: {
user_ppb: 1_000_000_000n,
tol_ppb: 0n,
},
},
});
const minter = system.tmc;
const test_amounts = [
100n * PRECISION,
1_000n * PRECISION,
10_000n * PRECISION,
];
for (const amount of test_amounts) {
const result = minter.mint_native(amount);
assert(
result.price_before === result.price_after,
"Price constant with zero slope",
);
minter.supply = 0n;
}
});
// 2. PARAMETER BOUNDARY TESTS
runTest("Initial Price Boundary Testing", () => {
const test_cases = [
{ value: 1n, name: "Minimum (1 wei)" },
{ value: PRECISION / 1_000_000n, name: "Very small (0.000001)" },
{ value: PRECISION / 1_000n, name: "Small (0.001)" },
{ value: PRECISION, name: "Standard (1.0)" },
{ value: 1_000n * PRECISION, name: "Large (1000)" },
{ value: 1_000_000n * PRECISION, name: "Very large (1,000,000)" },
{ value: 100_000_000n * PRECISION, name: "Pushed large (100M)" },
];
for (const test of test_cases) {
const system = create_system({
tmc: {
price_initial: test.value,
slope: PRECISION / 1_000n,
},
});
const price = system.tmc.get_price();
assert(price === test.value, `Initial price ${test.name}`);
}
});
runTest("Slope Boundary Testing", () => {
const test_cases = [
{ value: 0n, name: "Zero (constant price)" },
{ value: PRECISION / 1_000_000n, name: "Minimal (0.000001)" },
{ value: PRECISION / 1_000n, name: "Standard (0.001)" },
{ value: PRECISION / 10n, name: "High (0.1)" },
{ value: PRECISION, name: "Extreme (1.0)" },
{ value: PRECISION * 1_000n, name: "Very large (1000)" },
{ value: PRECISION * 10_000n, name: "Extreme (10000)" },
{ value: PRECISION * 100_000n, name: "Pushed extreme (100k)" },
];
for (const test of test_cases) {
const system = create_system({
tmc: {
price_initial: PRECISION,
slope: test.value,
},
});
const minter = system.tmc;
minter.supply = 1_000_000n * PRECISION;
const expected_price =
PRECISION + (test.value * 1_000_000n * PRECISION) / PRECISION;
assert(minter.get_price() === expected_price, `Slope ${test.name}`);
minter.supply = 0n;
}
});
runTest("Supply Boundary Testing", () => {
const system = create_system({
tmc: {
price_initial: PRECISION / 1_000n,
slope: PRECISION / 10_000n,
mint_shares: {
user_ppb: 1_000_000_000n,
tol_ppb: 0n,
},
},
});
const minter = system.tmc;
const test_supplies = [
{ supply: 0n, name: "Zero" },
{ supply: 1_000n * PRECISION, name: "1K" },
{ supply: 1_000_000n * PRECISION, name: "1M" },
{ supply: 1_000_000_000n * PRECISION, name: "1B" },
];
for (const test of test_supplies) {
minter.supply = test.supply;
const price = minter.get_price();
const expected =
minter.price_initial + (minter.slope * test.supply) / PRECISION;
assert(price === expected, `Supply ${test.name}`);
}
minter.supply = 0n;
});
runTest("Large Number Stress Test", () => {
const system = create_system({
tmc: {
price_initial: PRECISION / 1_000_000n,
slope: PRECISION / 1_000_000n,
mint_shares: {
user_ppb: 1_000_000_000n,
tol_ppb: 0n,
},
},
});
const minter = system.tmc;
const large_payment = 1_000_000_000_000_000_000n * PRECISION;
const result = minter.mint_native(large_payment);
assert(result.total_minted > 0n, "Large payment processed");
});
runTest("Parameter Combination Testing", () => {
const combinations = [
{
name: "Low price, high slope",
price_initial: PRECISION / 1_000_000n,
slope: PRECISION * 10n,
},
{
name: "High price, zero slope",
price_initial: 10_000_000n * PRECISION,
slope: 0n,
},
{
name: "Medium price, medium slope",
price_initial: PRECISION,
slope: PRECISION / 100n,
},
{
name: "Very small price, very small slope",
price_initial: 1n,
slope: PRECISION / 1_000_000n,
},
];
for (const combo of combinations) {
const system = create_system({
tmc: {
price_initial: combo.price_initial,
slope: combo.slope,
mint_shares: {
user_ppb: 1_000_000_000n,
tol_ppb: 0n,
},
},
});
const result = system.tmc.mint_native(100n * PRECISION);
assert(result.total_minted > 0n, `Combo: ${combo.name}`);
}
});
runTest("Current Default Parameters Validation", () => {
const system = create_system({});
const minter = system.tmc;
const total_shares = minter.user_ppb + minter.tol_ppb;
assert(total_shares === PPB, "Default shares sum to 100%");
const result = minter.mint_native(1_000n * PRECISION);
assert(result.total_minted > 0n, "Default config produces valid mint");
});
// 3. SCALING RULES
runTest("Scaling Rules - Naming Convention", () => {
const system = create_system({});
const minter = system.tmc;
assert(minter.hasOwnProperty("user_ppb"), "user share has _ppb suffix");
assert(minter.hasOwnProperty("tol_ppb"), "tol share has _ppb suffix");
});
runTest("Scaling Rules - Input Pre-scaling", () => {
const system = create_system({
tmc: {
price_initial: PRECISION,
slope: PRECISION,
mint_shares: {
user_ppb: 1_000_000_000n,
tol_ppb: 0n,
},
},
});
const minter = system.tmc;
const payment = 10n * PRECISION;
const result = minter.mint_native(payment);
assert(result.total_minted > 0n, "Pre-scaled inputs work correctly");
});
runTest("Scaling Rules - Price Scaling Consistency", () => {
const system = create_system({
tmc: {
price_initial: PRECISION * 2n,
slope: 0n,
mint_shares: {
user_ppb: 1_000_000_000n,
tol_ppb: 0n,
},
},
});
const minter = system.tmc;
const pool = system.xyk;
const mint_result = minter.mint_native(1_000n * PRECISION);
assert(
mint_result.price_before === PRECISION * 2n,
"Minter price consistency",
);
});
runTest("Scaling Rules - PPB Values Range", () => {
const system = create_system({});
const user_ppb = system.tmc.user_ppb;
const tol_ppb = system.tmc.tol_ppb;
const total_shares = user_ppb + tol_ppb;
assert(total_shares === PPB, "Shares sum to 1,000,000,000 PPB");
assert(user_ppb <= PPB, "User share <= 100%");
assert(tol_ppb <= PPB, "TOL share <= 100%");
});
runTest("Scaling Rules - Precision Through Calculations", () => {
const system = create_system({
tmc: {
price_initial: PRECISION,
slope: PRECISION,
mint_shares: {
user_ppb: 333_333_333n,
tol_ppb: 666_666_667n,
},
},
});
const minter = system.tmc;
const payment = 1_000n * PRECISION;
const result = minter.mint_native(payment);
const total_distributed = result.user_native + result.tol_native;
const diff =
total_distributed > result.total_minted
? total_distributed - result.total_minted
: result.total_minted - total_distributed;
assert(diff <= 4n, "Precision loss <= 4 wei");
});
// 3. SCALING RULES & PRECISION
runTest("Scaling Rules - Property Fuzz", () => {
// Fuzz inputs within sane operational ranges
const cases = 100;
for (let i = 0; i < cases; i++) {
const price_initial =
BigInt(Math.floor(Math.random() * 1_000_000) + 1) *
(PRECISION / 1_000_000n);
const slope =
BigInt(Math.floor(Math.random() * 1_000_000) + 1) *
(PRECISION / 1_000_000n);
const system = create_system({ tmc: { price_initial, slope } });
const tmc = system.tmc;
// Random supply point
const s = BigInt(Math.floor(Math.random() * 1_000_000)) * PRECISION;
tmc.supply = s;
// Expected price: P = P0 + m * S / PRECISION
const expected = price_initial + (slope * s) / PRECISION;
const actual = tmc.get_price();
assert(actual >= 0n, "Price must be non-negative");
assert(
expected === actual,
"Price formula must hold exactly under scaling",
);
}
});
// 4. COMPONENT TESTS
runTest("System Initialization", () => {
const system = create_system({
tmc: {
price_initial: PRECISION / 1_000n,
slope: PRECISION / 1_000n,
mint_shares: {
user_ppb: 333_333_333n,
tol_ppb: 666_666_667n,
},
},
});
assert(system.tmc !== undefined, "Minter initialized");
assert(system.tol !== undefined, "TOL manager initialized");
assert(system.xyk !== undefined, "XYK pool initialized");
assert(system.router !== undefined, "Router initialized");
});
runTest("TMC Minting and Distribution", () => {
const system = create_system({
tmc: {
price_initial: PRECISION / 1_000n,
slope: PRECISION / 1_000n,
mint_shares: {
user_ppb: 333_333_333n,
tol_ppb: 666_666_667n,
},
},
});
const minter = system.tmc;
const payment = 1_000n * PRECISION;
const result = minter.mint_native(payment);
const user_expected = (result.total_minted * 333_333_333n) / PPB;
const tol_expected = (result.total_minted * 666_666_667n) / PPB;
assertApprox(result.user_native, user_expected, 1n, "User share correct");
assertApprox(result.tol_native, tol_expected, 1n, "TOL share correct");
});
runTest("TOL Adding Liquidity to XYK", () => {
const system = create_system({});
const minter = system.tmc;
const pool = system.xyk;
const mint_result = minter.mint_native(1_000n * PRECISION);
const tol = /** @type {any} */ (mint_result.tol);
const total_lp =
tol.bucket_a.lp_tokens +
tol.bucket_b.lp_tokens +
tol.bucket_c.lp_tokens +
tol.bucket_d.lp_tokens;
assert(total_lp > 0n, "TOL LP tokens minted");
assert(pool.reserve_native > 0n, "Pool native reserve increased");
assert(pool.reserve_foreign > 0n, "Pool foreign reserve increased");
});
runTest("XYK Pool Swaps", () => {
const system = create_system({});
const pool = system.xyk;
const minter = system.tmc;
minter.mint_native(10_000n * PRECISION);
const swap_amount = 100n * PRECISION;
const k_before = pool.reserve_native * pool.reserve_foreign;
const output = pool.swap_foreign_to_native(swap_amount, 0n);
assert(output.native_out > 0n, "Swap produces output");
assert(output.fee !== undefined, "fee returned");
assert(output.fee >= 0n, "fee non-negative");
const k_after = pool.reserve_native * pool.reserve_foreign;
assert(k_after >= k_before, "K invariant maintained or increased");
});
runTest("XYK Multi-Swap Invariant", () => {
const system = create_system({});
const pool = system.xyk;
const minter = system.tmc;
// Seed meaningful liquidity
minter.mint_native(50_000n * PRECISION);
const amounts = [10n, 25n, 100n, 1000n, 5000n].map((a) => a * PRECISION);
let prev_k = pool.reserve_native * pool.reserve_foreign;
for (const amt of amounts) {
const out = pool.swap_foreign_to_native(amt, 0n);
assert(out.native_out > 0n, "Swap produces output");
assert(out.fee !== undefined, "fee returned");
assert(out.fee >= 0n, "fee non-negative");
// With fee_xyk_ppb = 0, fee should be 0
if (pool.fee_ppb === 0n) {
assert(out.fee === 0n, "Zero fee when fee_ppb is 0");
}
const k_now = pool.reserve_native * pool.reserve_foreign;
assert(k_now >= prev_k, "K invariant maintained or increased");
prev_k = k_now;
}
});
runTest("XYK Fee Tracking - Native to Foreign", () => {
const system = create_system({});
const pool = system.xyk;
const minter = system.tmc;
minter.mint_native(10_000n * PRECISION);
const swap_amount = 100n * PRECISION;
const output = pool.swap_native_to_foreign(swap_amount, 0n);
assert(output.foreign_out > 0n, "Swap produces foreign output");
assert(output.fee !== undefined, "fee returned");
assert(output.fee >= 0n, "fee non-negative");
// With fee_xyk_ppb = 0, fee should be 0
if (pool.fee_ppb === 0n) {
assert(output.fee === 0n, "Zero fee when fee_ppb is 0");
}
});
runTest("Smart Router Path Selection", () => {
const system = create_system({
price_initial: PRECISION,
slope: 100_000n,
});
const router = system.router;
const minter = system.tmc;
minter.mint_native(10_000n * PRECISION);
const swap_amount = 100n * PRECISION;
const result = router.swap_foreign_to_native(swap_amount, 0n);
assert(result.native_out > 0n, "Router produces output");
assert(
result.route === "TMC" || result.route === "XYK",
"Valid route selected",
);
});
runTest("TMC Burn Functionality", () => {
const system = create_system({});
const minter = system.tmc;
const mint_result = minter.mint_native(1_000_000n * PRECISION);
const supply_after_mint = minter.supply;
const burn_amount = supply_after_mint / 2n;
const burn_result = minter.burn_native(burn_amount);
assert(minter.supply === supply_after_mint - burn_amount, "Supply decreased");
assert(burn_result.supply_before > 0n, "Burn executed");
});
// 5. INTEGRATION TESTS
runTest("Edge Cases", () => {
const system = create_system({});
const minter = system.tmc;
const pool = system.xyk;
const zero_result = minter.calculate_mint(0n);
assert(zero_result === 0n, "Zero payment returns zero tokens");
assert(!pool.has_liquidity(), "Pool starts with no liquidity");
try {
pool.swap_foreign_to_native(100n * PRECISION);
assert(false, "Should fail on empty pool");
} catch (e) {
assert(true, "Empty pool swap rejected");
}
});
runTest("Full Integration Flow", () => {
const system = create_system({
price_initial: PRECISION,
slope: PRECISION,
shares: {
user_ppb: 333_333_333n,
tol_ppb: 666_666_667n,
},
});
const minter = system.tmc;
const router = system.router;
const mint_result = minter.mint_native(10_000n * PRECISION);
assert(mint_result.total_minted > 0n, "Mint successful");
const swap_result = router.swap_foreign_to_native(1_000n * PRECISION, 0n);
assert(swap_result.native_out > 0n, "Swap successful");
const burn_result = minter.burn_native(mint_result.total_minted / 10n);
assert(burn_result.supply_before > 0n, "Burn successful");
});
runTest("Overflow Protection Testing", () => {
const max_uint256 = (1n << 256n) - 1n;
const half_max = max_uint256 / 2n;
try {
const system = create_system({
price_initial: half_max,
slope: PRECISION / 1_000n,
});
const result = system.tmc.mint_native(1_000n * PRECISION);
assert(result.total_minted > 0n, "Large price_initial handled");
} catch (e) {
assert(true, "Overflow protected");
}
});
runTest("Safe Operating Ranges", () => {
const configs = [
{
name: "Conservative",
price_initial: PRECISION,
slope: PRECISION / 1_000n,
},
{
name: "Moderate",
price_initial: PRECISION / 100n,
slope: PRECISION / 100n,
},
{
name: "Aggressive",
price_initial: PRECISION / 1_000n,
slope: PRECISION / 10n,
},
];
for (const config of configs) {
const system = create_system({
tmc: {
price_initial: config.price_initial,
slope: config.slope,
},
});
const result = system.tmc.mint_native(1_000n * PRECISION);
assert(result.total_minted > 0n, `${config.name} config safe`);
}
});
runTest("Formula Performance Analysis", () => {
const payment = 100n * PRECISION;
const price_initial = PRECISION;
const slope = PRECISION / 1_000n;
const current_supply = 1_000_000n * PRECISION;
const iterations = 1000;
const start = getTimestamp();
for (let i = 0; i < iterations; i++) {
const system = create_system({
price_initial,
slope,
shares: {
user_ppb: 1_000_000_000n,
tol_ppb: 0n,
},
});
system.tmc.supply = current_supply;
const result = system.tmc.calculate_mint(payment);
}
const end = getTimestamp();
const total_time = end - start;
const avg_time = total_time / BigInt(iterations);
assert(avg_time < 1_000_000n, "Performance acceptable (<1ms per op)");
});
// 6. MULTI-ACTOR CORRECTNESS
runTest("Distribution Accuracy - Multi-Mint Accumulation", () => {
// Test that Treasury and Team receive exact allocation percentages over multiple mints
const system = create_system({
tmc: {
price_initial: PRECISION / 1_000n,
slope: PRECISION / 1_000n,
},
});
const alice = new User(0n, 100_000n * PRECISION);
alice.set_router(system.router);
let total_user_received = 0n;
// Perform 15 mints to accumulate significant distributions
for (let i = 0; i < 15; i++) {
const result = alice.buy_native(1_000n * PRECISION);
if (result.route === "TMC") {
total_user_received += result.native_out;
}
}
const total_supply = system.tmc.supply;
const tol_native = system.xyk.reserve_native;
// Calculate actual distribution ratios
const user_ratio = (total_user_received * PPB) / total_supply;
const tol_ratio = (tol_native * PPB) / total_supply;
// Expected ratios from DEFAULT_CONFIG: user=33.3%, tol=66.7%
const expected_user = 333_333_333n;
const expected_tol = 666_666_667n;
// Validate within 1% tolerance (10,000,000 PPB)
const tolerance = PPB / 100n;
assertApprox(
user_ratio,
expected_user,
tolerance,
"User distribution should be ~33.3%",
);
assertApprox(
tol_ratio,
expected_tol,
tolerance,
"TOL distribution should be ~66.7%",
);
// Verify total distribution sums to 100% (within rounding)
const total_ratio = user_ratio + tol_ratio;
assertApprox(
total_ratio,
PPB,
tolerance,
"Total distribution must sum to 100%",
);
});
runTest("Mass Conservation - System-Wide Token Accounting", () => {
// Test that total supply exactly equals sum of all participant balances
const system = create_system({
tmc: {
price_initial: PRECISION / 1_000n,
slope: PRECISION / 1_000n,
},
});
const alice = new User(0n, 10_000n * PRECISION);
const bob = new User(0n, 5_000n * PRECISION);
alice.set_router(system.router);
bob.set_router(system.router);
// Multiple mint operations to build up system
alice.buy_native(2_000n * PRECISION);
bob.buy_native(1_000n * PRECISION);
alice.buy_native(500n * PRECISION);
bob.buy_native(300n * PRECISION);
// Collect all balances
const total_supply = system.tmc.supply;
const alice_balance = alice.get_balance().native;
const bob_balance = bob.get_balance().native;
const tol_balance = system.tol.get_balance();
const tol_native =
tol_balance.bucket_a.contributed_native +
tol_balance.bucket_b.contributed_native +
tol_balance.bucket_c.contributed_native +
tol_balance.bucket_d.contributed_native;
const xyk_native = system.xyk.reserve_native;
// Mass conservation: current supply equals sum of all token balances
// Burned tokens are already excluded from supply, so no need to add them back
const total_accounted = alice_balance + bob_balance + tol_native + xyk_native;
assertApprox(
total_supply,
total_accounted,
total_accounted / 1000n, // 0.1% tolerance for rounding
`Mass conservation violated: supply=${total_supply}, accounted=${total_accounted}`,
);
// Additional verification: no negative balances
assert(alice_balance >= 0n, "Alice balance cannot be negative");
assert(bob_balance >= 0n, "Bob balance cannot be negative");
assert(tol_native >= 0n, "TOL balance cannot be negative");
assert(xyk_native >= 0n, "XYK reserves cannot be negative");
// Verify supply is positive after operations
assert(total_supply > 0n, "Total supply must be positive after mints");
// Verify all participants have accumulated tokens
assert(alice_balance > 0n, "Alice should have received tokens");
assert(bob_balance > 0n, "Bob should have received tokens");
assert(tol_native > 0n, "TOL should have accumulated tokens");
assert(xyk_native > 0n, "XYK should have TOL reserves");
});
runTest("TOL Independence - Participant Sales Don't Touch TOL", () => {
// Test that Treasury, Team, and User sales only affect XYK reserves, never TOL LP tokens
const system = create_system({
tmc: {
price_initial: PRECISION / 1_000n,
slope: PRECISION / 1_000n,
},
});
const alice = new User(0n, 20_000n * PRECISION);
alice.set_router(system.router);
// Build up system with multiple mints
for (let i = 0; i < 10; i++) {
alice.buy_native(1_000n * PRECISION);
}
// Snapshot TOL state before any sales
const tol_balance_before = system.tol.get_balance();
const tol_lp_before =
tol_balance_before.bucket_a.balance_lp +
tol_balance_before.bucket_b.balance_lp +
tol_balance_before.bucket_c.balance_lp +
tol_balance_before.bucket_d.balance_lp;
const tol_contributed_native_before =
tol_balance_before.bucket_a.contributed_native +
tol_balance_before.bucket_b.contributed_native +
tol_balance_before.bucket_c.contributed_native +
tol_balance_before.bucket_d.contributed_native;
const tol_contributed_foreign_before =
tol_balance_before.bucket_a.contributed_foreign +
tol_balance_before.bucket_b.contributed_foreign +
tol_balance_before.bucket_c.contributed_foreign +
tol_balance_before.bucket_d.contributed_foreign;
assert(tol_lp_before > 0n, "TOL should have accumulated LP tokens");
// Execute sales from alice
const alice_balance = alice.get_balance().native;
alice.sell_native(alice_balance / 4n);
// Snapshot TOL state after sales
const tol_balance_after = system.tol.get_balance();
const tol_lp_after =
tol_balance_after.bucket_a.balance_lp +
tol_balance_after.bucket_b.balance_lp +
tol_balance_after.bucket_c.balance_lp +
tol_balance_after.bucket_d.balance_lp;
const tol_contributed_native_after =
tol_balance_after.bucket_a.contributed_native +
tol_balance_after.bucket_b.contributed_native +
tol_balance_after.bucket_c.contributed_native +
tol_balance_after.bucket_d.contributed_native;
const tol_contributed_foreign_after =
tol_balance_after.bucket_a.contributed_foreign +
tol_balance_after.bucket_b.contributed_foreign +
tol_balance_after.bucket_c.contributed_foreign +
tol_balance_after.bucket_d.contributed_foreign;
// Critical validation: TOL must be completely unaffected by participant sales
assert(
tol_lp_after === tol_lp_before,
`TOL LP tokens changed: before=${tol_lp_before}, after=${tol_lp_after}`,
);
assert(
tol_contributed_native_after === tol_contributed_native_before,
"TOL native contribution changed from participant sales",
);
assert(
tol_contributed_foreign_after === tol_contributed_foreign_before,
"TOL foreign contribution changed from participant sales",
);
// Verify TOL is strictly non-decreasing (can only increase on new mints)
assert(tol_lp_after >= tol_lp_before, "TOL must never decrease");
// Additional verification: XYK reserves should have changed (due to sales)
assert(system.xyk.reserve_native > 0n, "XYK must maintain native reserves");
assert(system.xyk.reserve_foreign > 0n, "XYK must maintain foreign reserves");
});
// 7. ADVANCED SCENARIOS
runTest("Circular Swaps and Arbitrage Detection", () => {
const system = create_system({
tmc: {
price_initial: PRECISION / 1_000n,