o2-tools 0.4.3-rc

Reusable tooling for trade account and order book contract interactions on Fuel
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
//! The prepaid ("Turbo") overlay: forfeited entries, the free
//! performance-gated rollover, the cosigned deadline that grants or ends it,
//! the atomic v2 publication and the sales switch.
//!
//! Every behaviour here is keyed on the `TurboTerms` sidecar a tier version
//! may carry. The legacy suites prove the other half of the contract: a tier
//! WITHOUT terms — every session the fixture opens — behaves exactly as it
//! always did, and these tests re-prove it in-place where the two cohorts
//! meet (top-ups, the sales switch).

use super::*;
use crate::{
    prop::{
        RolloverWithdrawalRecorded,
        SessionRolledOver,
        SessionSeized,
        TicketSettled,
        TierEnabledChanged,
        TierVersionPublishedV2,
        TurboTerms,
    },
    prop_expiry::generate_pool_expiry_signing_payload,
};

/// A tier id the fixture never uses, so the fixture's own session stays on
/// its legacy terms while these tests sell the prepaid ones beside it.
const TURBO_TIER_ID: u64 = 7;
/// `line / leverage` — the deposit half of the price, forfeited at close.
const TURBO_DEPOSIT: u64 = 250_000;
/// The fee half of the price, paid to the platform inside the opening call.
const TURBO_FEE: u64 = 25_000;
/// What the user actually sends: the whole price, deposit and fee together.
/// A PURCHASE, not a posting: the fee leaves for the platform at the door,
/// the deposit stays with the pool as the session's first-loss bucket, and
/// the session itself opens on zero collateral and zero accrued fees.
const TURBO_ENTRY: u64 = TURBO_DEPOSIT + TURBO_FEE;
/// 9% of the line: the profit a rollover demands above the anchor.
const ROLLOVER_BAR: u64 = 900_000;
/// The account size the tier sells — `deposit * leverage`. A prepaid ticket
/// buys this whatever it cost, so a discount must leave it untouched.
const TURBO_LINE: u64 = TURBO_DEPOSIT * 40;

/// The launch shape: `leverage 40` prices the deposit at `line/40`,
/// `maintenance_bps 100` leaves the pool a 1%-of-line cushion under the
/// user's 1.5% drawdown, and the tier sells SEVEN DAYS by name — the pool
/// refuses any other period at open, `validate_turbo_tier` pins the
/// prolong fees to zero so nothing is purchasable or armable, and the
/// free rollover is the only extension that exists.
fn turbo_tier_params() -> TierParams {
    turbo_tier_params_for(LINE)
}

/// The same shape at any account size: deposit `line/40`, the price being
/// deposit + fee, the drawdown 1.5% of the line over a 1%-of-line pool
/// cushion — the three shipped price points are this one function at
/// 10_000_000 / 5_000_000 / 2_500_000.
fn turbo_tier_params_for(line: u64) -> TierParams {
    TierParams {
        line,
        leverage: 40,
        duration: 0,
        maintenance_bps: 100,
        open_buffer_bps: 101,
        liq_price_factor: 9_900,
        prolong_fee: [0, 0, 0, 0],
        max_credit_line_bps: 20_000,
        max_price_age: u64::MAX,
        open_fee: line / 400,
        profit_share_bps: 0,
        price_band_bps: 1_000,
    }
}

fn turbo_terms(max_loss_bps: [u64; 4]) -> TurboTerms {
    TurboTerms {
        max_loss_bps,
        // The finalised product: 9% of the line earns a free week, three
        // times, each widening the drawdown.
        rollover_profit_bps: 900,
        max_rollovers: 3,
    }
}

/// The shipped escalator: 1.5% / 2% / 2.5% / 3% of the line.
const DRAWDOWN_SCHEDULE: [u64; 4] = [150, 200, 250, 300];

/// The tier, armed for settlement: published, then given a cosigner whose
/// signature `expire_or_rollover` will accept. Every test that reaches a
/// prepaid deadline needs both.
async fn publish_turbo_tier(fixture: &PropFixture, terms: TurboTerms) -> u32 {
    let version = publish_turbo_tier_unarmed(fixture, terms).await;
    // `expire_or_rollover` turns on `outside` - a figure only the keeper can
    // supply - so the pool takes it under COSIGNATURE rather than from a
    // privileged caller. The pool keeps its OWN cosigner, independent of the
    // oracle's; the fixture's deployer plays it.
    fixture
        .deployment
        .pool
        .methods()
        .set_expiry_cosigner(fixture.deployer.address())
        .call()
        .await
        .unwrap();
    version
}

/// The publication alone, leaving the pool with NO expiry cosigner - the
/// state every pool is in before governance arms one, in which no prepaid
/// deadline can be settled at all.
///
/// One call, one publication: the economics, the terms and the books land
/// atomically, and the version they create is sellable only after all of
/// them exist. Returns the version new sessions will pin.
async fn publish_turbo_tier_unarmed(fixture: &PropFixture, terms: TurboTerms) -> u32 {
    let response = fixture
        .deployment
        .pool
        .methods()
        .publish_tier_v2(
            TURBO_TIER_ID,
            turbo_tier_params(),
            terms.clone(),
            vec![fixture.order_book.contract_id],
        )
        .with_contract_ids(&[
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .call()
        .await
        .unwrap();
    let version = response.value;
    let published = response
        .decode_logs_with_type::<TierVersionPublishedV2>()
        .unwrap();
    assert_eq!(published.len(), 1);
    assert_eq!(published[0].tier_id, TURBO_TIER_ID);
    assert_eq!(published[0].version, version);
    assert_eq!(published[0].terms, terms);
    assert_eq!(published[0].rollover_window_seconds, 21_600);
    // Derived under the prepaid regime (`k = line`), so the static floor
    // reads `line + maintenance` - above `V` by construction, which is
    // exactly why a prepaid session never uses it: the drawdown schedule
    // is its only floor, and publication requires one.
    assert_eq!(published[0].k, 10_000_000);
    assert_eq!(published[0].threshold_floor, 10_100_000);
    // The V2 publication does NOT emit the legacy event: a pre-restructure
    // consumer must skip this tier, never render it as refundable.
    assert!(
        response
            .decode_logs_with_type::<TierVersionPublished>()
            .unwrap()
            .is_empty()
    );
    version
}

/// Closes the fixture's legacy session and opens a prepaid one on the same
/// account — the reusable-container property doing exactly what it is for.
async fn open_turbo_session(fixture: &PropFixture) -> SessionOpened {
    fixture.close_session().await;
    start_turbo_session(fixture).await
}

/// The opening half alone, for a test whose account is already sessionless.
async fn start_turbo_session(fixture: &PropFixture) -> SessionOpened {
    start_turbo_session_paying(fixture, TURBO_ENTRY).await
}

/// The same, paying an exact `entry` — the price is the deposit plus the
/// fee, and a turbo entry must equal it to the unit, so a discounted entry
/// pays a smaller total and a wrong one is refused.
async fn start_turbo_session_paying(fixture: &PropFixture, entry: u64) -> SessionOpened {
    let response = fixture
        .account
        .methods()
        .start_session(TURBO_TIER_ID, entry, ProlongPeriod::Week)
        .call_params(CallParameters::new(
            entry,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .with_contract_ids(&[
            fixture.deployment.oracle_id,
            fixture.deployment.pool_id,
            fixture.deployment.registry_id,
        ])
        // The fee half of the price leaves for the platform's ADDRESS inside
        // this very call, and an address transfer needs an output to land on
        // — the zero-fee legacy fixture never had to provide one.
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap();
    let opened = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionOpened>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(opened.len(), 1);
    opened.into_iter().next().unwrap()
}

/// Re-arms the account's session key from CHAIN time.
///
/// The fixture arms it for a day, matching its own one-day legacy tier. A
/// seven-day turbo term outlives that by design, so any test that jumps the
/// chain across a term has to re-issue the key before it can drive the
/// account again — the parent may always do so, and `set_session` simply
/// overwrites the stored key.
async fn refresh_session_key(fixture: &PropFixture) {
    let chain = fixture
        .user
        .try_provider()
        .unwrap()
        .latest_block_time()
        .await
        .unwrap()
        .map(|time| time.timestamp() as u64)
        .unwrap_or(0);
    fixture
        .account
        .methods()
        .set_session(ParallelSessionArgs {
            nonce: U256::zero(),
            session_id: Identity::Address(fixture.user.address()),
            expiry: Time {
                unix: chain + 86_400,
            },
            contract_ids: vec![],
        })
        .with_contract_ids(&[fixture.deployment.oracle_id])
        .call()
        .await
        .unwrap();
}

/// Moves the chain just past the session's deadline WITHOUT expiring it.
async fn advance_past_expiry(fixture: &PropFixture) {
    let session = fixture.session().await;
    let provider = fixture.outsider.try_provider().unwrap();
    let latest = provider
        .latest_block_time()
        .await
        .unwrap()
        .expect("local chain has a latest block time");
    let seconds = session.expires_at.saturating_sub(latest.timestamp() as u64) + 1;
    let target = latest
        .checked_add_signed(chrono::TimeDelta::seconds(seconds as i64))
        .expect("test expiry timestamp is representable");
    provider.produce_blocks(1, Some(target)).await.unwrap();
}

/// The keeper settling a PREPAID deadline, driven the way the backend drives
/// it: it declares how much of the session's value arrived from outside, and
/// what it decided to do, and cosigns both.
///
/// Kept fallible throughout — half of what these tests prove is which
/// settlements the pool REFUSES.
async fn try_settle(
    fixture: &PropFixture,
    outside: u64,
    roll: bool,
) -> Result<CallResponse<()>> {
    let signature =
        expiry_cosignature(fixture, outside, roll, fixture.deployer.clone()).await;
    settle_with(fixture, outside, roll, signature, None).await
}

/// The settlement call with the signature and the submitter handed in — for
/// the tests that present a forged one, a stale one, or one carried by
/// somebody other than the keeper.
async fn settle_with(
    fixture: &PropFixture,
    outside: u64,
    roll: bool,
    signature: Signature,
    caller: Option<Wallet>,
) -> Result<CallResponse<()>> {
    let pool = match caller {
        Some(caller) => fixture.deployment.pool.clone().with_account(caller),
        None => fixture.deployment.pool.clone(),
    };
    Ok(pool
        .methods()
        .expire_or_rollover(fixture.child_id, vec![], outside, roll, signature)
        .with_contracts(&[
            &fixture.account,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await?)
}

/// The keeper closing the session out. Nothing arrived from outside, and it
/// decided the week was not earned.
async fn try_expire(fixture: &PropFixture) -> Result<CallResponse<()>> {
    try_settle(fixture, 0, false).await
}

/// The keeper claiming the free week. Nothing arrived from outside — these
/// sessions earn what they earn — so the pool's bar sees the whole gain.
async fn try_roll(fixture: &PropFixture) -> Result<CallResponse<()>> {
    try_settle(fixture, 0, true).await
}

/// The PERMISSIONLESS deadline, driven by `caller`. Legacy sessions settle
/// here; a prepaid one must not.
async fn try_legacy_expire(
    fixture: &PropFixture,
    caller: Wallet,
) -> Result<CallResponse<()>> {
    Ok(fixture
        .deployment
        .pool
        .clone()
        .with_account(caller)
        .methods()
        .expire_session(fixture.child_id, vec![])
        .with_contracts(&[
            &fixture.account,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await?)
}

/// The expiry cosignature over the session as it stands RIGHT NOW.
///
/// Reads `session_id` and `expires_at` off chain rather than tracking them,
/// because both move: a roll bumps the deadline a week on, which is exactly
/// what spends the previous signature. `signer` is a parameter so a test can
/// present a signature from the wrong key.
async fn expiry_cosignature(
    fixture: &PropFixture,
    outside: u64,
    roll: bool,
    signer: Wallet,
) -> Signature {
    let session = fixture
        .deployment
        .pool
        .methods()
        .get_session(fixture.child_id)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value
        .expect("no session to settle");
    let chain_id = fixture
        .user
        .provider()
        .consensus_parameters()
        .await
        .unwrap()
        .chain_id();
    let message = generate_pool_expiry_signing_payload(
        *chain_id,
        fixture.deployment.pool.contract_id(),
        fixture.child_id,
        session.session_id,
        session.expires_at,
        outside,
        roll,
    );
    Signature::Secp256k1(Secp256k1 {
        bits: *signer.signer().sign(message).await.unwrap(),
    })
}

async fn rollover_view(fixture: &PropFixture) -> crate::prop::RolloverView {
    fixture
        .deployment
        .pool
        .methods()
        .get_rollover(fixture.child_id)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value
        .unwrap()
}

/// A prepaid publication is one transaction, and its refusals are whole:
/// an incoherent configuration leaves NO trace - no version, no terms,
/// nothing sellable. And once published, the terms are immutable by
/// construction rather than by guard: no call that could change them
/// exists, so there is no retroactive-terms attack to refuse and no
/// publish-then-attach race to police.
#[tokio::test]
async fn a_turbo_publication_is_atomic_and_refuses_incoherent_terms_whole() {
    let fixture = PropFixture::new().await;
    let pool = fixture.deployment.pool.clone();

    let before = pool
        .methods()
        .current_tier_version(TURBO_TIER_ID)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert_eq!(before, None, "the turbo tier does not exist yet");

    // A FORFEIT-ONLY shape - drawdown, no rollover - is a real product:
    // the floor is measured from the LINE and needs no anchor (an absent
    // rollover row is term one forever), so the schedule stands on its own.
    // Published on its own id so the atomicity checks below still start
    // from a tier that does not exist.
    let mut forfeit_only = turbo_terms(DRAWDOWN_SCHEDULE);
    forfeit_only.rollover_profit_bps = 0;
    forfeit_only.max_rollovers = 0;
    pool.methods()
        .publish_tier_v2(
            TURBO_TIER_ID + 2,
            turbo_tier_params(),
            forfeit_only,
            vec![fixture.order_book.contract_id],
        )
        .with_contract_ids(&[
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .call()
        .await
        .expect("a forfeit-only prepaid tier publishes");

    // A schedule with a zero in ANY step the session can reach is refused at
    // publish. Step 0 opens the session already on its liquidation line; a
    // later zero is worse, because a rollover re-anchors to `V` and the user
    // is seized on the block after he EARNS that week - and the publication
    // is immutable, so the version could never be repaired. The escalator
    // must also never narrow.
    for (schedule, what) in [
        ([0, 200, 250, 300], "a dead first step"),
        ([150, 0, 250, 300], "a dead middle step"),
        ([150, 200, 250, 0], "a dead last step"),
        ([150, 100, 250, 300], "a step that narrows"),
    ] {
        let mut bad = turbo_terms(DRAWDOWN_SCHEDULE);
        bad.max_loss_bps = schedule;
        let error = pool
            .methods()
            .publish_tier_v2(
                TURBO_TIER_ID,
                turbo_tier_params(),
                bad,
                vec![fixture.order_book.contract_id],
            )
            .with_contract_ids(&[
                fixture.order_book.contract_id,
                fixture.deployment.price_feed_id,
            ])
            .call()
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("InvalidTurboTerms"),
            "{what} must be refused: {error:#}"
        );
    }

    // Two preconditions of the zero-collateral model, each refused whole.
    // A tier with NO drawdown would sell sessions born liquidatable (with
    // the pool funding the whole line, the legacy floor sits above `V`
    // from birth); and a cap under the line would truncate the line the
    // seat is born holding.
    let mut floorless = turbo_terms(DRAWDOWN_SCHEDULE);
    floorless.max_loss_bps = [0, 0, 0, 0];
    for (params, bad, what) in [
        (turbo_tier_params(), floorless, "a tier selling no drawdown"),
        (
            {
                let mut narrow = turbo_tier_params();
                narrow.max_credit_line_bps = 9_999;
                narrow
            },
            turbo_terms(DRAWDOWN_SCHEDULE),
            "a cap under the line",
        ),
    ] {
        let error = pool
            .methods()
            .publish_tier_v2(
                TURBO_TIER_ID,
                params,
                bad,
                vec![fixture.order_book.contract_id],
            )
            .with_contract_ids(&[
                fixture.order_book.contract_id,
                fixture.deployment.price_feed_id,
            ])
            .call()
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("InvalidTurboTerms"),
            "{what} must be refused: {error:#}"
        );
    }

    // A step the session can NEVER reach is nobody's business: this tier
    // sells one rollover, so only steps 0 and 1 are ever indexed.
    let mut short = turbo_terms([150, 200, 0, 0]);
    short.max_rollovers = 1;
    pool.methods()
        .publish_tier_v2(
            TURBO_TIER_ID + 1,
            turbo_tier_params(),
            short,
            vec![fixture.order_book.contract_id],
        )
        .with_contract_ids(&[
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .call()
        .await
        .expect("only reachable steps are policed");

    // Only the admin publishes, exactly as with the legacy call.
    let error = pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .publish_tier_v2(
            TURBO_TIER_ID,
            turbo_tier_params(),
            turbo_terms(DRAWDOWN_SCHEDULE),
            vec![fixture.order_book.contract_id],
        )
        .with_contract_ids(&[
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AccessControlNotAuthorized"),
        "{error:#}"
    );

    // ATOMICITY: every refusal above left NO trace - the tier still does
    // not exist. A refused publication is whole, like the successful one.
    // refused publication leaves no half-published version behind.
    let after = pool
        .methods()
        .current_tier_version(TURBO_TIER_ID)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert_eq!(after, None, "a refused publication must leave no trace");

    // The happy path, then the two kinds side by side: the v2 version
    // carries its terms, and the legacy tier the fixture booted with -
    // published through the v1 call - carries none.
    let version = publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    let stored = pool
        .methods()
        .get_turbo_terms(TURBO_TIER_ID, version)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert_eq!(stored, Some(turbo_terms(DRAWDOWN_SCHEDULE)));
    assert_eq!(
        pool.methods()
            .get_turbo_terms(TIER_ID, 1)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        None,
        "a legacy publication never carries terms"
    );
    // And the live legacy session stays legacy, with the turbo tier beside it.
    assert_eq!(
        pool.methods()
            .session_turbo_terms(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        None,
    );
}

/// The rollout as it will actually be run: the new product ships on NEW
/// tier ids, and the old ids are switched off so they sell nothing further.
/// Neither half touches a session that is already open.
///
/// The switch is sales-only by design. An old session keeps its pinned
/// terms and every call it ever had — which is the whole backward-compat
/// promise, and the reason this is not the design doc's `deprecated`, which
/// deliberately stops prolongation too in order to wind a bad version down.
#[tokio::test]
async fn switching_an_old_tier_off_stops_its_sales_and_strands_no_session() {
    let mut fixture = PropFixture::new().await;
    let pool = fixture.deployment.pool.clone();

    // Every tier is enabled by default, including ones published before the
    // switch existed — the storage default has to mean "open for business".
    assert!(
        pool.methods()
            .is_tier_enabled(TIER_ID)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );

    // The new product goes out on its own tier id, beside the old one.
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;

    // Only the admin may work the switch.
    let error = pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .set_tier_enabled(TIER_ID, false)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AccessControlNotAuthorized"),
        "{error:#}"
    );

    let response = pool
        .methods()
        .set_tier_enabled(TIER_ID, false)
        .call()
        .await
        .unwrap();
    let changed = response
        .decode_logs_with_type::<TierEnabledChanged>()
        .unwrap();
    assert_eq!(changed.len(), 1);
    assert_eq!(changed[0].tier_id, TIER_ID);
    assert!(!changed[0].enabled);
    assert!(
        !pool
            .methods()
            .is_tier_enabled(TIER_ID)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );

    // The session the old tier already sold owes the switch nothing: it
    // still reports its own cohort and still buys time on its pinned terms.
    assert_eq!(
        pool.methods()
            .session_turbo_terms(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        None,
    );
    let response = fixture
        .call_account(vec![fixture.prolong_call(1)], 1)
        .await
        .unwrap();
    let prolonged = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionProlonged>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].fee, 6_000);

    // But it sells nothing further...
    fixture.close_session().await;
    let error = fixture
        .account
        .methods()
        .start_session(TIER_ID, COLLATERAL, ProlongPeriod::SixHours)
        .call_params(CallParameters::new(
            COLLATERAL,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .with_contracts(&[
            &fixture.deployment.oracle,
            &fixture.deployment.pool,
            &fixture.deployment.registry,
        ])
        .call()
        .await
        .unwrap_err();
    assert!(error.to_string().contains("TierDisabled"), "{error:#}");

    // ...while the new tier sells the new product on the same account,
    // which is already sessionless after the close above.
    let opened = start_turbo_session(&fixture).await;
    assert_eq!(opened.tier_id, TURBO_TIER_ID);
    assert_eq!(
        pool.methods()
            .session_turbo_terms(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(turbo_terms(DRAWDOWN_SCHEDULE)),
    );

    // And the switch is reversible - it closes a shop, it does not burn one.
    pool.methods()
        .set_tier_enabled(TIER_ID, true)
        .call()
        .await
        .unwrap();
    assert!(
        pool.methods()
            .is_tier_enabled(TIER_ID)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
}

/// The entry is a price: the fee leaves at the door, the deposit leaves at
/// the close, and a break-even user walks away with exactly nothing — while
/// every coin is accounted to the platform.
#[tokio::test]
async fn a_turbo_entry_is_forfeited_whole_and_the_walkaway_is_profits_only() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;

    let platform_before = fixture
        .deployer
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let opened = open_turbo_session(&fixture).await;
    // The purchase posts NOTHING: the ledger opens at zero, the line whole.
    assert_eq!(opened.collateral, 0);
    assert_eq!(opened.open_fee, TURBO_FEE);
    assert_eq!(opened.fees_accrued, 0);
    assert_eq!(opened.credit_line, LINE);
    // The anchor is `V` at open: the line, exactly.
    let view = rollover_view(&fixture).await;
    assert_eq!(view.anchor, LINE);
    assert_eq!(view.rollovers_used, 0);
    assert_eq!(view.max_rollovers, 3);
    assert_eq!(view.profit_required, ROLLOVER_BAR);
    // The fee half of the price reached the platform inside the opening call.
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        platform_before + TURBO_FEE as u128
    );

    // A break-even close: the deposit is forfeited, not refunded.
    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let response = fixture.close_session().await;
    let closed = fixture.closed_event(&response);
    assert_eq!(closed.user_net, 0);
    assert!(closed.payout_parent.is_empty());
    let settled = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<TicketSettled>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(settled.len(), 1);
    assert_eq!(settled[0].ticket, TURBO_DEPOSIT);
    assert_eq!(
        settled[0].to_platform, TURBO_DEPOSIT,
        "no loss, so no absorption"
    );
    assert_eq!(settled[0].absorbed_by_pool, 0);
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        platform_before + TURBO_ENTRY as u128,
        "the platform's whole take is the price: fee at the door, deposit at the close"
    );
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        parent_before,
        "a break-even prepaid user gets exactly nothing back"
    );
}

/// A prepaid ticket cannot be NETTED away - structurally.
///
/// `draw -> repay_from_collateral` moves no coins, so it slips past every
/// gate that watches value leaving. Under the old deposit-as-collateral
/// model that walk made a non-refundable entry refundable in two calls and
/// a guard had to chase it. Now the ticket never enters `collateral` at
/// all: the session's ledger is zero, `amount <= collateral` refuses every
/// netting by plain arithmetic, and there is no guard left to get wrong.
#[tokio::test]
async fn a_prepaid_ticket_cannot_be_netted_away() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;

    let platform_before = fixture
        .deployer
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    open_turbo_session(&fixture).await;

    // Draw the deposit, then try to net it against funded collateral.
    let draw = fixture.draw_call(TURBO_DEPOSIT);
    fixture.call_account(vec![draw], 1).await.unwrap();
    let repay = fixture.repay_from_collateral_call(TURBO_DEPOSIT);
    let error = fixture.call_account(vec![repay], 0).await.unwrap_err();
    let refusal = format!("{error:?}");
    assert!(
        refusal.contains("INSUFFICIENT_BALANCE")
            || refusal.contains("InsufficientBalance"),
        "there is no collateral to net - the ticket is not in the ledger: {refusal}"
    );
    assert_eq!(
        fixture.session().await.collateral,
        0,
        "the refused netting moved nothing, and there was nothing to move"
    );

    // Hand the draw back the honest way and close: the ticket is forfeited in
    // full and the user walks away with nothing.
    let ret = fixture.pool_call(
        fn_selector!(return_quote(u64)),
        TURBO_DEPOSIT,
        fixture.collateral_asset,
        Some(call_data!(TURBO_DEPOSIT)),
    );
    fixture.call_account(vec![ret], 0).await.unwrap();

    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let response = fixture.close_session().await;
    let closed = fixture.closed_event(&response);
    assert_eq!(closed.user_net, 0);
    let settled = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<TicketSettled>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(settled.len(), 1);
    assert_eq!(
        settled[0].to_platform, TURBO_DEPOSIT,
        "the whole deposit reaches the platform"
    );
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        platform_before + TURBO_ENTRY as u128,
        "the platform's take is the whole price"
    );
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        parent_before,
        "and the parent gets nothing back"
    );
}

/// A prepaid session takes a top-up on the same terms as a legacy one, from
/// an outsider included.
///
/// It once refused every funder, and the reason was the rollover bar: a gift
/// raises `V` without being earned, so an outsider could buy a user his free
/// week. The bar no longer counts outside money — the keeper supplies what
/// arrived and the pool nets it off — so the ban lost its reason and went
/// with it. A gift now does what a gift should: it funds the line, and it is
/// still there for the user at settlement.
#[tokio::test]
async fn a_top_up_lands_on_a_prepaid_session_as_it_does_on_a_legacy_one() {
    let fixture = PropFixture::new().await;

    // The legacy fixture session accepts an outside top-up, exactly as before.
    fixture.fund_collateral(100_000).await;
    assert_eq!(fixture.session().await.collateral, COLLATERAL + 100_000);

    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;
    fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .add_collateral(fixture.child_id)
        .call_params(CallParameters::new(
            100_000,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .call()
        .await
        .expect("an outsider may fund a prepaid session's line");

    // It landed, and it landed as LINE: the gift is the ONLY collateral a
    // prepaid session ever has - the entry itself posted nothing.
    let session = fixture.session().await;
    assert_eq!(session.collateral, 100_000);
}

/// The prepaid floor counts LATER fees. A top-up is the one collateral a
/// prepaid session has, `repay_base_from_collateral` is the one call that
/// accrues a fee against it - and the pool leg then pays the top-up back
/// out NET of that fee. Pinned as a boundary, one unit each way, because
/// every other prepaid test runs with `fees_accrued` at zero.
#[tokio::test]
async fn a_topped_up_seat_withdraws_its_top_up_net_of_later_fees() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    let top_up = 100_000u64;
    fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.user.clone())
        .methods()
        .add_collateral(fixture.child_id)
        .call_params(CallParameters::new(
            top_up,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .call()
        .await
        .unwrap();

    // Borrow a sliver of base and net it back out of the top-up: 10^7 base
    // units cost 20_000 quote at the 2.0 ask, plus the 100 ppm fee of 2.
    let quantity = 10_000_000u64;
    let value = 20_000u64;
    let fee = 2u64;
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    fixture.call_account(vec![borrow], 1).await.unwrap();
    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, quantity);
    fixture.call_account(vec![repay], 1).await.unwrap();

    let session = fixture.session().await;
    assert_eq!(session.collateral, top_up - value);
    assert_eq!(session.fees_accrued, fee);

    // One unit past the fee-netted top-up is refused by name...
    let withdrawable = top_up - value - fee;
    let over = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, withdrawable + 1)),
    );
    let error = fixture.call_account(vec![over], 2).await.unwrap_err();
    let refusal = format!("{error:?}");
    assert!(
        refusal.contains("BELOW_TIER_COLLATERAL")
            || refusal.contains("BelowTierCollateral"),
        "the fee's cover may not leave: {refusal}"
    );

    // ...and the exact figure goes home, leaving only the fee's cover.
    let take = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, withdrawable)),
    );
    fixture.call_account(vec![take], 2).await.unwrap();
    assert_eq!(fixture.session().await.collateral, fee);
}

/// The flat journey: no profit means no rollover — not due before the
/// window, not earned inside it — and expiry forfeits the stake.
#[tokio::test]
async fn a_flat_turbo_session_earns_nothing_and_expires_into_forfeit() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    advance_past_expiry(&fixture).await;

    // Nothing was earned, so the ONE deadline call absorbs rather than
    // rolling. There is no separate refusal to observe any more: the
    // outcome IS the observation.
    let response = try_expire(&fixture).await.unwrap();
    let closed = fixture.closed_event(&response);
    assert!(matches!(closed.reason, SettlementReason::Expiry));
    let settled = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<TicketSettled>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(settled.len(), 1);
    assert_eq!(settled[0].ticket, TURBO_DEPOSIT);
    assert_eq!(settled[0].to_platform, TURBO_DEPOSIT);

    // A zero-activity seat owes nothing and is routed nothing: the ticket
    // the pool already holds settles the whole exit, so the five-term
    // identity closes at zero on both sides.
    let seized = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionSeized>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(seized.len(), 1);
    assert!(seized[0].debt.is_empty(), "{:?}", seized[0].debt);
    assert!(
        seized[0].transferred.is_empty(),
        "{:?}",
        seized[0].transferred
    );
}

/// The winning journey, end to end: a 20% gain outranks the deadline, the
/// roll is free and re-bases the anchor, and the escalator's next step then
/// holds the winner to 2% below the NEW anchor — where the static floor
/// would have let the whole profit burn back off.
#[tokio::test]
async fn a_nine_percent_winner_is_rolled_by_the_expiry_trigger() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // Long one whole base at 2.0, then mark it at 4.0: +2_000_000 of profit,
    // twice the 1_000_000 the rollover demands.
    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    fixture
        .publish_base_price(4_000_000_000_000_000_000u128)
        .await;
    assert_eq!(fixture.session_value().await, 12_000_000);

    let expires_before = fixture.session().await.expires_at;
    advance_past_expiry(&fixture).await;

    // The deadline does not take the earned extension away - it GRANTS it.
    // One permissionless trigger ends the term, and what it does with it
    // depends only on what the session earned: the anchor re-bases to the
    // valuation that earned it and the deadline moves a week from where it
    // stood.
    let response = try_roll(&fixture).await.unwrap();
    let rolled = response
        .decode_logs_with_type::<SessionRolledOver>()
        .unwrap();
    assert_eq!(rolled.len(), 1);
    assert_eq!(rolled[0].rollovers_used, 1);
    assert_eq!(rolled[0].max_rollovers, 3);
    assert_eq!(rolled[0].anchor, 12_000_000);
    assert_eq!(rolled[0].profit_required, ROLLOVER_BAR);
    assert_eq!(rolled[0].new_expires_at, expires_before + 604_800);
    assert_eq!(fixture.session().await.expires_at, expires_before + 604_800);

    // The second period gives the whole gain back: `V` returns to the line.
    // He is NOT liquidated for that. The drawdown is sold on the account
    // SIZE, so handing back profit lands him exactly where he started, with
    // the second term's allowance still ahead of him - a floor that had
    // re-anchored to his 12_000_000 peak would have taken the account here,
    // which is the trailing drawdown this product does not sell.
    fixture
        .publish_base_price(2_000_000_000_000_000_000u128)
        .await;
    assert_eq!(fixture.session_value().await, 10_000_000);
    let lines = fixture.lines().await;
    // The line: 10_000_000 − the escalator's second step (2% of the line)
    // + the absorption cost of the 2_000_000 position it still holds
    // (1% haircut = 20_000), which rides ON TOP of the user's allowance
    // rather than flooring it.
    assert_eq!(lines.threshold, U256::from(9_820_000u64));
    assert!(
        !fixture.is_liquidatable().await,
        "giving back the gain is not a loss of principal"
    );

    // Only a real loss past the term's allowance takes him. At 1.8 the
    // basket is worth 1_800_000, so `V` is 9_800_000 against a line of
    // 10_000_000 − 200_000 + 18_000 = 9_818_000.
    fixture
        .publish_base_price(1_800_000_000_000_000_000u128)
        .await;
    assert_eq!(fixture.session_value().await, 9_800_000);
    assert_eq!(fixture.lines().await.threshold, U256::from(9_818_000u64));
    assert!(fixture.is_liquidatable().await);
    let closed = fixture.closed_event(&fixture.liquidate().await);
    assert!(matches!(closed.reason, SettlementReason::Liquidation));
    assert!(
        closed.payout_parent.is_empty(),
        "the forfeited stake absorbed the loss and the rest went to the platform"
    );
}

/// A withdrawal leaves the anchor FIXED and grows a separate `withdrawn`
/// tally. The anchor is the rollover BAR's baseline, so moving it would sell
/// a free week for money that was only passed through; the tally is what
/// keeps genuinely banked profit counting toward the next rollover.
///
/// The drawdown floor is not involved either way - it is derived from the
/// tier's LINE, so no sequence of deposits and withdrawals can widen it.
#[tokio::test]
async fn withdrawing_banked_profit_leaves_the_anchor_fixed() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // Cash resting on the account with no draw and no debt is profit by
    // construction — placed directly, as the withdraw suite does.
    let banked = 100_000u64;
    fixture
        .user
        .force_transfer_to_contract(
            fixture.child_id,
            banked,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
    // Nothing is reserved against banked profit: the fee was part of the
    // purchase, never a charge owed by the session, so the whole of it is
    // the user's to take.
    let withdrawable = banked;
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, withdrawable)),
    );
    let response = fixture.call_account(vec![withdraw], 2).await.unwrap();
    let recorded = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<RolloverWithdrawalRecorded>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(recorded.len(), 1);
    assert_eq!(recorded[0].amount, withdrawable);
    assert_eq!(recorded[0].withdrawn_total, withdrawable);
    // The anchor is the period-start baseline and does NOT move on a
    // withdrawal - only the withdrawn tally grows. The floor stays put.
    let view = rollover_view(&fixture).await;
    assert_eq!(view.anchor, LINE);
    assert_eq!(view.withdrawn, withdrawable);
}

/// The accepted-loss tail, proven on chain: a tier may sell a drawdown
/// wider than the deposit funds, and settlement books the shortfall as bad
/// debt. Here the FIRST step is already 3% of the line — floor 9,700,000,
/// below the pool's 9,750,000 principal — so no rollover is needed to reach
/// it. The line is the anchor less the allowance, never clamped at `k`.
#[tokio::test]
async fn a_tier_can_sell_a_drawdown_wider_than_the_pools_principal() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms([300, 300, 300, 300])).await;
    open_turbo_session(&fixture).await;

    // Flat, at open: the floor is 3% below the line, deeper than the
    // ticket's first-loss bucket reaches - the tail past the ticket is the
    // pool's accepted loss.
    let ticket_edge = LINE - TURBO_DEPOSIT;
    let threshold = fixture.lines().await.threshold;
    assert_eq!(threshold, U256::from(LINE - LINE * 300 / 10_000));
    assert!(
        threshold < U256::from(ticket_edge),
        "the sold drawdown reaches past the ticket"
    );

    // Trade down past it and be liquidated into bad debt.
    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    fixture
        .publish_base_price(1_500_000_000_000_000_000u128)
        .await;
    assert!(fixture.is_liquidatable().await);

    let bad_debt_before = fixture.bad_debt().await;
    let closed = fixture.closed_event(&fixture.liquidate().await);
    assert!(matches!(closed.reason, SettlementReason::Liquidation));
    assert!(
        closed.bad_debt != 0,
        "a liquidation below the principal must book the shortfall"
    );
    assert_eq!(fixture.bad_debt().await, bad_debt_before + closed.bad_debt);
}

/// The rule the product settled on: the weekly target is a FLAT 9% of the
/// account size — $900 on a $10K account, every week, never re-based — and
/// a withdrawal during the week still counts toward it.
///
/// This is the case that makes the two halves inseparable. A user who makes
/// $2K and banks it ends the week with his NAV back at the line, so a naive
/// "did NAV grow by 9%?" test would refuse him the rollover he earned. The
/// anchor is what remembers: it falls by exactly what left, so `V - anchor`
/// still reads the whole $2K. Algebraically it is the same quantity as
/// `(NAV + withdrawn) - start`, and this test pins it end to end.
#[tokio::test]
async fn a_banked_week_still_counts_toward_a_target_that_never_moves() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // ...and a prepaid one identifies as prepaid, carrying the exact terms
    // it was sold under.
    assert_eq!(
        fixture
            .deployment
            .pool
            .methods()
            .session_turbo_terms(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(turbo_terms(DRAWDOWN_SCHEDULE)),
    );

    let opening = rollover_view(&fixture).await;
    assert_eq!(opening.anchor, LINE);
    assert_eq!(opening.profit_required, ROLLOVER_BAR);

    // ── Make 2_000_000 — more than twice the 900_000 bar ─────────────────
    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    fixture
        .publish_base_price(4_000_000_000_000_000_000u128)
        .await;
    assert_eq!(fixture.session_value().await, 12_000_000);

    // ── Bank it: sell out, clear the draw, take the profit off the desk ──
    fixture
        .rest_order(4_000_000, quantity, fixture.collateral_asset, 4_000_000)
        .await;
    let sell = fixture.book_call(4_000_000, quantity, fixture.base_asset, quantity);
    let return_quote = fixture.pool_call(
        fn_selector!(return_quote()),
        cost,
        fixture.collateral_asset,
        None,
    );
    fixture
        .call_account(vec![sell, fixture.settle_book_call(), return_quote], 2)
        .await
        .unwrap();
    let banked = fixture.account_balance(fixture.collateral_asset).await
        - fixture.session().await.fees_accrued;
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, banked)),
    );
    fixture.call_account(vec![withdraw], 2).await.unwrap();

    // His NAV is back where he started — a naive NAV test would say he made
    // nothing this week.
    let nav = fixture.session_value().await;
    assert!(
        nav < (LINE + ROLLOVER_BAR) as i128,
        "the banked user's NAV is back near the line: {nav}"
    );

    let banked_view = rollover_view(&fixture).await;
    // The target did NOT move with him: still a flat 900_000.
    assert_eq!(
        banked_view.profit_required, ROLLOVER_BAR,
        "the weekly target is a flat share of the account size, never re-based"
    );
    // The anchor stays at the period start; the withdrawal is tallied
    // separately, so the week still scores the whole 2_000_000 he made:
    // `(V + withdrawn) - anchor`.
    assert_eq!(banked_view.anchor, LINE);
    assert_eq!(banked_view.withdrawn, banked);
    assert_eq!(
        nav + banked_view.withdrawn as i128 - banked_view.anchor as i128,
        2_000_000
    );

    // ── And he rolls, on a week whose NAV grew by almost nothing ─────────
    advance_past_expiry(&fixture).await;
    // Banking the profit must not cost him the week he earned: the expiry
    // trigger rolls him instead of closing him.
    let response = try_roll(&fixture).await.unwrap();
    let rolled = response
        .decode_logs_with_type::<SessionRolledOver>()
        .unwrap();
    assert_eq!(rolled.len(), 1);
    assert_eq!(rolled[0].rollovers_used, 1);
    // Next week's bar is the same 900_000, measured from the new baseline.
    assert_eq!(rolled[0].profit_required, ROLLOVER_BAR);
    assert_eq!(rolled[0].anchor as i128, nav);
    assert_eq!(rollover_view(&fixture).await.profit_required, ROLLOVER_BAR);
}

/// A PARTIAL withdrawal still counts: a user who made just over the bar and
/// took only part of it home has profit split across two places - what still
/// rests on the desk (`V - anchor`) and what he withdrew (`withdrawn`). Here
/// NEITHER half reaches the 900_000 bar on its own; only the sum does, and
/// the rollover gate must read the sum. This is the mirror of the banked-week
/// test, which drove `V` all the way back to the line - here both terms are
/// load-bearing at once.
#[tokio::test]
async fn a_partial_withdrawal_still_earns_the_rollover_on_the_sum() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;
    assert_eq!(rollover_view(&fixture).await.anchor, LINE);

    // Make exactly 1_000_000 - just over the 900_000 bar. Long one base at
    // 2.0, mark it at 3.0.
    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    fixture
        .publish_base_price(3_000_000_000_000_000_000u128)
        .await;
    assert_eq!(fixture.session_value().await, 11_000_000);

    // Realise it: sell the base back at 3.0 and clear the draw, leaving
    // 1_000_000 of quote profit resting on the account.
    fixture
        .rest_order(3_000_000, quantity, fixture.collateral_asset, 3_000_000)
        .await;
    let sell = fixture.book_call(3_000_000, quantity, fixture.base_asset, quantity);
    let return_quote = fixture.pool_call(
        fn_selector!(return_quote()),
        cost,
        fixture.collateral_asset,
        None,
    );
    fixture
        .call_account(vec![sell, fixture.settle_book_call(), return_quote], 2)
        .await
        .unwrap();

    // Take home only HALF: withdraw 500_000 of the 1_000_000 earned.
    let taken = 500_000u64;
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, taken)),
    );
    fixture.call_account(vec![withdraw], 2).await.unwrap();

    // 500_000 still rests on the desk and 500_000 was withdrawn. Neither
    // half reaches the 900_000 bar; the sum is the whole 1_000_000 he made.
    let nav = fixture.session_value().await;
    assert_eq!(nav, 10_500_000);
    let view = rollover_view(&fixture).await;
    assert_eq!(view.anchor, LINE);
    assert_eq!(view.withdrawn, taken);
    let on_desk = nav - LINE as i128;
    assert!(
        on_desk < ROLLOVER_BAR as i128 && (view.withdrawn as i128) < ROLLOVER_BAR as i128,
        "neither half alone clears the bar: on_desk={on_desk}, withdrawn={}",
        view.withdrawn
    );
    assert_eq!(on_desk + view.withdrawn as i128, 1_000_000);

    // And so he rolls: the gate reads `V + withdrawn`, not `V` alone.
    advance_past_expiry(&fixture).await;
    // A partial withdrawal must not cost him the week he earned.
    let response = try_roll(&fixture).await.unwrap();
    let rolled = response
        .decode_logs_with_type::<SessionRolledOver>()
        .unwrap();
    assert_eq!(rolled.len(), 1);
    assert_eq!(rolled[0].rollovers_used, 1);
    // The new period re-anchors at the current valuation and clears the tally.
    assert_eq!(rolled[0].anchor as i128, nav);
    assert_eq!(rollover_view(&fixture).await.withdrawn, 0);
}

// ---------------------------------------------------------------------------
// The product's user stories, as agreed with product — each test is one
// sentence from that conversation, proven on chain.
// ---------------------------------------------------------------------------

/// "7 day only account." The tier sells the week by NAME: any other period
/// is refused at the door, and the week runs exactly its 604_800 seconds —
/// there is no hand-crafted `start_session(.., Month)` that buys five weeks
/// for the price of one.
#[tokio::test]
async fn a_turbo_account_sells_exactly_seven_days() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    fixture.close_session().await;

    for period in [
        ProlongPeriod::SixHours,
        ProlongPeriod::Day,
        ProlongPeriod::Month,
    ] {
        let error = fixture
            .account
            .methods()
            .start_session(TURBO_TIER_ID, TURBO_ENTRY, period.clone())
            .call_params(CallParameters::new(
                TURBO_ENTRY,
                fixture.collateral_asset,
                u64::MAX,
            ))
            .unwrap()
            .with_contracts(&[
                &fixture.deployment.oracle,
                &fixture.deployment.pool,
                &fixture.deployment.registry,
            ])
            .call()
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("PeriodNotOffered"),
            "{period:?} must be refused by name, not by price: {error:#}"
        );
    }

    let opened = start_turbo_session(&fixture).await;
    assert_eq!(
        opened.expires_at - opened.started_at,
        604_800,
        "the week is the whole term - the tier's base duration is pinned to zero"
    );
}

/// "So basically, a user can pay for 1 week and get 3 free weeks." The
/// headline journey: one payment, three earned rollovers with the drawdown
/// widening each week, and after the cap even a profitable week ends the
/// account — the profits going home with the user.
#[tokio::test]
async fn one_payment_buys_at_most_four_weeks_and_the_last_profit_goes_home() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // One position, held for a month: 1 whole base bought at 2.0. Each
    // week's +1.0 price print is +1_000_000 of profit - comfortably past
    // the 900_000 bar.
    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();

    // Weeks 1-3: earn, expire refused, roll free, drawdown steps.
    let mut price = 2_000_000_000_000_000_000u128;
    for week in 1u64..=3 {
        price += 1_000_000_000_000_000_000;
        fixture.publish_base_price(price).await;
        advance_past_expiry(&fixture).await;
        // Captured BEFORE the trigger, which now moves the deadline itself.
        let expires_before = fixture.session().await.expires_at;
        let response = try_roll(&fixture).await.unwrap();
        let rolled = response
            .decode_logs_with_type::<SessionRolledOver>()
            .unwrap();
        assert_eq!(rolled.len(), 1);
        assert_eq!(rolled[0].rollovers_used, week, "free week number {week}");
        assert_eq!(rolled[0].new_expires_at, expires_before + 604_800);

        // The drawdown escalator stepped WITH the roll: the live line is
        // the ACCOUNT SIZE less this week's allowance, plus the 1% haircut
        // cost of the held basket - every term exact.
        let anchor = rolled[0].anchor;
        assert!(
            anchor > LINE,
            "a winner's anchor climbs with him: {anchor} at week {}",
            week + 1
        );
        let allowance = LINE * DRAWDOWN_SCHEDULE[week as usize] / 10_000;
        let basket_value = (price / 1_000_000_000_000) as u64;
        let absorption = basket_value / 100;
        let lines = fixture.lines().await;
        assert_eq!(
            lines.threshold,
            U256::from(LINE - allowance + absorption),
            "week {}'s drawdown is {} bps of the LINE, not of the anchor \
             the roll just set",
            week + 1,
            DRAWDOWN_SCHEDULE[week as usize],
        );
    }

    // Week 4 is profitable TOO - but the cap is spent, so the deadline wins
    // and the account ends, forfeiting the stake and paying the profit out.
    fixture.publish_base_price(6_500_000_000_000_000_000).await;
    advance_past_expiry(&fixture).await;
    let response = try_expire(&fixture).await.unwrap();
    let closed = fixture.closed_event(&response);
    assert!(matches!(closed.reason, SettlementReason::Expiry));
    assert!(
        closed.user_net != 0,
        "the month's profit goes home with the user"
    );
    assert!(!closed.payout_parent.is_empty());
    let settled = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<TicketSettled>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(settled.len(), 1);
    assert_eq!(settled[0].ticket, TURBO_DEPOSIT);
    assert_eq!(settled[0].to_platform, TURBO_DEPOSIT);
}

/// "1.5% max drawdown" — in the FIRST week, before any roll: trading down
/// past 150_000 on the 10_000_000 line is the end of the account, and the
/// money reconciles to the unit.
#[tokio::test]
async fn the_first_week_liquidates_at_the_sold_drawdown() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // Long 1 base at 2.0, then a -10% print: -200_000 of the 150_000 the
    // first week allows.
    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    fixture.publish_base_price(1_800_000_000_000_000_000).await;

    // The line: anchor 10_000_000 - 150_000 + the 1% absorption cost of
    // the 1_800_000 basket = 9_868_000. V is 9_800_000 - under it.
    let lines = fixture.lines().await;
    assert_eq!(lines.threshold, U256::from(9_868_000u64));
    assert_eq!(fixture.session_value().await, 9_800_000);
    assert!(fixture.is_liquidatable().await);

    let response = fixture.liquidate().await;
    let closed = fixture.closed_event(&response);
    assert!(matches!(closed.reason, SettlementReason::Liquidation));
    // Money, to the unit: profit = -2_000_000 drawn + 1_800_000*0.99
    // credited = -218_000; the 250_000 ticket absorbs the loss first and
    // the 32_000 residue is the platform's; the user is paid nothing and
    // the pool books no bad debt.
    let settled = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<TicketSettled>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(settled.len(), 1);
    assert_eq!(settled[0].ticket, 250_000);
    assert_eq!(settled[0].absorbed_by_pool, 218_000);
    assert_eq!(settled[0].to_platform, 32_000);
    assert_eq!(closed.bad_debt, 0);
    assert!(closed.payout_parent.is_empty());
    assert_eq!(closed.user_net, 0);

    // The forced-exit routing keeps the five-term identity whole with the
    // TICKET on the held side - the pool has held those coins since the
    // open. The liquidator is billed only the true shortfall:
    // 2_000_000 drawn + 32_000 paid out - 250_000 ticket = 1_782_000,
    // exactly the basket value handed over - and is routed no cash.
    let seized = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionSeized>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(seized.len(), 1);
    assert_eq!(
        seized[0].debt,
        vec![(fixture.collateral_asset, 1_782_000)],
        "the shortfall must not re-bill the ticket the pool already holds"
    );
    assert!(
        !seized[0]
            .transferred
            .iter()
            .any(|(asset, _)| *asset == fixture.collateral_asset),
        "no session quote remains to route: {:?}",
        seized[0].transferred
    );
}

/// "$250 for $10K / $150 for $5k / $75 for $2.5K" — the three price points
/// are one shape at three sizes, and each forfeits exactly its own deposit.
#[tokio::test]
async fn every_price_point_forfeits_its_own_deposit() {
    let fixture = PropFixture::new().await;
    fixture.close_session().await;

    // (tier_id, line, price): deposit = line/40, fee = line/400.
    for (tier_id, line) in [(8u64, 5_000_000u64), (9u64, 2_500_000u64)] {
        let deposit = line / 40;
        let fee = line / 400;
        let price = deposit + fee;
        fixture
            .deployment
            .pool
            .methods()
            .publish_tier_v2(
                tier_id,
                turbo_tier_params_for(line),
                turbo_terms(DRAWDOWN_SCHEDULE),
                vec![fixture.order_book.contract_id],
            )
            .with_contract_ids(&[
                fixture.order_book.contract_id,
                fixture.deployment.price_feed_id,
            ])
            .call()
            .await
            .unwrap();

        let platform_before = fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap();
        let parent_before = fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap();
        fixture
            .account
            .methods()
            .start_session(tier_id, price, ProlongPeriod::Week)
            .call_params(CallParameters::new(
                price,
                fixture.collateral_asset,
                u64::MAX,
            ))
            .unwrap()
            .with_contracts(&[
                &fixture.deployment.oracle,
                &fixture.deployment.pool,
                &fixture.deployment.registry,
            ])
            .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
            .call()
            .await
            .unwrap();
        let response = fixture.close_session().await;
        let settled = fixture
            .deployment
            .pool
            .log_decoder()
            .decode_logs_with_type::<TicketSettled>(&response.tx_status.receipts)
            .unwrap();
        assert_eq!(settled.len(), 1, "line {line}");
        assert_eq!(settled[0].ticket, deposit, "line {line}");
        assert_eq!(settled[0].to_platform, deposit, "line {line}");
        assert_eq!(
            fixture
                .deployer
                .get_asset_balance(&fixture.collateral_asset)
                .await
                .unwrap(),
            platform_before + price as u128,
            "line {line}: the platform's whole take is the price"
        );
        assert_eq!(
            fixture
                .user
                .get_asset_balance(&fixture.collateral_asset)
                .await
                .unwrap(),
            parent_before - price as u128,
            "line {line}: a break-even user is out exactly the price"
        );
    }
}

/// "Profits can be withdrawn immediately as long as all open positions are
/// closed" — with the position open the withdrawal is refused; flat, the
/// same withdrawal pays the parent.
#[tokio::test]
async fn profits_withdraw_only_once_positions_are_closed() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // Banked cash on the account, and an OPEN position beside it.
    let banked = 100_000u64;
    fixture
        .user
        .force_transfer_to_contract(
            fixture.child_id,
            banked,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
    let quantity = 500_000_000u64;
    let cost = 1_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();

    let withdrawable = banked;
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, withdrawable)),
    );
    let error = fixture
        .call_account(vec![withdraw.clone()], 2)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("QuoteOutstanding"),
        "an open position blocks the withdrawal: {error:#}"
    );

    // Close the position - sell it back and return the draw - and the SAME
    // withdrawal goes through, to the parent's wallet.
    fixture
        .rest_order(2_000_000, quantity, fixture.collateral_asset, cost)
        .await;
    let sell = fixture.book_call(2_000_000, quantity, fixture.base_asset, quantity);
    let return_quote = fixture.pool_call(
        fn_selector!(return_quote()),
        cost,
        fixture.collateral_asset,
        None,
    );
    fixture
        .call_account(vec![sell, fixture.settle_book_call(), return_quote], 2)
        .await
        .unwrap();
    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    fixture.call_account(vec![withdraw], 2).await.unwrap();
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        parent_before + withdrawable as u128,
        "flat, the profit is the user's immediately"
    );
}

/// "I will not close their orders" — a rollover keeps the user's resting
/// book untouched: the order is still working after the roll, and the
/// session trades on.
#[tokio::test]
async fn a_rollover_keeps_the_users_resting_orders() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // Earn the bar with a held position...
    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    fixture.publish_base_price(4_000_000_000_000_000_000).await;

    // ...and a resting SELL working on the book: half the base, far above.
    let resting = quantity / 2;
    let sell = fixture.book_call(8_000_000, resting, fixture.base_asset, resting);
    fixture.call_account(vec![sell], 1).await.unwrap();
    let (base_on_book, _) = fixture
        .order_book
        .order_book
        .methods()
        .get_total_balance_of(Identity::ContractId(fixture.child_id))
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert_eq!(base_on_book, resting);

    let session_before = fixture.session().await.session_id;
    advance_past_expiry(&fixture).await;
    try_roll(&fixture).await.unwrap();

    // The roll moved the deadline and NOTHING else: the resting order is
    // exactly where the user left it.
    let (base_after, _) = fixture
        .order_book
        .order_book
        .methods()
        .get_total_balance_of(Identity::ContractId(fixture.child_id))
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert_eq!(
        base_after, resting,
        "a session that keeps its seat keeps its book"
    );
    assert_eq!(
        fixture.session().await.session_id,
        session_before,
        "same session, alive"
    );
}

/// "Extend Account: 20% discount for buying future turbo accounts" — the
/// on-chain half of that story.
///
/// A prepaid entry is a PRICE, not a deposit: the user hands it over and
/// never gets it back, so a discount cuts the WHOLE ticket — the forfeited
/// deposit as well as the fee. (On a legacy tier the deposit is the user's
/// own returnable margin, so only the fee moves there; that twin is pinned
/// separately.)
///
/// What the discount must NOT change is the account he gets. The line stays
/// the tier's line and the anchor stays with it, so a discounted user buys
/// the same size and the same drawdown; the pool funds the difference and
/// eats the shortfall if he is liquidated. That is the marketing cost, and
/// it is deliberate.
#[tokio::test]
async fn a_repurchase_discount_prices_the_whole_prepaid_ticket_down() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;
    // The first account runs its course.
    fixture.close_session().await;

    // The repurchase grant, exactly as analytics-api would issue it.
    let manager = Identity::Address(fixture.deployer.address());
    fixture
        .deployment
        .pool
        .methods()
        .grant_role(DISCOUNT_MANAGER_ROLE, manager)
        .call()
        .await
        .unwrap();
    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            Identity::Address(fixture.user.address()),
            None,
            Some(UserDiscount {
                discount_bps: 2_000,
                scope: DiscountScope::FirstPremium,
            }),
        )
        .call()
        .await
        .unwrap();

    // 20% off the WHOLE ticket: deposit and fee alike.
    let discounted_fee = TURBO_FEE * 8 / 10;
    let discounted_deposit = TURBO_DEPOSIT * 8 / 10;
    let opened =
        start_turbo_session_paying(&fixture, discounted_deposit + discounted_fee).await;
    assert_eq!(
        opened.open_fee, discounted_fee,
        "20% off the entry fee, reported as charged"
    );
    assert_eq!(opened.fees_accrued, 0, "the fee was bought, not owed");

    // ...and he still buys the SAME ACCOUNT. The line does not shrink with
    // the ticket, or a discount would quietly sell a smaller line and a
    // narrower drawdown than the tier advertises.
    assert_eq!(
        opened.credit_line, TURBO_LINE,
        "a discounted ticket buys the tier's full line"
    );
    let rollover = fixture
        .deployment
        .pool
        .methods()
        .get_rollover(fixture.child_id)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value
        .expect("a rollover-bearing tier anchors at open");
    assert_eq!(
        rollover.anchor, TURBO_LINE,
        "and the bar he must clear is unmoved by the discount"
    );

    // At the close the pool settles the ticket he PAID, not the list price
    // - the bucket holds what actually arrived. His profit is untouched
    // either way: the residue is paid from the pool's own bucket, never
    // from the user's pot.
    fixture
        .deployer
        .force_transfer_to_contract(
            fixture.child_id,
            TURBO_DEPOSIT + 100_000,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
    let response = fixture.close_session().await;
    let settled = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<TicketSettled>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(settled.len(), 1);
    assert_eq!(
        settled[0].ticket, discounted_deposit,
        "the discounted ticket is what the pool holds and settles"
    );
    assert_eq!(settled[0].to_platform, discounted_deposit);
}

/// A non-collateral withdrawal — the one path that reads the oracle — still
/// lowers the anchor, by the BID value of what left, rounded down.
#[tokio::test]
async fn withdrawing_an_asset_lowers_the_anchor_at_the_oracle_bid() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // Base resting on the account with no debt behind it - profit in kind.
    let held = 500_000_000u64;
    fixture
        .user
        .force_transfer_to_contract(
            fixture.child_id,
            held,
            fixture.base_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, held)),
    );
    let response = fixture.call_account(vec![withdraw], 2).await.unwrap();
    let recorded = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<RolloverWithdrawalRecorded>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(recorded.len(), 1);
    // 0.5 base at the 2.0 bid = 1_000_000 recorded as withdrawn; the anchor
    // is untouched.
    assert_eq!(recorded[0].amount, 1_000_000);
    assert_eq!(recorded[0].withdrawn_total, 1_000_000);
    let view = rollover_view(&fixture).await;
    assert_eq!(view.anchor, LINE);
    assert_eq!(view.withdrawn, 1_000_000);
}

/// The entry is the price, no more — through BOTH doors. A turbo account is
/// charged exactly once (the fee at open), takes exactly its price and not a
/// unit over, and refuses every top-up afterwards from every funder. There
/// is no way to fund a turbo session past its stake.
#[tokio::test]
async fn a_turbo_account_takes_its_price_and_never_a_unit_more() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    fixture.close_session().await;

    // OVER-POSTING at open is refused, not clamped: a deposit past the price
    // would be extra room out of the drawdown limit that returns at close.
    let error = fixture
        .account
        .methods()
        .start_session(TURBO_TIER_ID, TURBO_ENTRY + 1, ProlongPeriod::Week)
        .call_params(CallParameters::new(
            TURBO_ENTRY + 1,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .with_contracts(&[
            &fixture.deployment.oracle,
            &fixture.deployment.pool,
            &fixture.deployment.registry,
        ])
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("TurboEntryNotExact"),
        "a turbo entry over its price is refused: {error:#}"
    );

    // Under-posting past the required collateral is the existing floor; a
    // penny below the exact price (but at or above the deposit) is the new
    // one. Exactly the price opens.
    let opened = start_turbo_session_paying(&fixture, TURBO_ENTRY).await;
    assert_eq!(opened.collateral, 0, "the purchase posts nothing");
    assert_eq!(opened.open_fee, TURBO_FEE);
    assert_eq!(opened.fees_accrued, 0, "the fee was bought, not owed");

    // The one fee is the ONLY charge the account ever sees before it closes:
    // no period is prolongable (all refused) and the rollover is free. So
    // `fees_accrued` never moves.
    assert_eq!(fixture.session().await.fees_accrued, 0);

    // The exact-price rule governs the ENTRY, not the stake. A later top-up
    // is a different thing and lands normally — from the owner...
    fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.user.clone())
        .methods()
        .add_collateral(fixture.child_id)
        .call_params(CallParameters::new(
            1_000,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .call()
        .await
        .expect("a top-up is no longer refused — the bar nets outside money");

    // ...and from an unrelated third party too.
    fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .add_collateral(fixture.child_id)
        .call_params(CallParameters::new(
            1_000,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .call()
        .await
        .expect("a gift funds the line like any other top-up");

    // What is exact is the ENTRY, and that is untouched by any of it: the
    // collateral is exactly the two top-ups - the entry itself is not in it.
    assert_eq!(fixture.session().await.collateral, 1_000 + 1_000);
}

/// Earns roughly `2_000_000` of profit in one week and BANKS all of it to
/// the parent wallet, leaving the session flat with its stake intact and
/// its anchor back at the line. Returns what was withdrawn.
///
/// Buy one base at 2.0, mark it at 4.0, sell it back, clear the draw, and
/// withdraw the realised cash net of the fee reserve — the real shape of a
/// user taking his week's profit off the desk.
async fn earn_and_bank_a_week(fixture: &mut PropFixture) -> u64 {
    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture.publish_base_price(2_000_000_000_000_000_000).await;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    fixture.publish_base_price(4_000_000_000_000_000_000).await;
    fixture
        .rest_order(4_000_000, quantity, fixture.collateral_asset, 4_000_000)
        .await;
    let sell = fixture.book_call(4_000_000, quantity, fixture.base_asset, quantity);
    let return_quote = fixture.pool_call(
        fn_selector!(return_quote()),
        cost,
        fixture.collateral_asset,
        None,
    );
    fixture
        .call_account(vec![sell, fixture.settle_book_call(), return_quote], 2)
        .await
        .unwrap();
    let banked = fixture.account_balance(fixture.collateral_asset).await
        - fixture.session().await.fees_accrued;
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, banked)),
    );
    fixture.call_account(vec![withdraw], 2).await.unwrap();
    banked
}

/// The whole life of a turbo account, good weeks and a bad one: pay once,
/// win three weeks and BANK each week's profit to the wallet, roll free
/// each time with the drawdown widening, then on the fourth week — the cap
/// spent — give the session back more than it holds and be liquidated into
/// bad debt. The money reconciles end to end: every banked week is safe in
/// the wallet, the stake is forfeited exactly once, and the loss past the
/// stake is the pool's, not the user's.
#[tokio::test]
async fn the_whole_life_of_a_turbo_account_good_weeks_and_a_bad_one() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;

    open_turbo_session(&fixture).await;
    // Measured from AFTER the entry is paid — the fixture's own legacy
    // session was closed and refunded inside `open_turbo_session`, so the
    // clean baseline is the wallet with the turbo account already open.
    let wallet_after_open = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();

    // ── Weeks 1-3: win, bank the profit, roll free, drawdown widens ──────
    let mut total_banked = 0u64;
    let mut week = 0usize;
    while week < 3 {
        let banked = earn_and_bank_a_week(&mut fixture).await;
        total_banked += banked;

        // Banking dropped the anchor with the profit, so the week still
        // scores what it earned: the roll is due and owed.
        advance_past_expiry(&fixture).await;
        let response = try_roll(&fixture).await.unwrap();
        let rolled = response
            .decode_logs_with_type::<SessionRolledOver>()
            .unwrap();
        assert_eq!(rolled.len(), 1);
        assert_eq!(
            rolled[0].rollovers_used,
            week as u64 + 1,
            "free week number {}",
            week + 1
        );

        // The next week's drawdown is the escalator's next step, measured
        // from the ACCOUNT SIZE. Flat book after the sell, so no absorption
        // cost rides on it: the line is exactly `LINE − allowance`. The
        // anchor moved with the roll and the floor did NOT - that
        // separation is the whole point.
        let anchor = rolled[0].anchor;
        let allowance = LINE * DRAWDOWN_SCHEDULE[week + 1] / 10_000;
        // Reset the mark to the flat 2.0 so the line carries no basket cost.
        fixture.publish_base_price(2_000_000_000_000_000_000).await;
        assert_eq!(
            fixture.lines().await.threshold,
            U256::from(LINE - allowance),
            "week {}'s drawdown is {} bps of the line, and the anchor at \
             {anchor} does not move it",
            week + 2,
            DRAWDOWN_SCHEDULE[week + 1],
        );

        refresh_session_key(&fixture).await;
        week += 1;
    }
    assert_eq!(
        rollover_view(&fixture).await.rollovers_used,
        3,
        "three free weeks earned and consumed"
    );

    // The three banked weeks are already home, safe from whatever week four
    // does: the wallet is up by the withdrawals, less the one entry price.
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        wallet_after_open + total_banked as u128,
        "every banked week is in the wallet"
    );

    // ── Week 4, the bad one: cap spent, and the session gives it all back
    // and then some. Buy a base and let it fall 20% — a 400_000 loss on a
    // stake of 250_000, so profit goes to zero, through zero, and past what
    // the account holds. ──────────────────────────────────────────────────
    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    fixture.publish_base_price(1_600_000_000_000_000_000).await;
    assert!(fixture.is_liquidatable().await);

    // The cap is spent: even if it were somehow profitable, no roll remains,
    // so the deadline call ends the account instead of extending it.
    advance_past_expiry(&fixture).await;

    let bad_debt_before = fixture.bad_debt().await;
    let wallet_before_liq = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let closed = fixture.closed_event(&fixture.liquidate().await);
    assert!(matches!(closed.reason, SettlementReason::Liquidation));

    // The session lost more than its stake: the stake is forfeited whole and
    // the shortfall past it is the POOL's bad debt, not the user's — he
    // owes nothing beyond the entry he already paid.
    assert!(
        closed.profit_is_negative,
        "the session's own result is a loss"
    );
    assert!(
        closed.bad_debt != 0,
        "a loss past the stake must land as bad debt"
    );
    assert_eq!(
        fixture.bad_debt().await,
        bad_debt_before + closed.bad_debt,
        "the shortfall is booked, once"
    );
    assert_eq!(
        closed.user_net, 0,
        "a liquidated session pays the user nothing"
    );
    assert!(closed.payout_parent.is_empty());
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        wallet_before_liq,
        "the bad week takes nothing further from the user's banked profit"
    );

    // The account is empty and reusable: no session, no rollover row.
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .get_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_none()
    );
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .get_rollover(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_none()
    );

    // The whole life, reconciled: the user paid one entry, banked three
    // winning weeks, lost the fourth, and walks away UP by the banked profit
    // minus the price — never charged twice, never chased for the bad debt.
    let final_wallet = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    assert_eq!(
        final_wallet,
        wallet_after_open + total_banked as u128,
        "the bad week moved nothing in the wallet; the three good weeks stand"
    );
    assert!(
        total_banked > TURBO_ENTRY,
        "the banked profit dwarfs the one forfeited stake"
    );
}

/// The cohort boundary refuses in both directions: a LEGACY session cannot be
/// handed to the prepaid deadline call, and a turbo session cannot arm the
/// paid auto-renewal a prepaid tier does not offer. Neither product can reach
/// into the other's machinery.
#[tokio::test]
async fn the_cohort_boundary_refuses_each_product_the_others_machinery() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;

    // The fixture's own live session is on the LEGACY tier, and the call is
    // properly COSIGNED — so the refusal under test is the cohort one and
    // nothing else. A legacy session has no terms and nothing to roll; its
    // deadline belongs to the permissionless `expire_session`.
    let error = try_expire(&fixture).await.unwrap_err();
    assert!(
        error.to_string().contains("UsePermissionlessExpiry"),
        "a legacy deadline is settled by `expire_session`: {error:#}"
    );

    open_turbo_session(&fixture).await;

    // The paid auto-renewal cannot be armed, because a prepaid tier prices no
    // period — the free rollover is its only extension. Checked while the
    // session key is still live: the account's key outlives an hour, not a
    // week, so anything routed through `call_account` has to happen before
    // the clock jumps.
    let arm = fixture.pool_call(
        fn_selector!(set_auto_prolong(Option<ProlongPeriod>)),
        0,
        AssetId::default(),
        Some(call_data!(Some(ProlongPeriod::Day))),
    );
    let error = fixture.call_account(vec![arm], 0).await.unwrap_err();
    assert!(
        error.to_string().contains("PeriodNotOffered"),
        "a prepaid tier prices no period to arm: {error:#}"
    );

    // The other direction, and the one that keeps the prepaid promise: a
    // TURBO session handed to the permissionless call is refused rather than
    // absorbed. Absorbing it there would take away a week it may have
    // earned, decided by a caller who never had to say what arrived from
    // outside — which is the whole reason the prepaid deadline is cosigned.
    advance_past_expiry(&fixture).await;
    let error = try_legacy_expire(&fixture, fixture.deployer.clone())
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("UseExpireOrRollover"),
        "a prepaid deadline is settled by `expire_or_rollover`: {error:#}"
    );
    // An OUTSIDER gets the same answer — the permissionless door is closed to
    // this cohort by cohort, not by caller.
    let error = try_legacy_expire(&fixture, fixture.outsider.clone())
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("UseExpireOrRollover"),
        "the refusal is by cohort, not by caller: {error:#}"
    );
    // Past its deadline and still standing: the refusals settled nothing.
    assert!(
        fixture.session_opt().await.is_some(),
        "a refused deadline leaves the session untouched"
    );
}

/// The prepaid deadline is gated by a SIGNATURE, not by a caller, and the
/// difference is the point: `outside` is the keeper's word about how much of
/// the session's value arrived by transfer rather than being earned, and the
/// pool cannot check it. So the pool authorises the FIGURE — any relayer may
/// carry a signed one, and nobody can submit an unsigned one.
#[tokio::test]
async fn the_prepaid_deadline_takes_only_a_figure_its_own_cosigner_signed() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;
    advance_past_expiry(&fixture).await;

    // The wrong key. The outsider signs the very same bytes, and the pool
    // recovers an address that is not its cosigner.
    let forged = expiry_cosignature(&fixture, 0, false, fixture.outsider.clone()).await;
    let error = settle_with(&fixture, 0, false, forged, None)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("InvalidExpiryCosigner"),
        "only the pool's own cosigner can settle a prepaid deadline: {error:#}"
    );

    // The right key, the WRONG figure. `outside` is signed over, so a
    // signature issued for 900_000 cannot be re-presented as zero — which is
    // exactly the substitution that would forge a free week.
    let for_another_figure =
        expiry_cosignature(&fixture, 900_000, false, fixture.deployer.clone()).await;
    let error = settle_with(&fixture, 0, false, for_another_figure, None)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("InvalidExpiryCosigner"),
        "the signature pins the figure it authorised: {error:#}"
    );

    // Still standing: two refusals settled nothing.
    assert!(fixture.session_opt().await.is_some());

    // And the submitter is nobody in particular. The OUTSIDER carries a
    // signature the cosigner made, and it settles — that is what "authorise
    // the figure, not the caller" buys: the backend signs, any relayer pays
    // the gas.
    let signed = expiry_cosignature(&fixture, 0, false, fixture.deployer.clone()).await;
    let response = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .expire_or_rollover(fixture.child_id, vec![], 0, false, signed)
        .with_contracts(&[
            &fixture.account,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap();
    assert!(matches!(
        fixture.closed_event(&response).reason,
        SettlementReason::Expiry
    ));
}

/// Before governance arms a cosigner the prepaid deadline does not settle AT
/// ALL — it does not fall open to anyone. A pool with no cosigner refuses
/// every settlement rather than accepting any signature, which is the loud
/// failure rather than the silent one.
#[tokio::test]
async fn an_unarmed_pool_settles_no_prepaid_deadline() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier_unarmed(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;
    advance_past_expiry(&fixture).await;

    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .expiry_cosigner()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .is_none(),
        "the pool starts with no expiry cosigner"
    );

    let error = try_expire(&fixture).await.unwrap_err();
    assert!(
        error.to_string().contains("ExpiryCosignerNotSet"),
        "an unarmed pool refuses rather than accepting anyone: {error:#}"
    );
    assert!(fixture.session_opt().await.is_some());

    // Arming it is all that was missing.
    fixture
        .deployment
        .pool
        .methods()
        .set_expiry_cosigner(fixture.deployer.address())
        .call()
        .await
        .unwrap();
    let response = try_expire(&fixture).await.unwrap();
    assert!(matches!(
        fixture.closed_event(&response).reason,
        SettlementReason::Expiry
    ));
}

/// The cosigner is the POOL's, set by its own governance — not borrowed from
/// the account oracle. The two are independent addresses, and the oracle's
/// cosigner has no standing at the pool.
#[tokio::test]
async fn the_pool_keeps_its_own_expiry_cosigner_not_the_oracles() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier_unarmed(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;
    advance_past_expiry(&fixture).await;

    // Arm the pool with a DIFFERENT key from the one the oracle cosigns
    // batches with, and prove the pool follows its own.
    fixture
        .deployment
        .pool
        .methods()
        .set_expiry_cosigner(fixture.outsider.address())
        .call()
        .await
        .unwrap();
    assert_eq!(
        fixture
            .deployment
            .pool
            .methods()
            .expiry_cosigner()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(fixture.outsider.address())
    );

    // The oracle's cosigner — the deployer, who signs every batch in this
    // suite — is now the wrong key here.
    let error = try_expire(&fixture).await.unwrap_err();
    assert!(
        error.to_string().contains("InvalidExpiryCosigner"),
        "the pool does not defer to the oracle's cosigner: {error:#}"
    );

    // The pool's own key settles it.
    let signed = expiry_cosignature(&fixture, 0, false, fixture.outsider.clone()).await;
    let response = settle_with(&fixture, 0, false, signed, None).await.unwrap();
    assert!(matches!(
        fixture.closed_event(&response).reason,
        SettlementReason::Expiry
    ));
}

/// Only governance arms the cosigner. An outsider who could set it could
/// settle every prepaid deadline in the pool on his own word.
#[tokio::test]
async fn only_governance_arms_the_expiry_cosigner() {
    let fixture = PropFixture::new().await;
    let error = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .set_expiry_cosigner(fixture.outsider.address())
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AccessControlNotAuthorized"),
        "arming the cosigner is governance's alone: {error:#}"
    );
}

/// A gift is not a gain. Someone transfers the whole rollover bar straight
/// into the account — no trade, no risk — and the keeper reports it. The pool
/// nets it off and the week is not earned.
///
/// This is the attack the whole `outside` mechanism exists for: `holdings`
/// reads `balance_of(account, asset)`, so a transfer and a trading profit are
/// the same number to the chain. Only the keeper can tell them apart.
#[tokio::test]
async fn a_transferred_gift_does_not_buy_the_free_week() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // Flat: nothing earned, nothing lost.
    let value_before = fixture.session_value().await;

    // An outsider transfers the bar straight in. Nothing on chain marks this
    // as a gift rather than a gain.
    fixture
        .outsider
        .force_transfer_to_contract(
            fixture.child_id,
            ROLLOVER_BAR,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
    assert_eq!(
        fixture.session_value().await,
        value_before + ROLLOVER_BAR as i128,
        "the pool values the gift exactly as it would value a profit"
    );

    advance_past_expiry(&fixture).await;

    // Declared, the gift buys nothing: the pool subtracts it from its own bar
    // and refuses the roll rather than absorbing on a disagreement.
    let error = try_settle(&fixture, ROLLOVER_BAR, true).await.unwrap_err();
    assert!(
        error.to_string().contains("RolloverNotEarned"),
        "a declared gift is netted off the bar: {error:#}"
    );

    // And the declaration is the ONLY thing standing between the gift and a
    // free week — with it reported as zero the very same session rolls. That
    // is why the figure is cosigned rather than passed by whoever calls.
    try_roll(&fixture).await.unwrap();
}

/// Earned profit still rolls with a gift sitting alongside it. `outside` nets
/// off what arrived, never what was made — a user who genuinely earned his
/// week does not lose it because someone sent him money.
#[tokio::test]
async fn a_gift_alongside_real_profit_does_not_cost_the_earned_week() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // Earn the bar the honest way: long a base at 2.0, mark it at 4.0.
    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    fixture
        .publish_base_price(4_000_000_000_000_000_000u128)
        .await;

    // ...and receive a gift on top.
    let gift = 300_000u64;
    fixture
        .outsider
        .force_transfer_to_contract(
            fixture.child_id,
            gift,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();

    advance_past_expiry(&fixture).await;

    // The gift is declared and netted; the trading profit alone still clears
    // the bar, so the week is granted.
    let response = try_settle(&fixture, gift, true).await.unwrap();
    let rolled = response
        .decode_logs_with_type::<SessionRolledOver>()
        .unwrap();
    assert_eq!(rolled.len(), 1, "the earned week survives the netting");
    assert_eq!(rolled[0].rollovers_used, 1);
}

/// The front-run the signed decision exists to stop.
///
/// The settlement transaction is public. An attacker who reads `outside: 0`
/// out of the mempool can transfer the shortfall in ahead of it — and the pool
/// cannot tell that gift from a gain. Before the decision was signed, the
/// keeper's own call would then have granted the week. With it signed, the
/// keeper said ABSORB and absorb is what happens, whatever the balance says by
/// the time the call lands.
#[tokio::test]
async fn a_gift_landing_after_the_keeper_signed_cannot_turn_an_absorb_into_a_roll() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;
    advance_past_expiry(&fixture).await;

    // The keeper looks at a flat session, sees nothing earned, and signs
    // ABSORB with `outside: 0` — a true statement when it was made.
    let signature =
        expiry_cosignature(&fixture, 0, false, fixture.deployer.clone()).await;

    // The attacker front-runs it: the bar arrives as a transfer, so by the
    // time the keeper's call executes the pool's own valuation clears the bar.
    fixture
        .outsider
        .force_transfer_to_contract(
            fixture.child_id,
            ROLLOVER_BAR,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();

    // The stale call still lands — and still absorbs. The decision was signed,
    // so the gift bought nothing.
    let response = settle_with(&fixture, 0, false, signature, None)
        .await
        .unwrap();
    assert!(matches!(
        fixture.closed_event(&response).reason,
        SettlementReason::Expiry
    ));

    // The gift was the attacker's own money and it goes home with the user's
    // settlement, exactly like any other balance the account held.
    assert!(fixture.session_opt().await.is_none());
}

/// The decision is bound, so a signature cannot be re-pointed. A cosigned
/// ABSORB cannot be replayed as a roll, and a cosigned ROLL cannot be replayed
/// as an absorb.
#[tokio::test]
async fn a_cosigned_decision_cannot_be_flipped() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;
    advance_past_expiry(&fixture).await;

    let for_absorb =
        expiry_cosignature(&fixture, 0, false, fixture.deployer.clone()).await;
    let error = settle_with(&fixture, 0, true, for_absorb, None)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("InvalidExpiryCosigner"),
        "an absorb signature does not authorise a roll: {error:#}"
    );

    let for_roll = expiry_cosignature(&fixture, 0, true, fixture.deployer.clone()).await;
    let error = settle_with(&fixture, 0, false, for_roll, None)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("InvalidExpiryCosigner"),
        "a roll signature does not authorise an absorb: {error:#}"
    );
    assert!(fixture.session_opt().await.is_some());
}

/// A cosigned roll the pool disagrees with is REFUSED, not absorbed. Keeper
/// and pool disagreeing about what was earned is not a reason to settle the
/// user — it is a reason to stop, so the keeper can resubmit on figures they
/// both accept.
#[tokio::test]
async fn a_roll_the_pool_disagrees_with_is_refused_rather_than_absorbed() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;
    advance_past_expiry(&fixture).await;

    // Flat session, keeper asks for a roll anyway.
    let error = try_roll(&fixture).await.unwrap_err();
    assert!(
        error.to_string().contains("RolloverNotEarned"),
        "the pool keeps its veto over granting a week: {error:#}"
    );

    // Nothing settled: the session is still there for a correct call.
    assert!(fixture.session_opt().await.is_some());
    let response = try_expire(&fixture).await.unwrap();
    assert!(matches!(
        fixture.closed_event(&response).reason,
        SettlementReason::Expiry
    ));
}

/// A gift routed through `add_collateral` is the OTHER way outside money
/// reaches the bar, and it has to be netted just the same.
///
/// A top-up raises `collateral` — and the bar reads the session's value, of
/// which funded collateral is a part — while the anchor stays where the period
/// started. So an outsider funding a line moves the session toward its bar
/// exactly as a raw transfer does, and the keeper has to count both.
#[tokio::test]
async fn a_top_up_reaches_the_bar_like_any_other_outside_money() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    let value_before = fixture.session_value().await;
    fixture.fund_collateral(ROLLOVER_BAR).await;
    assert_eq!(
        fixture.session_value().await,
        value_before + ROLLOVER_BAR as i128,
        "a top-up moves the session's value as much as a transfer does"
    );

    advance_past_expiry(&fixture).await;
    let error = try_settle(&fixture, ROLLOVER_BAR, true).await.unwrap_err();
    assert!(
        error.to_string().contains("RolloverNotEarned"),
        "an outsider's top-up is outside money too: {error:#}"
    );
}

/// Donate, withdraw, repeat. `withdrawn` and `outside` are both cumulative
/// within a period, so a round trip nets to nothing however many times it is
/// run — the bar cannot be pumped by cycling the same coins.
#[tokio::test]
async fn cycling_the_same_coins_through_the_account_pumps_nothing() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    let cycle = 400_000u64;
    let mut donated = 0u64;
    for _ in 0..3 {
        fixture
            .outsider
            .force_transfer_to_contract(
                fixture.child_id,
                cycle,
                fixture.collateral_asset,
                TxPolicies::default(),
            )
            .await
            .unwrap();
        donated += cycle;

        // Straight back out to the parent wallet. `withdraw` credits the
        // period's `withdrawn` tally, which the bar adds back — so a coin that
        // arrived and left has to cancel exactly.
        let withdraw = fixture.pool_call(
            fn_selector!(withdraw(AssetId, u64)),
            0,
            AssetId::default(),
            Some(call_data!(fixture.collateral_asset, cycle)),
        );
        fixture.call_account(vec![withdraw], 2).await.unwrap();
    }

    advance_past_expiry(&fixture).await;

    // Three round trips of the bar's own size, and the session is exactly as
    // unearned as it started.
    let error = try_settle(&fixture, donated, true).await.unwrap_err();
    assert!(
        error.to_string().contains("RolloverNotEarned"),
        "a round trip nets to nothing, however many times it runs: {error:#}"
    );
}

/// A gift cannot widen the sold drawdown either. The floor is fixed to the
/// LINE the tier sold, so money arriving from outside raises the account's
/// value without moving the liquidation threshold under it.
#[tokio::test]
async fn a_gift_does_not_move_the_liquidation_floor() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    assert_eq!(fixture.lines().await.threshold, U256::from(9_850_000u64));
    fixture
        .outsider
        .force_transfer_to_contract(
            fixture.child_id,
            1_000_000,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
    assert_eq!(
        fixture.lines().await.threshold,
        U256::from(9_850_000u64),
        "the floor is the tier's, not the balance's"
    );
}

/// Settling twice takes nothing twice. Once a deadline is settled the session
/// is gone, and a second cosigned call finds nothing to settle.
#[tokio::test]
async fn a_settled_deadline_cannot_be_settled_again() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;
    advance_past_expiry(&fixture).await;

    // Sign TWO absorbs over the same live session, then spend one.
    let second = expiry_cosignature(&fixture, 0, false, fixture.deployer.clone()).await;
    try_expire(&fixture).await.unwrap();
    assert!(fixture.session_opt().await.is_none());

    let error = settle_with(&fixture, 0, false, second, None)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("NoActiveSession"),
        "a spent deadline has nothing left to settle: {error:#}"
    );
}

/// A cosignature does not let the keeper act EARLY, in either direction.
///
/// This is the pool's own gate rather than the keeper's good behaviour, and
/// it is what bounds the damage a compromised cosigner could do: `absorb`
/// requires the deadline to have passed, and `roll_at_expiry` refuses before
/// it. So the worst a bad signature can do to a live session is nothing.
#[tokio::test]
async fn a_cosigned_settlement_cannot_act_before_the_deadline() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // The clock has NOT been moved: the session is live and mid-term.

    // A cosigned ABSORB is refused — the pool checks the deadline itself.
    let error = try_expire(&fixture).await.unwrap_err();
    assert!(
        error.to_string().contains("NotExpired"),
        "a live session cannot be absorbed on anyone's say-so: {error:#}"
    );

    // ...and a cosigned ROLL is refused too, even from a session that would
    // clear the bar: the free week extends FROM the deadline, so granting it
    // early would hand out a week the term had not yet used.
    fixture.fund_collateral(2_000_000).await;
    let error = try_roll(&fixture).await.unwrap_err();
    assert!(
        error.to_string().contains("RolloverNotEarned"),
        "a week cannot be claimed before the term runs out: {error:#}"
    );

    // Live and untouched throughout.
    let session = fixture.session().await;
    assert_eq!(session.collateral, 2_000_000);
    assert_eq!(
        fixture
            .deployment
            .pool
            .methods()
            .get_rollover(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .expect("still anchored")
            .rollovers_used,
        0,
        "no week was spent"
    );
}

/// Banking profit must not widen the sold drawdown. A user who makes his
/// week's profit and withdraws all of it sits back at the line, and is still
/// liquidated at 1.5% below it — the anchor is the period-start baseline and
/// a withdrawal does not lower it. Under a withdrawal-reduced anchor the
/// floor would drop with the money and let him lose far past the sold limit.
#[tokio::test]
async fn banking_profit_does_not_widen_the_sold_drawdown() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // At open, flat: the floor is 1.5% below the line.
    assert_eq!(fixture.lines().await.threshold, U256::from(9_850_000u64));

    // Make 2_000_000 and bank all of it (sell out, clear the draw, withdraw).
    let banked = earn_and_bank_a_week(&mut fixture).await;
    assert!(banked > 0);

    // Back at the line, flat. The floor is STILL 9_850_000: the anchor did
    // not follow the withdrawal down. The old reducing anchor put it at
    // line − banked − allowance, ~20% of room.
    fixture.publish_base_price(2_000_000_000_000_000_000).await;
    let view = rollover_view(&fixture).await;
    assert_eq!(view.anchor, LINE);
    assert_eq!(view.withdrawn, banked);
    assert_eq!(fixture.lines().await.threshold, U256::from(9_850_000u64));

    // A 10% move against a fresh position (−200_000, past the 150_000
    // allowance) liquidates him — which the widened floor would not have.
    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    fixture.publish_base_price(1_800_000_000_000_000_000).await;
    assert!(fixture.is_liquidatable().await);
}

/// A DISCOUNTED user's profit leaves as freely as a full-price user's.
///
/// Under the old deposit-as-collateral model this was the blocker bug: the
/// floor was the LIST deposit and a discounted ticket posted less, so every
/// withdrawal reverted for the life of the account. Zero-collateral removes
/// the floor entirely - nothing the user posted stands behind the line, so
/// his profit is his and the pool leg simply has nothing to give.
#[tokio::test]
async fn a_discounted_users_profit_withdraws_and_its_ticket_still_does_not() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;

    let manager = Identity::Address(fixture.deployer.address());
    fixture
        .deployment
        .pool
        .methods()
        .grant_role(DISCOUNT_MANAGER_ROLE, manager)
        .call()
        .await
        .unwrap();
    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            Identity::Address(fixture.user.address()),
            None,
            Some(UserDiscount {
                discount_bps: 5_000,
                scope: DiscountScope::FirstPremium,
            }),
        )
        .call()
        .await
        .unwrap();

    fixture.close_session().await;
    let entry = (TURBO_DEPOSIT + TURBO_FEE) / 2;
    start_turbo_session_paying(&fixture, entry).await;

    // Profit lands on the account as cash.
    let profit = 100_000u64;
    fixture
        .deployer
        .force_transfer_to_contract(
            fixture.child_id,
            profit,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();

    // ...and leaves again, in full: `from_pool` is zero, so only a floor
    // read off RAW collateral would refuse this.
    let wallet_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, profit)),
    );
    fixture
        .call_account(vec![withdraw], 2)
        .await
        .expect("a discounted session's profit is the user's to take");
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        wallet_before + u128::from(profit),
        "the whole profit reached the wallet"
    );

    // The TICKET stays where it is: one unit past the profit would have to
    // come from the pool leg, and a prepaid session's pool leg holds only
    // what a top-up added - here, nothing.
    let over = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, 1_000u64)),
    );
    let error = fixture.call_account(vec![over], 2).await.unwrap_err();
    assert!(
        error.to_string().contains("BelowTierCollateral"),
        "the discounted ticket is no more withdrawable than a full-price \
         one: {error:#}"
    );
}

/// A prepaid session that ends holding a POSITION still settles its ticket
/// to the platform in full, and keeps its winnings.
///
/// Such a session cannot close itself — `close_session` refuses an
/// outstanding draw, and it can neither pay the draw in cash (it spent the
/// cash on the position) nor net a ticket it never had. The deadline is how
/// it really ends, and the settlement has to unwind three things at once:
/// repay the pool, settle the ticket, and pay the gain out in kind.
///
/// The old model needed an in-kind forfeit leg for this shape - the ticket
/// sat in `collateral` and could be converted into a tier asset. It cannot
/// any more: the ticket is quote the POOL has held since the open, so the
/// residue is one cash transfer whatever the session holds at close.
#[tokio::test]
async fn a_prepaid_session_holding_a_position_forfeits_its_ticket_at_the_deadline() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;

    // Draw, and spend the draw on base at 2.0.
    let price = 2_000_000u64;
    let cost = 200_000u64;
    let quantity = cost * 1_000_000_000 / price;
    fixture
        .rest_order(price, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(price, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();

    // The position quadruples, and the draw is still owed.
    fixture
        .publish_base_price(8_000_000_000_000_000_000u128)
        .await;
    assert_eq!(
        fixture.session().await.drawn_quote,
        cost,
        "the draw cannot be cleared: no cash, and the ticket is not nettable"
    );

    let parent_base_before = fixture
        .user
        .get_asset_balance(&fixture.base_asset)
        .await
        .unwrap();
    advance_past_expiry(&fixture).await;
    let response = try_expire(&fixture).await.unwrap();

    // The whole ticket reaches the platform, in cash.
    let settled = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<TicketSettled>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(settled.len(), 1);
    assert_eq!(
        settled[0].to_platform, TURBO_DEPOSIT,
        "the entry is non-refundable however the session ends"
    );

    // ...and the gain goes home to the parent, in kind.
    let base_paid = fixture
        .user
        .get_asset_balance(&fixture.base_asset)
        .await
        .unwrap()
        - parent_base_before;
    assert!(
        base_paid > 0,
        "the winnings are the user's: {:?}",
        fixture.closed_event(&response)
    );
}

/// A FULLY forgiven prepaid entry still cannot be opened - but the boundary
/// has moved, and is now one guard wide.
///
/// The POOL no longer minds: every prepaid session opens on zero collateral,
/// so a zero-priced seat is just the ordinary open with a zero payment. What
/// refuses it is the ACCOUNT's own `start_session`, which will not forward a
/// zero amount (`AmountIsZero`) - and the pool then refuses any non-zero
/// payment because a prepaid entry must equal its price exactly
/// (`TurboEntryNotExact`). The grant succeeds and the user is locked out.
///
/// Pinned rather than fixed: lifting it is one `require` in the account
/// contract plus a product decision that a free prepaid seat exists. A 90%
/// grant - the deepest discount the suite exercises live - opens normally,
/// so the boundary is exactly at 100%.
#[tokio::test]
async fn a_fully_forgiven_prepaid_entry_cannot_be_opened() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;

    let manager = Identity::Address(fixture.deployer.address());
    fixture
        .deployment
        .pool
        .methods()
        .grant_role(DISCOUNT_MANAGER_ROLE, manager)
        .call()
        .await
        .unwrap();
    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            Identity::Address(fixture.user.address()),
            None,
            Some(UserDiscount {
                discount_bps: 10_000,
                scope: DiscountScope::FirstPremium,
            }),
        )
        .call()
        .await
        .expect("the pool admits a fully forgiven premium");
    fixture.close_session().await;

    // Paying the price — which is now zero — forwards nothing.
    let error = fixture
        .account
        .methods()
        .start_session(TURBO_TIER_ID, 0, ProlongPeriod::Week)
        .call_params(CallParameters::new(0, fixture.collateral_asset, u64::MAX))
        .unwrap()
        .with_contracts(&[
            &fixture.deployment.oracle,
            &fixture.deployment.pool,
            &fixture.deployment.registry,
        ])
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("AmountIsZero"),
        "a zero entry forwards no coins at all: {error:#}"
    );

    // ...and paying anything else is not the price.
    let error = fixture
        .account
        .methods()
        .start_session(TURBO_TIER_ID, 1, ProlongPeriod::Week)
        .call_params(CallParameters::new(1, fixture.collateral_asset, u64::MAX))
        .unwrap()
        .with_contracts(&[
            &fixture.deployment.oracle,
            &fixture.deployment.pool,
            &fixture.deployment.registry,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("TurboEntryNotExact"),
        "a prepaid entry must equal its price exactly: {error:#}"
    );
}

/// The COLLATERAL WALK, on a discounted session.
///
/// `draw -> repay_from_collateral -> withdraw` was the shape that once made
/// a non-refundable entry refundable: net the funded deposit onto the
/// account, then drain it through the account leg. A discounted session was
/// the hardest case, because the subsidy arithmetic gave the guard two
/// numbers to disagree about. There is nothing to disagree about now - the
/// ticket never enters `collateral`, so the netting finds a zero ledger and
/// refuses on plain arithmetic, at any discount.
#[tokio::test]
async fn a_discounted_session_cannot_walk_its_ticket_out_through_the_netting() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;

    let manager = Identity::Address(fixture.deployer.address());
    fixture
        .deployment
        .pool
        .methods()
        .grant_role(DISCOUNT_MANAGER_ROLE, manager)
        .call()
        .await
        .unwrap();
    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            Identity::Address(fixture.user.address()),
            None,
            Some(UserDiscount {
                discount_bps: 5_000,
                scope: DiscountScope::FirstPremium,
            }),
        )
        .call()
        .await
        .unwrap();
    fixture.close_session().await;
    let entry = (TURBO_DEPOSIT + TURBO_FEE) / 2;
    let opened = start_turbo_session_paying(&fixture, entry).await;
    assert_eq!(
        opened.credit_line, TURBO_LINE,
        "a discounted ticket still buys the whole line"
    );

    // Draw the deposit and try to net it back against funded collateral. The
    // walk never gets as far as the withdrawal: a prepaid session may net only
    // what it ADDED, and this one has added nothing.
    let deposit_paid = TURBO_DEPOSIT / 2;
    let draw = fixture.draw_call(deposit_paid);
    fixture.call_account(vec![draw], 1).await.unwrap();
    let repay = fixture.repay_from_collateral_call(deposit_paid);
    let error = fixture.call_account(vec![repay], 0).await.unwrap_err();
    let refusal = format!("{error:?}");
    assert!(
        refusal.contains("INSUFFICIENT_BALANCE")
            || refusal.contains("InsufficientBalance"),
        "there is no collateral to net at any discount: {refusal}"
    );

    // The ledger is untouched, and the draw is still outstanding — the user
    // repays it with his own coins or carries it to settlement.
    let session = fixture.session().await;
    assert_eq!(session.collateral, 0, "the refused netting moved nothing");
    assert_eq!(session.drawn_quote, deposit_paid);
}

/// EVERY discount rate opens the same session: zero collateral, the whole
/// line, and the ticket out of reach because it is not in the ledger at
/// all. There is no subsidy arithmetic left to get wrong - the sweep now
/// proves the ABSENCE of rate-dependence rather than a delicate identity.
#[tokio::test]
async fn every_discount_rate_opens_exactly_on_the_floor_with_the_whole_line() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;

    let manager = Identity::Address(fixture.deployer.address());
    fixture
        .deployment
        .pool
        .methods()
        .grant_role(DISCOUNT_MANAGER_ROLE, manager)
        .call()
        .await
        .unwrap();
    // The fixture opens on its legacy session; the sweep needs the account
    // free before the first pass.
    fixture.close_session().await;

    // 0% (the control), 20%, 50%, 90% — and 99%, a rate whose deposit rounds
    // to a handful of units.
    for discount_bps in [0u64, 2_000, 5_000, 9_000, 9_900] {
        fixture
            .deployment
            .pool
            .methods()
            .set_user_discount(
                Identity::Address(fixture.user.address()),
                None,
                Some(UserDiscount {
                    discount_bps,
                    scope: DiscountScope::AllPremiums,
                }),
            )
            .call()
            .await
            .unwrap();

        let rate = 10_000 - discount_bps;
        let deposit = TURBO_DEPOSIT * rate / 10_000;
        let fee = TURBO_FEE * rate / 10_000;
        let opened = start_turbo_session_paying(&fixture, deposit + fee).await;

        assert_eq!(
            opened.credit_line, TURBO_LINE,
            "{discount_bps} bps off must still buy the tier's whole line"
        );
        assert_eq!(
            opened.collateral, 0,
            "{discount_bps} bps: the purchase posts nothing at any rate"
        );

        // Not a unit may leave a ledger that holds nothing...
        let over = fixture.pool_call(
            fn_selector!(withdraw(AssetId, u64)),
            0,
            AssetId::default(),
            Some(call_data!(fixture.collateral_asset, 1u64)),
        );
        let error = fixture.call_account(vec![over], 2).await.unwrap_err();
        let refusal = format!("{error:?}");
        assert!(
            refusal.contains("BELOW_TIER_COLLATERAL")
                || refusal.contains("BelowTierCollateral")
                || refusal.contains("InsufficientBalance"),
            "{discount_bps} bps: the ticket must be stuck: {refusal}"
        );

        // ...and profit sitting on the account leaves in full.
        let profit = 50_000u64;
        fixture
            .deployer
            .force_transfer_to_contract(
                fixture.child_id,
                profit,
                fixture.collateral_asset,
                TxPolicies::default(),
            )
            .await
            .unwrap();
        let take = fixture.pool_call(
            fn_selector!(withdraw(AssetId, u64)),
            0,
            AssetId::default(),
            Some(call_data!(fixture.collateral_asset, profit)),
        );
        fixture
            .call_account(vec![take], 2)
            .await
            .unwrap_or_else(|error| {
                panic!("{discount_bps} bps: profit must be withdrawable: {error:#}")
            });

        fixture.close_session().await;
    }
}