o2-tools 0.3.21-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
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
//! Integration coverage for prop deployment and cross-contract invariants.

use super::*;

/// Submission-age bound the harness runs the feed at: wide enough that a
/// test may publish at any timestamp it likes and still exercise the POOL's
/// own staleness rules rather than the feed's.
const TEST_MAX_OFFCHAIN_AGE_SECONDS: u64 = 10_000_000_000;

/// How far behind the chain the harness's publish clock starts. Far enough
/// that thousands of publishes stay in the past, small enough to sit well
/// inside [`TEST_MAX_OFFCHAIN_AGE_SECONDS`].
const PUBLISH_CLOCK_LAG_SECONDS: u64 = 1_000_000;
use crate::{
    call_data,
    fn_selector,
    order_book_deploy::{
        OrderArgs,
        OrderBookConfigurables,
        OrderBookDeploy,
        OrderBookDeployConfig,
        OrderType,
    },
    parallel_nonce::{
        build_parallel_nonce,
        generate_parallel_session_signing_payload,
    },
    prop::{
        BaseDebtRepaidFromCollateral,
        CallContractArg,
        CallParams,
        DiscountScope,
        MarginContractCallEvent,
        MarginPoolLiquidatorChanged,
        MarginWithdrawn,
        ParallelMultiCallContractArgs,
        ParallelSessionArgs,
        PriceInput,
        ProlongPeriod,
        ProlongTrigger,
        PropAccountContract,
        PropAccountOracleProxyContract,
        PropAccountProxyContract,
        QuoteRepaidFromCollateral,
        Secp256k1,
        SessionClosed,
        SessionOpened,
        SessionProlonged,
        SessionSeized,
        SettlementReason,
        Signature,
        State,
        TierParams,
        TierVersionPublished,
        Time,
        UserDiscount,
        UserDiscountChanged,
        UserDiscountsRemoved,
    },
    trial_trade_account::generate_trial_trade_approval_signing_payload,
};
use fuels::{
    programs::responses::CallResponse,
    test_helpers::{
        AssetConfig,
        ChainConfig,
        DbType,
        NodeConfig,
        WalletsConfig,
        launch_custom_provider_and_get_wallets,
    },
    types::U256,
};
use futures::TryStreamExt;
use std::time::{
    SystemTime,
    UNIX_EPOCH,
};

const TIER_ID: u64 = 1;
/// Mirrors the pool's `DISCOUNT_MANAGER_ROLE` constant - the one role
/// `set_user_discount` accepts.
const DISCOUNT_MANAGER_ROLE: u64 = 1;
const COLLATERAL: u64 = 2_000_000;
const LINE: u64 = 10_000_000;

struct PropFixture {
    _node_db: Option<tempfile::TempDir>,
    collateral_asset: AssetId,
    base_asset: AssetId,
    deployer: Wallet,
    user: Wallet,
    outsider: Wallet,
    deployment: PropDeployment<Wallet>,
    order_book: OrderBookDeploy<Wallet>,
    child_id: ContractId,
    account: PropAccountContract<Wallet>,
    nonce_position: u8,
    /// Strictly increasing source of `publish_time`s. The production feed
    /// refuses a timestamp in the future or at/below an asset's replay
    /// floor, so the harness runs a deterministic clock seeded WELL behind
    /// the chain: every publish is newer than the last and still comfortably
    /// in the past. The tier's `max_price_age` is `u64::MAX`, so how far
    /// behind it sits never reaches the pool's own staleness rule.
    publish_clock: std::sync::atomic::AtomicU64,
}

impl PropFixture {
    async fn new() -> Self {
        Self::new_with_node_config(None, None).await
    }

    async fn new_with_historical_storage() -> Self {
        let node_db = tempfile::tempdir().unwrap();
        let database_type = DbType::RocksDb(Some(node_db.path().to_path_buf()));
        Self::new_with_node_config(
            Some(NodeConfig {
                database_type,
                historical_execution: true,
                ..NodeConfig::default()
            }),
            Some(node_db),
        )
        .await
    }

    async fn new_with_node_config(
        node_config: Option<NodeConfig>,
        node_db: Option<tempfile::TempDir>,
    ) -> Self {
        let collateral_asset = AssetId::new([0x31; 32]);
        let base_asset = AssetId::new([0x32; 32]);
        let initial_balance = 100_000_000_000u64;
        let mut wallets = launch_custom_provider_and_get_wallets(
            WalletsConfig::new_multiple_assets(
                3,
                vec![
                    AssetConfig {
                        id: AssetId::default(),
                        num_coins: 4,
                        coin_amount: initial_balance,
                    },
                    AssetConfig {
                        id: collateral_asset,
                        num_coins: 4,
                        coin_amount: initial_balance,
                    },
                    AssetConfig {
                        id: base_asset,
                        num_coins: 4,
                        coin_amount: initial_balance,
                    },
                ],
            ),
            node_config,
            Some(ChainConfig::local_testnet()),
        )
        .await
        .unwrap();
        let outsider = wallets.pop().unwrap();
        let user = wallets.pop().unwrap();
        let deployer = wallets.pop().unwrap();

        // These tests publish at fixed timestamps (0, 1, hand-rolled
        // staleness) to drive the pool's OWN price rules, so the feed's
        // submission-age bound is opened wide rather than worked around.
        let mut config = PropDeployConfig::new(collateral_asset);
        config.max_offchain_age_seconds = Some(TEST_MAX_OFFCHAIN_AGE_SECONDS);
        let deployment = PropDeployment::deploy(&deployer, &config).await.unwrap();

        let order_book_configurables = OrderBookConfigurables::default()
            .with_MAKER_FEE(0u64.into())
            .unwrap()
            .with_TAKER_FEE(0u64.into())
            .unwrap()
            .with_MIN_ORDER(1)
            .unwrap()
            .with_DUST(0)
            .unwrap();
        let order_book = OrderBookDeploy::deploy(
            &deployer,
            base_asset,
            collateral_asset,
            &OrderBookDeployConfig::with_configurables(order_book_configurables),
        )
        .await
        .unwrap();

        deployment
            .price_feed
            .methods()
            .set_asset_decimals(collateral_asset, 6)
            .call()
            .await
            .unwrap();
        deployment
            .price_feed
            .methods()
            .set_asset_decimals(base_asset, 9)
            .call()
            .await
            .unwrap();
        let chain_now = deployer
            .try_provider()
            .unwrap()
            .latest_block_time()
            .await
            .unwrap()
            .map(|time| time.timestamp() as u64)
            .unwrap_or(0);
        let publish_clock =
            std::sync::atomic::AtomicU64::new(chain_now - PUBLISH_CLOCK_LAG_SECONDS);
        let first_publish =
            publish_clock.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
        deployment
            .price_feed
            .methods()
            .publish_prices(vec![
                PriceInput {
                    asset: collateral_asset,
                    bid: 1_000_000_000_000_000_000u64.into(),
                    ask: 1_000_000_000_000_000_000u64.into(),
                    timestamp: first_publish,
                },
                PriceInput {
                    asset: base_asset,
                    bid: 2_000_000_000_000_000_000u64.into(),
                    ask: 2_000_000_000_000_000_000u64.into(),
                    timestamp: first_publish,
                },
            ])
            .call()
            .await
            .unwrap();

        let tier_params = TierParams {
            line: LINE,
            leverage: 5,
            duration: 64_800,
            maintenance_bps: 250,
            open_buffer_bps: 375,
            liq_price_factor: 9_900,
            // Six hours is free, and it is the term every fixture session
            // opens on: `64_800 + 21_600` is the 86_400 these tests have
            // always run with, at the same zero entry cost. Prolonging is
            // priced, so the fee tests use Day.
            prolong_fee: [0, 6_000, 76_000, 738_000],
            max_credit_line_bps: 20_000,
            max_price_age: u64::MAX,
            open_fee: 0,
            profit_share_bps: 1_000,
            price_band_bps: 1_000,
        };
        let tier_response = deployment
            .pool
            .methods()
            .publish_tier_version(
                TIER_ID,
                tier_params.clone(),
                vec![order_book.contract_id],
            )
            .with_contract_ids(&[order_book.contract_id, deployment.price_feed_id])
            .call()
            .await
            .unwrap();
        let tier_events = tier_response
            .decode_logs_with_type::<TierVersionPublished>()
            .unwrap();
        assert_eq!(tier_events.len(), 1);
        assert_eq!(tier_events[0].params, tier_params);
        assert_eq!(tier_events[0].threshold_floor, 8_250_000);
        // The pool-wide base-repay fee rides along on every tier version, so a
        // consumer reading only these events can price the conversion the
        // tier's own assets are closed at. Asserted against the DEPLOY config
        // rather than a literal: the whole point is that the event reports the
        // configurable this pool was actually built with.
        assert_eq!(tier_events[0].base_repay_fee_ppm, config.base_repay_fee_ppm);
        assert_eq!(
            tier_events[0].auto_prolong_periods,
            vec![ProlongPeriod::SixHours, ProlongPeriod::Day]
        );
        assert!(tier_events[0].timestamp.unix != 0);

        for (asset, amount) in
            [(collateral_asset, 50_000_000), (base_asset, 10_000_000_000)]
        {
            deployer
                .force_transfer_to_contract(
                    deployment.pool.contract_id(),
                    amount,
                    asset,
                    TxPolicies::default(),
                )
                .await
                .unwrap();
        }

        let parent = Identity::Address(user.address());
        let child = deployment.deploy_account(&user, parent, 0).await.unwrap();
        let child_id = child.contract_id();
        let account = PropAccountContract::new(child_id, user.clone());
        let opened_response = account
            .methods()
            .start_session(TIER_ID, COLLATERAL, ProlongPeriod::SixHours)
            .call_params(CallParameters::new(COLLATERAL, collateral_asset, u64::MAX))
            .unwrap()
            .with_contract_ids(&[
                deployment.oracle_id,
                deployment.pool_id,
                deployment.registry_id,
            ])
            .call()
            .await
            .unwrap();
        let opened_events = deployment
            .pool
            .log_decoder()
            .decode_logs_with_type::<SessionOpened>(&opened_response.tx_status.receipts)
            .unwrap();
        assert_eq!(opened_events.len(), 1);
        assert_eq!(opened_events[0].account, child_id);
        assert_eq!(opened_events[0].parent, parent);
        assert_eq!(
            opened_events[0].expires_at,
            opened_events[0].started_at + 86_400
        );
        assert_eq!(opened_events[0].open_fee, 0);
        assert_eq!(opened_events[0].fees_accrued, 0);
        assert!(opened_events[0].timestamp.unix != 0);

        let expiry = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 86_400;
        account
            .methods()
            .set_session(ParallelSessionArgs {
                nonce: U256::zero(),
                session_id: Identity::Address(user.address()),
                expiry: Time { unix: expiry },
                contract_ids: vec![],
            })
            .with_contract_ids(&[deployment.oracle_id])
            .call()
            .await
            .unwrap();

        Self {
            _node_db: node_db,
            collateral_asset,
            base_asset,
            deployer,
            user,
            outsider,
            deployment,
            order_book,
            child_id,
            account,
            nonce_position: 0,
            publish_clock,
        }
    }

    fn pool_call(
        &self,
        function_selector: Vec<u8>,
        coins: u64,
        asset_id: AssetId,
        call_data: Option<Vec<u8>>,
    ) -> CallContractArg {
        CallContractArg {
            contract_id: self.deployment.pool_id,
            function_selector: Bytes(function_selector),
            call_params: CallParams {
                coins,
                asset_id,
                gas: 10_000_000,
            },
            call_data: call_data.map(Bytes),
        }
    }

    async fn signed_calls(
        &mut self,
        call_contract_args: Vec<CallContractArg>,
    ) -> (Signature, Signature, ParallelMultiCallContractArgs) {
        // Chain time, not wall clock: tests that push the node's clock forward
        // would otherwise sign a nonce that is already expired on arrival.
        let wall_clock = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let chain = self
            .user
            .try_provider()
            .unwrap()
            .latest_block_time()
            .await
            .unwrap()
            .map(|time| time.timestamp() as u64)
            .unwrap_or(0);
        let now = wall_clock.max(chain);
        let nonce = build_parallel_nonce(0, now + 3_600, 0, self.nonce_position);
        self.nonce_position += 1;
        let calls = ParallelMultiCallContractArgs {
            nonce,
            call_contract_args,
        };
        let user_message = generate_parallel_session_signing_payload(
            calls.nonce,
            calls.call_contract_args.clone(),
        );
        let chain_id = self
            .user
            .provider()
            .consensus_parameters()
            .await
            .unwrap()
            .chain_id();
        let cosigner_message = generate_trial_trade_approval_signing_payload(
            *chain_id,
            self.child_id,
            calls.nonce,
            calls.call_contract_args.clone(),
        );
        let user_signature = self.user.signer().sign(user_message).await.unwrap();
        let cosigner_signature =
            self.deployer.signer().sign(cosigner_message).await.unwrap();

        (
            Signature::Secp256k1(Secp256k1 {
                bits: *user_signature,
            }),
            Signature::Secp256k1(Secp256k1 {
                bits: *cosigner_signature,
            }),
            calls,
        )
    }

    async fn call_account(
        &mut self,
        calls: Vec<CallContractArg>,
        variable_outputs: usize,
    ) -> Result<CallResponse<()>> {
        let (user_signature, cosigner_signature, calls) = self.signed_calls(calls).await;
        Ok(self
            .account
            .methods()
            .call_contracts(user_signature, cosigner_signature, calls)
            .with_contracts(&[
                &self.deployment.oracle,
                &self.deployment.pool,
                &self.deployment.price_feed,
                &self.deployment.registry,
                &self.order_book.order_book,
            ])
            .with_variable_output_policy(VariableOutputPolicy::Exactly(variable_outputs))
            .call()
            .await?)
    }

    async fn session(&self) -> crate::prop::SessionView {
        self.deployment
            .pool
            .methods()
            .get_session(self.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .unwrap()
    }

    async fn pool_balance(&self, asset: AssetId) -> u64 {
        self.deployer
            .try_provider()
            .unwrap()
            .get_contract_asset_balance(&self.deployment.pool_id, &asset)
            .await
            .unwrap()
    }

    async fn account_balance(&self, asset: AssetId) -> u64 {
        self.deployer
            .try_provider()
            .unwrap()
            .get_contract_asset_balance(&self.child_id, &asset)
            .await
            .unwrap()
    }

    async fn lines(&self) -> crate::prop::SessionLines {
        self.deployment
            .pool
            .methods()
            .get_session_lines(self.child_id)
            .with_contract_ids(&[
                self.child_id,
                self.order_book.contract_id,
                self.deployment.price_feed_id,
            ])
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    }

    /// The signed session value the two legs encode:
    /// `V = k + collateral - fees + holdings - debts - drawn_quote`.
    async fn session_value(&self) -> i128 {
        let lines = self.lines().await;
        i128::try_from(lines.positive.as_u128()).unwrap()
            - i128::try_from(lines.negative.as_u128()).unwrap()
    }

    /// The next `publish_time` from the harness's monotonic clock.
    fn next_publish_time(&self) -> u64 {
        self.publish_clock
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
            + 1
    }

    async fn publish_base_price(&self, price: u128) {
        self.deployment
            .price_feed
            .methods()
            .publish_prices(vec![PriceInput {
                asset: self.base_asset,
                bid: price,
                ask: price,
                timestamp: self.next_publish_time(),
            }])
            .call()
            .await
            .unwrap();
    }

    /// Rests an order for the deployer, the counterparty the account trades
    /// against. The asset sent with the call decides the side.
    async fn rest_order(&self, price: u64, quantity: u64, asset: AssetId, coins: u64) {
        self.order_book
            .order_book
            .methods()
            .create_order(OrderArgs {
                price,
                quantity,
                order_type: OrderType::Spot,
            })
            .call_params(CallParameters::new(coins, asset, u64::MAX))
            .unwrap()
            .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
            .call()
            .await
            .unwrap();
    }

    fn book_call(
        &self,
        price: u64,
        quantity: u64,
        asset: AssetId,
        coins: u64,
    ) -> CallContractArg {
        CallContractArg {
            contract_id: self.order_book.contract_id,
            function_selector: Bytes(fn_selector!(create_order(OrderArgs))),
            call_params: CallParams {
                coins,
                asset_id: asset,
                gas: 10_000_000,
            },
            call_data: Some(Bytes(call_data!(OrderArgs {
                price,
                quantity,
                order_type: OrderType::Spot,
            }))),
        }
    }

    fn settle_book_call(&self) -> CallContractArg {
        CallContractArg {
            contract_id: self.order_book.contract_id,
            function_selector: Bytes(fn_selector!(settle_balance(Identity))),
            call_params: CallParams {
                coins: 0,
                asset_id: AssetId::default(),
                gas: 10_000_000,
            },
            call_data: Some(Bytes(call_data!(Identity::ContractId(self.child_id)))),
        }
    }

    fn draw_call(&self, amount: u64) -> CallContractArg {
        self.pool_call(
            fn_selector!(draw(u64)),
            0,
            AssetId::default(),
            Some(call_data!(amount)),
        )
    }

    fn prolong_call(&self, times: u64) -> CallContractArg {
        self.pool_call(
            fn_selector!(prolong_session(ProlongPeriod, u64)),
            0,
            AssetId::default(),
            Some(call_data!(ProlongPeriod::Day, times)),
        )
    }

    fn repay_base_from_collateral_call(
        &self,
        asset: AssetId,
        amount: u64,
    ) -> CallContractArg {
        self.pool_call(
            fn_selector!(repay_base_from_collateral(AssetId, u64)),
            0,
            AssetId::default(),
            Some(call_data!(asset, amount)),
        )
    }

    fn repay_from_collateral_call(&self, amount: u64) -> CallContractArg {
        self.pool_call(
            fn_selector!(repay_from_collateral(u64)),
            0,
            AssetId::default(),
            Some(call_data!(amount)),
        )
    }

    /// The same signed-call path with a caller-chosen contract-input set, so a
    /// test can prove what a call does NOT need in its transaction. Anything a
    /// call touches and the list omits reverts the whole thing.
    async fn call_account_with_contract_ids(
        &mut self,
        calls: Vec<CallContractArg>,
        contract_ids: &[ContractId],
    ) -> Result<CallResponse<()>> {
        let (user_signature, cosigner_signature, calls) = self.signed_calls(calls).await;
        Ok(self
            .account
            .methods()
            .call_contracts(user_signature, cosigner_signature, calls)
            .with_contract_ids(contract_ids)
            .with_variable_output_policy(VariableOutputPolicy::Exactly(0))
            .call()
            .await?)
    }

    async fn debt(&self, asset: AssetId) -> u64 {
        self.deployment
            .pool
            .methods()
            .get_debt(self.child_id, asset)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    }

    /// An OUTSIDE funder topping the session up. It holds no session of its
    /// own, so none of the self-funding restrictions apply to it and the
    /// collateral it posts is not share-bearing.
    async fn fund_collateral(&self, amount: u64) {
        self.deployment
            .pool
            .clone()
            .with_account(self.outsider.clone())
            .methods()
            .add_collateral(self.child_id)
            .call_params(CallParameters::new(amount, self.collateral_asset, u64::MAX))
            .unwrap()
            .call()
            .await
            .unwrap();
    }

    async fn bad_debt(&self) -> u64 {
        self.deployment
            .pool
            .methods()
            .get_bad_debt()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    }

    async fn is_liquidatable(&self) -> bool {
        let lines = self.lines().await;
        lines.positive <= lines.negative + lines.threshold
    }

    /// The keeper's forced exit, from a wallet with no claim on the session.
    async fn liquidate(&self) -> CallResponse<()> {
        self.deployment
            .pool
            .clone()
            .with_account(self.outsider.clone())
            .methods()
            .liquidate(self.child_id, vec![])
            .with_contracts(&[
                &self.account,
                &self.deployment.oracle,
                &self.order_book.order_book,
                &self.deployment.price_feed,
            ])
            .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
            .call()
            .await
            .unwrap()
    }

    async fn close_session(&self) -> CallResponse<()> {
        self.account
            .methods()
            .close_session(vec![])
            .with_contracts(&[
                &self.deployment.pool,
                &self.deployment.oracle,
                &self.order_book.order_book,
                &self.deployment.price_feed,
            ])
            .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
            .call()
            .await
            .unwrap()
    }

    fn closed_event(&self, response: &CallResponse<()>) -> SessionClosed {
        let closed = self
            .deployment
            .pool
            .log_decoder()
            .decode_logs_with_type::<SessionClosed>(&response.tx_status.receipts)
            .unwrap();
        assert_eq!(closed.len(), 1);
        closed.into_iter().next().unwrap()
    }
}

async fn expire_fixture_session(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_until_expired =
        session.expires_at.saturating_sub(latest.timestamp() as u64) + 1;
    let expired_time = latest
        .checked_add_signed(chrono::TimeDelta::seconds(seconds_until_expired as i64))
        .expect("test expiry timestamp is representable");
    provider
        .produce_blocks(1, Some(expired_time))
        .await
        .unwrap();

    fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .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
        .unwrap();
}

async fn occupied_pool_storage_slots(fixture: &PropFixture) -> usize {
    fixture
        .deployer
        .try_provider()
        .unwrap()
        .client()
        .contract_storage_slots(&fixture.deployment.pool_id)
        .await
        .unwrap()
        .try_collect::<Vec<_>>()
        .await
        .unwrap()
        .len()
}

#[test]
fn settlement_reason_wire_order_matches_backend_abi() {
    fn discriminant(reason: SettlementReason) -> u64 {
        match fuels::core::traits::Tokenizable::into_token(reason) {
            fuels::types::Token::Enum(selector) => selector.0,
            token => panic!("expected enum token, got {token:?}"),
        }
    }

    assert_eq!(discriminant(SettlementReason::UserClose), 0);
    assert_eq!(discriminant(SettlementReason::Expiry), 1);
    assert_eq!(discriminant(SettlementReason::Liquidation), 2);
}

#[tokio::test]
async fn admin_controls_the_liquidator() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let fixture = PropFixture::new().await;
    let deployer = Identity::Address(fixture.deployer.address());
    let liquidator = Identity::Address(fixture.outsider.address());

    assert_eq!(
        fixture
            .deployment
            .pool
            .methods()
            .liquidator()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        deployer
    );

    let outsider_pool = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone());
    assert!(
        outsider_pool
            .methods()
            .set_liquidator(liquidator)
            .call()
            .await
            .is_err()
    );
    for invalid in [
        Identity::Address(Address::zeroed()),
        Identity::ContractId(ContractId::zeroed()),
    ] {
        assert!(
            fixture
                .deployment
                .pool
                .methods()
                .set_liquidator(invalid)
                .call()
                .await
                .is_err()
        );
    }

    let response = fixture
        .deployment
        .pool
        .methods()
        .set_liquidator(liquidator)
        .call()
        .await
        .unwrap();
    let events = response
        .decode_logs_with_type::<MarginPoolLiquidatorChanged>()
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].old_liquidator, deployer);
    assert_eq!(events[0].new_liquidator, liquidator);
    assert!(events[0].timestamp.unix != 0);
    assert_eq!(
        fixture
            .deployment
            .pool
            .methods()
            .liquidator()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        liquidator
    );
}

#[tokio::test]
async fn live_withdrawal_emits_canonical_event() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;
    let amount = 100_000;

    fixture
        .user
        .force_transfer_to_contract(
            fixture.child_id,
            amount,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, amount)),
    );
    let response = fixture.call_account(vec![withdraw], 2).await.unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<MarginWithdrawn>(&response.tx_status.receipts)
        .unwrap();

    assert_eq!(events.len(), 1);
    assert_eq!(events[0].account, fixture.child_id);
    assert_eq!(events[0].session_id, 1);
    assert_eq!(events[0].asset_id, fixture.collateral_asset);
    assert_eq!(events[0].amount, amount);
    assert_eq!(events[0].from_account, amount);
    assert_eq!(events[0].from_pool, 0);
    assert_eq!(events[0].from_capitalised, 0);
    assert_eq!(events[0].share_qty, 10_000);
    assert_eq!(events[0].new_collateral, COLLATERAL);
    assert_eq!(events[0].new_credit_line, LINE);
    assert_eq!(events[0].capitalised_total, 0);
    assert!(events[0].timestamp.unix != 0);
}

#[tokio::test]
async fn outside_funders_can_rescue_debt_but_self_funding_still_requires_a_clean_slate() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let lines = fixture
        .deployment
        .pool
        .methods()
        .get_session_lines(fixture.child_id)
        .with_contract_ids(&[
            fixture.child_id,
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert_eq!(lines.positive, U256::from(LINE));
    assert_eq!(lines.negative, U256::zero());
    assert_eq!(lines.threshold, U256::from(8_250_000u64));
    assert_eq!(lines.freeze, U256::from(8_375_000u64));

    let liquidation_error = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .liquidate(fixture.child_id, vec![])
        .with_contracts(&[
            &fixture.account,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .call()
        .await
        .unwrap_err();
    assert!(
        liquidation_error.to_string().contains("NotLiquidatable"),
        "permissionless liquidation should reach the objective health gate: {liquidation_error:#}"
    );

    let draw_amount = 1_000_000;
    let draw = fixture.pool_call(
        fn_selector!(draw(u64)),
        0,
        AssetId::default(),
        Some(call_data!(draw_amount)),
    );
    fixture.call_account(vec![draw], 1).await.unwrap();

    let rescue_amount = 500_000;
    fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .add_collateral(fixture.child_id)
        .call_params(CallParameters::new(
            rescue_amount,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .call()
        .await
        .unwrap();
    let rescued = fixture.session().await;
    assert_eq!(rescued.drawn_quote, draw_amount);
    assert_eq!(rescued.collateral, COLLATERAL + rescue_amount);
    assert_eq!(rescued.credit_line, LINE + rescue_amount);
    assert_eq!(rescued.capitalised, 0);

    let self_amount = 100_000;
    fixture
        .user
        .force_transfer_to_contract(
            fixture.child_id,
            self_amount,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
    let self_top_up = fixture.pool_call(
        fn_selector!(add_collateral(ContractId)),
        self_amount,
        fixture.collateral_asset,
        Some(call_data!(fixture.child_id)),
    );
    let error = fixture
        .call_account(vec![self_top_up], 0)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("QuoteOutstanding"),
        "unexpected self-funding error: {error:#}"
    );

    let return_quote = fixture.pool_call(
        fn_selector!(return_quote()),
        draw_amount,
        fixture.collateral_asset,
        None,
    );
    fixture.call_account(vec![return_quote], 0).await.unwrap();
    let self_top_up = fixture.pool_call(
        fn_selector!(add_collateral(ContractId)),
        self_amount,
        fixture.collateral_asset,
        Some(call_data!(fixture.child_id)),
    );
    fixture.call_account(vec![self_top_up], 0).await.unwrap();
    let capitalised = fixture.session().await;
    assert_eq!(capitalised.drawn_quote, 0);
    assert_eq!(capitalised.capitalised, self_amount);

    let borrow_amount = 1_000_000_000u64;
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, borrow_amount)),
    );
    fixture.call_account(vec![borrow], 1).await.unwrap();

    fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .add_collateral(fixture.child_id)
        .call_params(CallParameters::new(
            rescue_amount,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .call()
        .await
        .unwrap();
    let rescued_debt = fixture.session().await;
    assert_eq!(rescued_debt.capitalised, self_amount);

    fixture
        .user
        .force_transfer_to_contract(
            fixture.child_id,
            self_amount,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
    let self_top_up = fixture.pool_call(
        fn_selector!(add_collateral(ContractId)),
        self_amount,
        fixture.collateral_asset,
        Some(call_data!(fixture.child_id)),
    );
    let error = fixture
        .call_account(vec![self_top_up], 0)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("DebtsOutstanding"),
        "unexpected self-funding error: {error:#}"
    );

    assert_oracle_proxy_is_upgradeable(&fixture).await;
    assert_new_pool_defaults_do_not_require_a_create_manifest(&fixture).await;
}

#[tokio::test]
async fn outsider_can_expire_an_elapsed_session() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let fixture = PropFixture::new().await;
    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_until_expired =
        session.expires_at.saturating_sub(latest.timestamp() as u64) + 1;
    let expired_time = latest
        .checked_add_signed(chrono::TimeDelta::seconds(seconds_until_expired as i64))
        .expect("test expiry timestamp is representable");
    provider
        .produce_blocks(1, Some(expired_time))
        .await
        .unwrap();

    let response = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .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::Exactly(1))
        .call()
        .await
        .unwrap();

    let events = response.decode_logs_with_type::<SessionClosed>().unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].reason, SettlementReason::Expiry);
    assert!(events[0].timestamp.unix > session.expires_at);
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
}

#[tokio::test]
async fn expiry_routes_in_kind_debt_repayment_to_the_liquidator() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;
    let liquidator = Identity::Address(fixture.outsider.address());
    fixture
        .deployment
        .pool
        .methods()
        .set_liquidator(liquidator)
        .call()
        .await
        .unwrap();

    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_debts(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );

    let borrowed = 1_000_000_000u64;
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, borrowed)),
    );
    fixture.call_account(vec![borrow], 1).await.unwrap();
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .has_debts(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
    assert_eq!(
        fixture
            .deployment
            .pool
            .methods()
            .get_debt(fixture.child_id, fixture.base_asset)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        borrowed
    );
    let pool_after_borrow = fixture.pool_balance(fixture.base_asset).await;
    let liquidator_before = fixture
        .outsider
        .get_asset_balance(&fixture.base_asset)
        .await
        .unwrap();

    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_until_expired =
        session.expires_at.saturating_sub(latest.timestamp() as u64) + 1;
    let expired_time = latest
        .checked_add_signed(chrono::TimeDelta::seconds(seconds_until_expired as i64))
        .expect("test expiry timestamp is representable");
    provider
        .produce_blocks(1, Some(expired_time))
        .await
        .unwrap();

    let response = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .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::Exactly(2))
        .call()
        .await
        .unwrap();

    let seized = response.decode_logs_with_type::<SessionSeized>().unwrap();
    assert_eq!(seized.len(), 1);
    assert_eq!(seized[0].account, fixture.child_id);
    assert_eq!(seized[0].session_id, session.session_id);
    assert_eq!(seized[0].reason, SettlementReason::Expiry);
    assert_eq!(seized[0].liquidator, liquidator);
    // The account was carrying its own cover: it owed the base and was still
    // holding every unit of it. All three vectors say so, and the debt line
    // survives BECAUSE it is gross.
    assert_eq!(seized[0].holdings, vec![(fixture.base_asset, borrowed)]);
    assert_eq!(seized[0].debt, vec![(fixture.base_asset, borrowed)]);
    assert_eq!(seized[0].transferred, vec![(fixture.base_asset, borrowed)]);
    // The netted view of that same pair, from the same call: the holding
    // cancels the debt and the close reports nothing owed. Not wrong - and no
    // use to a liquidator, which cannot tell this apart from a session that
    // never borrowed at all. The gross pair above is what tells it that the
    // asset it is being handed is the asset it owes, so it buys nothing.
    let closed = fixture.closed_event(&response);
    assert!(closed.cancelled_debt.is_empty());
    assert!(seized[0].timestamp.unix > session.expires_at);
    assert_eq!(
        fixture.pool_balance(fixture.base_asset).await,
        pool_after_borrow
    );
    assert_eq!(
        fixture
            .outsider
            .get_asset_balance(&fixture.base_asset)
            .await
            .unwrap(),
        liquidator_before + u128::from(borrowed)
    );
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
    assert_eq!(
        fixture
            .deployment
            .pool
            .methods()
            .get_debt(fixture.child_id, fixture.base_asset)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        0
    );
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_debts(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
}

#[tokio::test]
async fn settlement_clears_session_scoped_accounting_storage() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;

    let clean_fixture = PropFixture::new_with_historical_storage().await;
    expire_fixture_session(&clean_fixture).await;
    let clean_close_slots = occupied_pool_storage_slots(&clean_fixture).await;

    let mut debt_fixture = PropFixture::new_with_historical_storage().await;
    let borrowed = 1_000_000_000u64;
    let borrow = debt_fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(debt_fixture.base_asset, borrowed)),
    );
    debt_fixture.call_account(vec![borrow], 1).await.unwrap();
    expire_fixture_session(&debt_fixture).await;
    let debt_close_slots = occupied_pool_storage_slots(&debt_fixture).await;

    assert_eq!(
        debt_close_slots, clean_close_slots,
        "settlement left debt, debt-asset index, or received-asset storage behind",
    );

    let mut netted_fixture = PropFixture::new_with_historical_storage().await;
    let netted = 1_000_000u64;
    let draw = netted_fixture.draw_call(netted);
    netted_fixture.call_account(vec![draw], 1).await.unwrap();
    let repay = netted_fixture.repay_from_collateral_call(netted);
    netted_fixture.call_account(vec![repay], 0).await.unwrap();
    expire_fixture_session(&netted_fixture).await;

    assert_eq!(
        occupied_pool_storage_slots(&netted_fixture).await,
        clean_close_slots,
        "settlement left the session's `decapitalised` memo behind, where a \
         re-opened session could inherit it",
    );
}

#[tokio::test]
async fn liquidation_routes_the_basket_after_the_accounts_short_trade() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;
    let liquidator = Identity::Address(fixture.outsider.address());
    fixture
        .deployment
        .pool
        .methods()
        .set_liquidator(liquidator)
        .call()
        .await
        .unwrap();

    let quantity = 1_000_000_000u64;
    let sale_proceeds = 2_000_000u64;
    fixture
        .order_book
        .order_book
        .methods()
        .create_order(OrderArgs {
            price: sale_proceeds,
            quantity,
            order_type: OrderType::Spot,
        })
        .call_params(CallParameters::new(
            sale_proceeds,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap();

    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let sell = CallContractArg {
        contract_id: fixture.order_book.contract_id,
        function_selector: Bytes(fn_selector!(create_order(OrderArgs))),
        call_params: CallParams {
            coins: quantity,
            asset_id: fixture.base_asset,
            gas: 10_000_000,
        },
        call_data: Some(Bytes(call_data!(OrderArgs {
            price: sale_proceeds,
            quantity,
            order_type: OrderType::Spot,
        }))),
    };
    let settle_book = CallContractArg {
        contract_id: fixture.order_book.contract_id,
        function_selector: Bytes(fn_selector!(settle_balance(Identity))),
        call_params: CallParams {
            coins: 0,
            asset_id: AssetId::default(),
            gas: 10_000_000,
        },
        call_data: Some(Bytes(call_data!(Identity::ContractId(fixture.child_id,)))),
    };
    fixture
        .call_account(vec![borrow, sell, settle_book], 2)
        .await
        .unwrap();

    let adverse_price = 10_000_000_000_000_000_000u128;
    fixture
        .deployment
        .price_feed
        .methods()
        .publish_prices(vec![PriceInput {
            asset: fixture.base_asset,
            bid: adverse_price,
            ask: adverse_price,
            timestamp: fixture.next_publish_time(),
        }])
        .call()
        .await
        .unwrap();

    let lines = fixture
        .deployment
        .pool
        .methods()
        .get_session_lines(fixture.child_id)
        .with_contract_ids(&[
            fixture.child_id,
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert!(lines.positive <= lines.negative + lines.threshold);

    let pool_cash_before = fixture.pool_balance(fixture.collateral_asset).await;
    let liquidator_before = fixture
        .outsider
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let response = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .liquidate(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::Exactly(1))
        .call()
        .await
        .unwrap();

    let seized = response.decode_logs_with_type::<SessionSeized>().unwrap();
    let seized_cash = COLLATERAL + sale_proceeds;
    assert_eq!(seized.len(), 1);
    assert_eq!(seized[0].account, fixture.child_id);
    assert_eq!(seized[0].reason, SettlementReason::Liquidation);
    assert_eq!(seized[0].liquidator, liquidator);
    // The mirror of the expiry case: the account sold the base it borrowed, so
    // it holds none of the asset it owes. Nothing nets, and the debt line has to
    // be bought back with the cash it holds instead.
    assert_eq!(
        seized[0].holdings,
        vec![(fixture.collateral_asset, sale_proceeds)]
    );
    assert_eq!(seized[0].debt, vec![(fixture.base_asset, quantity)]);
    assert_eq!(
        seized[0].transferred,
        vec![(fixture.collateral_asset, seized_cash)]
    );
    // `transferred` exceeds `holdings` by the funded collateral, which the pool
    // held all along and released to the liquidator on the way out. No quote
    // debt line: this session never drew.
    assert_eq!(seized_cash - sale_proceeds, COLLATERAL);
    assert!(seized[0].timestamp.unix != 0);
    assert_eq!(
        fixture
            .outsider
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        liquidator_before + u128::from(seized_cash)
    );
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        pool_cash_before - COLLATERAL
    );

    let closed = response.decode_logs_with_type::<SessionClosed>().unwrap();
    assert_eq!(closed.len(), 1);
    assert_eq!(closed[0].reason, SettlementReason::Liquidation);
    assert!(closed[0].profit_is_negative);
    assert!(closed[0].bad_debt != 0);
    assert_eq!(
        closed[0].cancelled_debt,
        vec![(fixture.base_asset, quantity)]
    );
    assert!(closed[0].payout_parent.is_empty());
    assert!(closed[0].payout_platform.is_empty());
    assert_eq!(
        fixture
            .deployment
            .pool
            .methods()
            .get_bad_debt()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        closed[0].bad_debt
    );
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
}

/// A long that fell, taken by the keeper instead of netted away. He drew quote
/// and bought the base with it, so he owes the pool 2_000_000 of QUOTE and not
/// one unit of any borrowed asset - and the debt table only ever holds borrowed
/// assets, because `borrow` refuses COLLATERAL_ASSET and sends it through
/// `draw`. `SessionClosed.cancelled_debt` is therefore EMPTY here while the pool
/// is unmistakably owed money, which is the blind spot the quote line exists to
/// cover.
///
/// It is reported net of the collateral the pool keeps. The 2_000_000 of funded
/// collateral answers the draw inside the pool - unlike an asset debt, whose
/// covering coins ship out in the basket - so the raw draw would have the
/// liquidator redeposit money the pool already holds. What is genuinely still
/// owed is the 198_000 of residual value the pool credited the parent for a
/// position it then handed away, and that is the line this test pins: an order
/// of magnitude below the draw.
#[tokio::test]
async fn a_liquidated_draw_reports_the_quote_the_debt_table_cannot_hold() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;
    let liquidator = Identity::Address(fixture.outsider.address());
    fixture
        .deployment
        .pool
        .methods()
        .set_liquidator(liquidator)
        .call()
        .await
        .unwrap();

    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(cost, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(cost, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    assert_eq!(fixture.account_balance(fixture.base_asset).await, quantity);
    // Every unit of the draw is in the position. There is no cash anywhere to
    // sweep back at settlement, so `held_cash` will be zero.
    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);
    assert_eq!(fixture.session().await.drawn_quote, cost);

    // The base falls to a tenth: the position marks at 200_000 against a
    // 2_000_000 draw, which puts `V` at 8_200_000 and hands the session to the
    // keeper.
    fixture
        .publish_base_price(200_000_000_000_000_000u128)
        .await;
    assert_eq!(fixture.session_value().await, 8_200_000);
    assert!(
        fixture.is_liquidatable().await,
        "the session must be the keeper's for this test to mean anything"
    );

    let liquidator_before = fixture
        .outsider
        .get_asset_balance(&fixture.base_asset)
        .await
        .unwrap();
    let response = fixture.liquidate().await;
    let closed = fixture.closed_event(&response);
    let seized = response.decode_logs_with_type::<SessionSeized>().unwrap();
    assert_eq!(seized.len(), 1);
    assert_eq!(seized[0].account, fixture.child_id);
    assert_eq!(seized[0].session_id, closed.session_id);
    assert_eq!(seized[0].reason, SettlementReason::Liquidation);
    assert_eq!(seized[0].liquidator, liquidator);

    // Everything the account had was the position, and the whole of it goes to
    // the liquidator. No quote either way: the draw was spent, so there was none
    // left on the account to sweep and none left in the session to hand over.
    assert_eq!(seized[0].holdings, vec![(fixture.base_asset, quantity)]);
    assert_eq!(seized[0].transferred, vec![(fixture.base_asset, quantity)]);

    // 200_000 marked, less the 1% `liq_price_factor` haircut a forced exit
    // settles at: what the pool credited the parent for the position it then
    // gave away. Of the 2_000_000 draw, the other 1_802_000 of funded
    // collateral stays with the pool and answers it there - so THIS, not the
    // draw, is the quote debt line. Reporting the raw draw would have the
    // basket buy back ten times what the pool is actually short.
    let credited = 198_000u64;
    assert_eq!(seized[0].debt, vec![(fixture.collateral_asset, credited)]);
    // The point of the field, stated as the difference it makes: reading the
    // close event alone, a liquidator would see no debt at all here.
    assert!(closed.cancelled_debt.is_empty());
    assert_eq!(closed.user_net, credited);
    assert_eq!(
        closed.payout_parent,
        vec![(fixture.collateral_asset, credited)]
    );
    assert_eq!(closed.reason, SettlementReason::Liquidation);
    assert!(closed.profit_is_negative);
    // Funded collateral covered the loss in full, so nothing was written off -
    // the quote line above is a live claim on the basket, not bad debt.
    assert_eq!(closed.bad_debt, 0);
    assert_eq!(
        fixture
            .outsider
            .get_asset_balance(&fixture.base_asset)
            .await
            .unwrap(),
        liquidator_before + u128::from(quantity)
    );
}

/// Both debt legs at once, against a single holding - the shape a liquidator
/// actually has to reason about. He borrowed the base AND drew quote, spent the
/// draw on more of the base, and the base fell.
///
/// Two debts and one asset. The netted view collapses that to a third thing: the
/// base debt disappears into the holding it is covered by, the quote debt is not
/// in the debt table to begin with, and what is left describes neither leg. The
/// gross pair keeps them apart, which is the only form in which the decision
/// "sell this to buy that" can be made at all.
#[tokio::test]
async fn a_seized_session_reports_both_debt_legs_against_one_holding() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;
    let liquidator = Identity::Address(fixture.outsider.address());
    fixture
        .deployment
        .pool
        .methods()
        .set_liquidator(liquidator)
        .call()
        .await
        .unwrap();

    let bought = 1_000_000_000u64;
    let borrowed = 100_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(cost, bought, fixture.base_asset, bought)
        .await;

    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, borrowed)),
    );
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(cost, bought, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![borrow, draw, buy, fixture.settle_book_call()], 3)
        .await
        .unwrap();
    // One asset on the balance, carrying both the borrowed position and the one
    // the draw paid for. Not a unit of quote left anywhere.
    assert_eq!(
        fixture.account_balance(fixture.base_asset).await,
        borrowed + bought
    );
    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);
    assert_eq!(fixture.session().await.drawn_quote, cost);

    // The base falls to a tenth. The borrowed leg shrinks with it, so `V` lands
    // where the pure long landed: 8_200_000, and the keeper's.
    fixture
        .publish_base_price(200_000_000_000_000_000u128)
        .await;
    assert_eq!(fixture.session_value().await, 8_200_000);
    assert!(fixture.is_liquidatable().await);

    let response = fixture.liquidate().await;
    let closed = fixture.closed_event(&response);
    let seized = response.decode_logs_with_type::<SessionSeized>().unwrap();
    assert_eq!(seized.len(), 1);

    // Both debts, named and separate: the base the account borrowed, and the
    // quote left of its draw. The base line survives even though the account is
    // holding eleven times the asset to cover it - which is exactly what tells
    // the liquidator it can settle that leg out of the basket and buy nothing.
    // The quote line is NOT the 2_000_000 draw: the pool kept 1_802_000 of the
    // funded collateral against it and owes itself nothing for that part, so
    // the true shortfall is what it credited the parent for the seized
    // position - the same 198_000 the pure-long case pins.
    assert_eq!(
        seized[0].debt,
        vec![
            (fixture.base_asset, borrowed),
            (fixture.collateral_asset, 198_000),
        ]
    );
    // One holding, gross: the borrowed position and the bought one are the same
    // asset and arrive as one line.
    assert_eq!(
        seized[0].holdings,
        vec![(fixture.base_asset, borrowed + bought)]
    );
    assert_eq!(
        seized[0].transferred,
        vec![(fixture.base_asset, borrowed + bought)]
    );

    // What the same close looks like netted, and why it cannot be worked from:
    // the base debt has vanished into the holding, and the quote debt was never
    // representable here at all. Nothing owed, on an account that owed twice.
    assert!(closed.cancelled_debt.is_empty());
    assert_eq!(closed.reason, SettlementReason::Liquidation);
}

/// The tier shape the entry-term design exists for: NO base duration and NO
/// joining fee, four terms priced by their own `prolong_fee`. The opener picks
/// how long he wants, and that choice is the whole entry price - so one tier
/// sells four products.
#[tokio::test]
async fn a_zero_duration_tier_sells_its_term_at_the_door() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let fixture = PropFixture::new().await;

    const WEEK_FEE: u64 = 76_000;
    let tier_params = TierParams {
        line: LINE,
        leverage: 5,
        // The session lives exactly as long as the term it buys.
        duration: 0,
        maintenance_bps: 250,
        open_buffer_bps: 375,
        liq_price_factor: 9_900,
        prolong_fee: [6_000, 21_000, WEEK_FEE, 738_000],
        max_credit_line_bps: 20_000,
        max_price_age: u64::MAX,
        // No joining fee: the term IS the price.
        open_fee: 0,
        profit_share_bps: 1_000,
        price_band_bps: 1_000,
    };
    fixture
        .deployment
        .pool
        .methods()
        .publish_tier_version(TIER_ID, tier_params, vec![fixture.order_book.contract_id])
        .with_contract_ids(&[
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .call()
        .await
        .unwrap();

    let parent = Identity::Address(fixture.user.address());
    let child = fixture
        .deployment
        .deploy_account(&fixture.user, parent, 1)
        .await
        .unwrap();
    let account = PropAccountContract::new(child.contract_id(), fixture.user.clone());
    let platform_before = fixture
        .deployer
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();

    let opened_response = account
        .methods()
        .start_session(TIER_ID, COLLATERAL, ProlongPeriod::Week)
        .call_params(CallParameters::new(
            COLLATERAL,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .with_contract_ids(&[
            fixture.deployment.oracle_id,
            fixture.deployment.pool_id,
            fixture.deployment.registry_id,
        ])
        // The term is paid for at the door, so the coins leave in this call.
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap();
    let opened = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionOpened>(&opened_response.tx_status.receipts)
        .unwrap();

    assert_eq!(opened.len(), 1);
    // The whole entry price is the chosen term's fee, and it is already gone.
    assert_eq!(opened[0].open_fee, WEEK_FEE);
    assert_eq!(opened[0].fees_accrued, WEEK_FEE);
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        platform_before + u128::from(WEEK_FEE)
    );
    // A week and not a second more: with no base duration the term bought is
    // the entire life of the session.
    assert_eq!(
        opened[0].expires_at - opened[0].started_at,
        604_800,
        "a zero-duration tier must grant exactly the purchased term"
    );
    // Priced off the collateral NET of what it just paid, like any other fee:
    // `k` (8_000_000) plus 2_000_000 - 76_000.
    assert_eq!(opened[0].credit_line, 9_924_000);
}

#[tokio::test]
async fn prolongation_fee_can_move_a_session_through_its_health_lines() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;
    let before = fixture.session().await;
    let times = 300u64;
    let expected_fee = 1_800_000u64;
    // Day, because six hours is the free ENTRY term in this fixture and a
    // prolongation must be paid for.
    let expected_extension = 86_400u64 * times;
    let prolong = fixture.pool_call(
        fn_selector!(prolong_session(ProlongPeriod, u64)),
        0,
        AssetId::default(),
        Some(call_data!(ProlongPeriod::Day, times)),
    );

    // The fee leaves the pool inside this very call, so the transaction has to
    // carry a variable output for it - a prolongation is no longer a pure
    // ledger write.
    let platform_before = fixture
        .deployer
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let pool_before = fixture.pool_balance(fixture.collateral_asset).await;
    let response = fixture.call_account(vec![prolong], 1).await.unwrap();
    let events = response
        .decode_logs_with_type::<SessionProlonged>()
        .unwrap();
    let call_events = response
        .decode_logs_with_type::<MarginContractCallEvent>()
        .unwrap();
    assert_eq!(call_events.len(), 1);
    assert_eq!(
        call_events[0].authority,
        Identity::Address(fixture.user.address())
    );
    assert_eq!(call_events[0].called_contract, fixture.deployment.pool_id);
    assert!(call_events[0].timestamp.unix != 0);
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].period, ProlongPeriod::Day);
    assert_eq!(events[0].times, times);
    assert_eq!(events[0].seconds, expected_extension);
    assert_eq!(events[0].trigger, ProlongTrigger::User);
    assert_eq!(events[0].fee, expected_fee);
    // Charged AND paid in the same call, which is why one counter says both.
    assert_eq!(events[0].fees_accrued, expected_fee);

    // The money really moved: out of the pool, into the platform payout
    // identity, in the amount the event reported.
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        platform_before + u128::from(expected_fee)
    );
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        pool_before - expected_fee
    );

    let after = fixture.session().await;
    assert_eq!(after.expires_at, before.expires_at + expected_extension);
    // `collateral` stays GROSS and `fees_accrued` still counts the fee, which
    // is what keeps the line and both health lines exactly where they were
    // when the fee merely accrued. Only the coins moved.
    assert_eq!(after.fees_accrued, expected_fee);

    let lines = fixture
        .deployment
        .pool
        .methods()
        .get_session_lines(fixture.child_id)
        .with_contract_ids(&[
            fixture.child_id,
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert!(lines.positive <= lines.negative + lines.freeze);
    assert!(lines.positive <= lines.negative + lines.threshold);
}

/// The OTHER entry fee. Every other test in this file runs a tier with
/// `open_fee` at zero, so the opening payout has no coverage there - and it
/// is the one fee charged against collateral that arrives in the very same
/// call, which is why it can never fail for want of pool inventory.
///
/// Pins both halves. The coins reach the platform inside `start_session`, so
/// the opening transaction now needs a variable output it never needed before.
/// And the session the user is left holding is bit-for-bit the one the accrual
/// model gave him - same gross collateral, same `fees_accrued`, same line, same
/// value - because paying early moves coins, not value. At the close the
/// platform collects nothing further: it already has the fee, and the parent's
/// cheque plus that fee is exactly what he funded.
#[tokio::test]
async fn the_open_fee_reaches_the_platform_inside_the_opening_call() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let fixture = PropFixture::new().await;

    // 100 bps of the 10_000_000 line. New sessions pin the latest version, so
    // publishing one is enough - the fixture's own session keeps version 1.
    let open_fee = 100_000u64;
    let tier_params = TierParams {
        line: LINE,
        leverage: 5,
        duration: 86_400,
        maintenance_bps: 250,
        open_buffer_bps: 375,
        liq_price_factor: 9_900,
        // Six hours free, so the entry costs exactly `open_fee`.
        prolong_fee: [0, 21_000, 76_000, 738_000],
        max_credit_line_bps: 20_000,
        max_price_age: u64::MAX,
        // 100 bps of LINE, as an amount.
        open_fee,
        profit_share_bps: 1_000,
        price_band_bps: 1_000,
    };
    fixture
        .deployment
        .pool
        .methods()
        .publish_tier_version(TIER_ID, tier_params, vec![fixture.order_book.contract_id])
        .with_contract_ids(&[
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .call()
        .await
        .unwrap();

    let parent = Identity::Address(fixture.user.address());
    let child = fixture
        .deployment
        .deploy_account(&fixture.user, parent, 1)
        .await
        .unwrap();
    let child_id = child.contract_id();
    let account = PropAccountContract::new(child_id, fixture.user.clone());

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

    let opened_response = account
        .methods()
        .start_session(TIER_ID, COLLATERAL, ProlongPeriod::SixHours)
        .call_params(CallParameters::new(
            COLLATERAL,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .with_contract_ids(&[
            fixture.deployment.oracle_id,
            fixture.deployment.pool_id,
            fixture.deployment.registry_id,
        ])
        // The fee leaves in this call. Without the output the whole open
        // reverts, which is the deploy-side consequence of charging early.
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap();
    let opened = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionOpened>(&opened_response.tx_status.receipts)
        .unwrap();
    assert_eq!(opened.len(), 1);
    assert_eq!(opened[0].open_fee, open_fee);
    assert_eq!(opened[0].fees_accrued, open_fee);
    // Gross, exactly as it was posted: the fee is not deducted from the ledger,
    // only from the pool's balance.
    assert_eq!(opened[0].collateral, COLLATERAL);
    // `k` plus the collateral NET of the fee - the same line the accrual model
    // priced, because the line always read the net.
    assert_eq!(opened[0].credit_line, 9_900_000);

    // 2_000_000 in, 100_000 straight back out to the platform.
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        platform_before + u128::from(open_fee)
    );
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        pool_before + COLLATERAL - open_fee
    );

    // `V = k + collateral - fees` is untouched by the payout.
    let value = fixture
        .deployment
        .pool
        .methods()
        .get_session_lines(child_id)
        .with_contract_ids(&[
            child_id,
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert_eq!(value.positive - value.negative, U256::from(9_900_000u64));

    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let close_response = account
        .methods()
        .close_session(vec![])
        .with_contracts(&[
            &fixture.deployment.pool,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap();
    let closed = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionClosed>(&close_response.tx_status.receipts)
        .unwrap();
    assert_eq!(closed.len(), 1);
    let closed = &closed[0];

    // The closing claim is the profit share and nothing else. No profit here,
    // and the fee is long gone, so the close collects nothing at all.
    assert_eq!(closed.fees_accrued, open_fee);
    assert_eq!(closed.platform_total, 0);
    assert!(closed.payout_platform.is_empty());
    assert_eq!(closed.bad_debt, 0);
    assert_eq!(closed.user_net, COLLATERAL - open_fee);
    assert_eq!(
        closed.payout_parent,
        vec![(fixture.collateral_asset, COLLATERAL - open_fee)]
    );

    // Nothing created, nothing destroyed: the parent's cheque plus the fee the
    // platform took at open is precisely what he funded.
    let parent_gain = (fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap()
        - parent_before) as u64;
    assert_eq!(parent_gain + open_fee, COLLATERAL);
}

async fn assert_oracle_proxy_is_upgradeable(fixture: &PropFixture) {
    let expected_owner =
        State::Initialized(Identity::Address(fixture.deployer.address()));
    assert_eq!(
        fixture
            .deployment
            .oracle_proxy
            .methods()
            .proxy_target()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(ContractId::from(fixture.deployment.oracle_blob_id))
    );
    assert_eq!(
        fixture
            .deployment
            .oracle_proxy
            .methods()
            .proxy_owner()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        expected_owner
    );
    assert!(
        fixture
            .deployment
            .oracle_proxy
            .methods()
            .initialize_proxy()
            .call()
            .await
            .is_err()
    );
    assert!(
        fixture
            .deployment
            .oracle
            .methods()
            .initialize()
            .call()
            .await
            .is_err()
    );

    let outsider_proxy = PropAccountOracleProxyContract::new(
        fixture.deployment.oracle_id,
        fixture.outsider.clone(),
    );
    assert!(
        outsider_proxy
            .methods()
            .set_proxy_target(ContractId::from(fixture.deployment.account_blob_id,))
            .call()
            .await
            .is_err()
    );
    assert!(
        fixture
            .deployment
            .oracle_proxy
            .methods()
            .set_proxy_target(ContractId::zeroed())
            .call()
            .await
            .is_err()
    );

    fixture
        .deployment
        .oracle_proxy
        .methods()
        .set_proxy_target(ContractId::from(fixture.deployment.account_blob_id))
        .call()
        .await
        .unwrap();
    assert_eq!(
        fixture
            .deployment
            .oracle_proxy
            .methods()
            .proxy_target()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(ContractId::from(fixture.deployment.account_blob_id))
    );
    fixture
        .deployment
        .oracle_proxy
        .methods()
        .set_proxy_target(ContractId::from(fixture.deployment.oracle_blob_id))
        .call()
        .await
        .unwrap();

    assert_eq!(
        fixture
            .deployment
            .oracle
            .methods()
            .get_prop_account_impl()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(ContractId::from(fixture.deployment.account_blob_id))
    );
    assert_eq!(
        fixture
            .deployment
            .oracle
            .methods()
            .get_prop_margin_pool()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(fixture.deployment.pool_id)
    );
    assert_eq!(
        PropAccountProxyContract::new(fixture.child_id, fixture.user.clone(),)
            .methods()
            .oracle()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        fixture.deployment.oracle_id
    );
}

async fn assert_new_pool_defaults_do_not_require_a_create_manifest(
    fixture: &PropFixture,
) {
    let proxy_configurables = PropMarginPoolProxyContractConfigurables::default()
        .with_INITIAL_OWNER(State::Initialized(Identity::Address(
            fixture.deployer.address(),
        )))
        .unwrap()
        .with_INITIAL_TARGET(ContractId::from(fixture.deployment.pool_blob_id))
        .unwrap();
    let proxy_contract = regular_contract(
        PROP_MARGIN_POOL_PROXY_BYTECODE,
        PROP_MARGIN_POOL_PROXY_STORAGE,
        Salt::from([0x77; 32]),
    )
    .unwrap()
    .with_configurables(proxy_configurables);
    let (proxy_id, is_new) = deploy_regular(&fixture.deployer, proxy_contract)
        .await
        .unwrap();
    assert!(is_new);

    let proxy = PropMarginPoolProxyContract::new(proxy_id, fixture.deployer.clone());
    proxy.methods().initialize_proxy().call().await.unwrap();
    let pool = PropMarginPoolContract::new(proxy_id, fixture.deployer.clone());

    assert!(
        !pool
            .methods()
            .is_initialized()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
    assert_eq!(
        pool.methods()
            .get_bad_debt()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        0
    );
}

/// The netting is two pool-side ledgers falling together: no coins move and the
/// session's value does not budge. It must work while the session is frozen out
/// of the order book, because digging out is the entire point.
#[tokio::test]
async fn repay_from_collateral_nets_the_draw_below_the_freeze_line() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    // Drawn PAST the posted collateral, which the tier's leverage allows and
    // which the netting therefore cannot fully clear.
    let drawn = 2_500_000u64;
    let netted = COLLATERAL;
    let draw = fixture.draw_call(drawn);
    fixture.call_account(vec![draw], 1).await.unwrap();
    // 275 six-hour extensions accrue 1_650_000 of fees: enough to freeze the
    // session, not enough to make it liquidatable.
    let prolong = fixture.prolong_call(275);
    fixture.call_account(vec![prolong], 1).await.unwrap();

    let before = fixture.session().await;
    let value_before = fixture.session_value().await;
    let lines = fixture.lines().await;
    assert_eq!(before.fees_accrued, 1_650_000);
    assert_eq!(before.credit_line, 8_350_000);
    assert_eq!(value_before, 8_350_000);
    assert!(
        lines.positive <= lines.negative + lines.freeze,
        "the session must be below the freeze line for this test to mean anything"
    );
    assert!(lines.positive > lines.negative + lines.threshold);

    // The draw outruns the collateral, and only the collateral can be netted.
    let repay = fixture.repay_from_collateral_call(drawn);
    let error = fixture.call_account(vec![repay], 0).await.unwrap_err();
    assert!(
        error.to_string().contains("InsufficientBalance"),
        "unexpected netting error: {error:#}"
    );

    let pool_cash_before = fixture.pool_balance(fixture.collateral_asset).await;
    let account_cash_before = fixture.account_balance(fixture.collateral_asset).await;
    let repay = fixture.repay_from_collateral_call(netted);
    let response = fixture.call_account(vec![repay], 0).await.unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<QuoteRepaidFromCollateral>(&response.tx_status.receipts)
        .unwrap();

    assert_eq!(events.len(), 1);
    assert_eq!(events[0].account, fixture.child_id);
    assert_eq!(events[0].session_id, before.session_id);
    assert_eq!(events[0].amount, netted);
    assert_eq!(events[0].new_drawn_quote, drawn - netted);
    assert_eq!(events[0].new_collateral, 0);
    // The line prices off collateral NET of fees, and no collateral is left to
    // back it, so it falls back to bare `k`.
    assert_eq!(events[0].new_credit_line, 8_000_000);
    assert_eq!(events[0].from_capitalised, 0);
    assert_eq!(events[0].capitalised_total, 0);
    assert_eq!(events[0].decapitalised_total, netted);
    assert!(events[0].timestamp.unix != 0);

    let after = fixture.session().await;
    assert_eq!(after.drawn_quote, drawn - netted);
    assert_eq!(after.collateral, 0);
    assert_eq!(after.credit_line, 8_000_000);
    // The memo lives on the session itself, so the number the event reports and
    // the number settlement will read are the same storage slot - there is no
    // side table left to drift out of step with the log.
    assert_eq!(after.decapitalised, events[0].decapitalised_total);
    assert_eq!(after.decapitalised, netted);
    // Not one coin moved, and the pool's view of the session's value is
    // exactly where it was.
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        pool_cash_before
    );
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        account_cash_before
    );
    assert_eq!(fixture.session_value().await, value_before);

    let repay = fixture.repay_from_collateral_call(0);
    let error = fixture.call_account(vec![repay], 0).await.unwrap_err();
    assert!(
        error.to_string().contains("AmountIsZero"),
        "unexpected netting error: {error:#}"
    );
}

/// The netting carries NO health gate, and this is the case that proves it may
/// not. It cannot move `V` - both ledgers fall by the same `amount`, holdings
/// and debts are untouched, and the live threshold reads only the tier's terms
/// and the absorption cost - so a gate could never fire on anything the call
/// DID. It could only refuse a session that was already the liquidator's, which
/// is precisely the user this call exists to dig out.
///
/// The proof that the refusal would buy the pool nothing: the SAME underwater
/// session is liquidated twice, once with a netting in the middle and once
/// without, and the keeper's exit and every payout come out identical.
#[tokio::test]
async fn netting_while_liquidatable_changes_nothing_the_keeper_collects() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;

    async fn underwater_then_liquidated(netted: bool) -> SessionClosed {
        let mut fixture = PropFixture::new().await;
        let drawn = 1_000_000u64;
        let draw = fixture.draw_call(drawn);
        fixture.call_account(vec![draw], 1).await.unwrap();
        // 300 extensions accrue 1_800_000 of fees, putting `V` at 8_200_000 -
        // under the tier's 8_250_000 threshold.
        let prolong = fixture.prolong_call(300);
        fixture.call_account(vec![prolong], 1).await.unwrap();
        assert_eq!(fixture.session_value().await, 8_200_000);
        assert!(
            fixture.is_liquidatable().await,
            "the session must be the liquidator's for this test to mean anything"
        );

        if netted {
            let repay = fixture.repay_from_collateral_call(drawn);
            fixture.call_account(vec![repay], 0).await.unwrap();
            let after = fixture.session().await;
            assert_eq!(after.drawn_quote, 0);
            assert_eq!(after.collateral, COLLATERAL - drawn);
            // Netting did not buy him one unit of health, and the keeper's
            // exit is still open the instant the call returns.
            assert_eq!(fixture.session_value().await, 8_200_000);
            assert!(
                fixture.is_liquidatable().await,
                "the netting must not be an escape from liquidation"
            );
        }

        let closed = fixture.closed_event(&fixture.liquidate().await);
        assert!(
            !fixture
                .deployment
                .pool
                .methods()
                .has_session(fixture.child_id)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value
        );
        closed
    }

    let plain = underwater_then_liquidated(false).await;
    let netted = underwater_then_liquidated(true).await;
    let collateral_asset = AssetId::new([0x31; 32]);

    assert_eq!(plain.reason, SettlementReason::Liquidation);
    assert_eq!(netted.reason, plain.reason);
    // The pool marks the same session at the same value either way...
    assert_eq!(plain.v, 8_200_000);
    assert_eq!(netted.v, plain.v);
    assert!(!plain.v_is_negative && !netted.v_is_negative);
    // ...and hands out the same money. The netting's `+1_000_000` of measured
    // profit is met by `-1_000_000` of funded collateral, so `distributable`,
    // the platform's claim and the parent's remainder never move.
    //
    // The 1_800_000 of prolongation fees was collected 300 calls ago, so the
    // CLOSE collects nothing: `fees_accrued` is money already gone, taken off
    // the funded collateral and claimed by nobody again. The platform's total
    // take on the session is unchanged at 1_800_000 -
    // `fees_accrued + platform_total` - and so is the parent's, which is the
    // invariant this test exists to pin.
    assert_eq!(plain.fees_accrued, 1_800_000);
    assert_eq!(netted.fees_accrued, plain.fees_accrued);
    assert_eq!(plain.platform_total, 0);
    assert_eq!(netted.platform_total, plain.platform_total);
    assert_eq!(plain.fees_accrued + plain.platform_total, 1_800_000);
    assert!(plain.payout_platform.is_empty());
    assert_eq!(netted.payout_platform, plain.payout_platform);
    assert_eq!(plain.user_net, netted.user_net);
    // The parent's remainder is what it always was: the 2_000_000 he funded
    // less the 1_800_000 of fees. The fee left earlier, not in a larger amount.
    assert_eq!(plain.user_net, COLLATERAL - 1_800_000);
    assert_eq!(
        plain.payout_parent,
        vec![(collateral_asset, COLLATERAL - 1_800_000)]
    );
    assert_eq!(plain.payout_parent, netted.payout_parent);
    assert_eq!(plain.bad_debt, 0);
    assert_eq!(netted.bad_debt, plain.bad_debt);
}

/// With no health gate the call reads storage and nothing else: no oracle, no
/// walk over the tier's books, and nothing but the pool among the transaction's
/// contract inputs. Proved the only way the VM lets you prove it - by leaving
/// the price feed and the book OUT of the input set, which reverts the whole
/// transaction the moment the contract touches either.
///
/// This is what makes the call safe to reach for in a crisis: a stale or
/// unreachable price feed can never trap a user inside a draw.
#[tokio::test]
async fn netting_asks_for_neither_the_price_feed_nor_the_books() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    // The whole draw goes into an unmatched buy: nothing on the account,
    // 1_000_000 of quote resting on the book. A distressed user very often has
    // orders resting precisely because he is mid-unwind.
    let drawn = 1_000_000u64;
    let draw = fixture.draw_call(drawn);
    let buy = fixture.book_call(2_000_000, 500_000_000, fixture.collateral_asset, drawn);
    fixture.call_account(vec![draw, buy], 2).await.unwrap();
    let prolong = fixture.prolong_call(275);
    fixture.call_account(vec![prolong], 1).await.unwrap();

    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);
    assert_eq!(
        fixture
            .order_book
            .order_book
            .methods()
            .get_total_balance_of(Identity::ContractId(fixture.child_id))
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        (0, drawn)
    );
    let value_before = fixture.session_value().await;
    assert_eq!(value_before, 8_350_000);

    // Only the oracle the account itself needs to authorise the session, and
    // the pool being called. No price feed, no book, no registry.
    let repay = fixture.repay_from_collateral_call(drawn);
    fixture
        .call_account_with_contract_ids(
            vec![repay],
            &[fixture.deployment.oracle_id, fixture.deployment.pool_id],
        )
        .await
        .unwrap();

    let after = fixture.session().await;
    assert_eq!(after.drawn_quote, 0);
    assert_eq!(after.collateral, COLLATERAL - drawn);
    assert_eq!(fixture.session_value().await, value_before);
    // The resting order is exactly where it was: the netting reads books, moves
    // coins and cancels orders precisely never.
    assert_eq!(
        fixture
            .order_book
            .order_book
            .methods()
            .get_total_balance_of(Identity::ContractId(fixture.child_id))
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        (0, drawn)
    );

    // Collateral is left over but the draw is gone, so the netting is bounded
    // by the draw and not by the pot it is netted against.
    let repay = fixture.repay_from_collateral_call(1);
    let error = fixture.call_account(vec![repay], 0).await.unwrap_err();
    assert!(
        error.to_string().contains("OverRepay"),
        "unexpected netting error: {error:#}"
    );
}

/// The netting does not require a clean slate, and must not: the story it was
/// written for has the user close the quote leg while an in-kind short is still
/// open. `withdraw` is a DRAIN - coins leave and the pool's claim stays put -
/// so it demands `drawn_quote` and every debt at zero. This is an
/// EXTINGUISHMENT: the amount never leaves the contract, it cancels the pool's
/// own claim, so the pool's net position is identical to the coin across it
/// however many debts are open.
#[tokio::test]
async fn netting_clears_a_draw_while_an_asset_debt_is_still_open() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let quantity = 1_000_000_000u64;
    let sale = 2_000_000u64;
    let drawn = 1_000_000u64;

    // Short the base and draw quote beside it: an in-kind debt and a cash draw
    // outstanding at the same time.
    fixture
        .rest_order(sale, quantity, fixture.collateral_asset, sale)
        .await;
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let sell = fixture.book_call(sale, quantity, fixture.base_asset, quantity);
    fixture
        .call_account(vec![borrow, sell, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    let draw = fixture.draw_call(drawn);
    fixture.call_account(vec![draw], 1).await.unwrap();

    assert_eq!(fixture.debt(fixture.base_asset).await, quantity);
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        sale + drawn
    );
    let value_before = fixture.session_value().await;
    let pool_cash_before = fixture.pool_balance(fixture.collateral_asset).await;

    let repay = fixture.repay_from_collateral_call(drawn);
    fixture.call_account(vec![repay], 0).await.unwrap();

    let after = fixture.session().await;
    assert_eq!(after.drawn_quote, 0);
    assert_eq!(after.collateral, COLLATERAL - drawn);
    // The debt leg is untouched, `V` has not moved, and not one coin did.
    assert_eq!(fixture.debt(fixture.base_asset).await, quantity);
    assert_eq!(fixture.session_value().await, value_before);
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        pool_cash_before
    );
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        sale + drawn
    );

    // And the doors that stay shut while the pool is still owed an asset stay
    // shut. The draw is gone, so each of these now fails on the DEBT.
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, 1u64)),
    );
    let error = fixture.call_account(vec![withdraw], 2).await.unwrap_err();
    assert!(
        error.to_string().contains("DebtsOutstanding"),
        "the netting must not open a drain: {error:#}"
    );
    let capitalise = fixture.pool_call(
        fn_selector!(add_collateral(ContractId)),
        1,
        fixture.collateral_asset,
        Some(call_data!(fixture.child_id)),
    );
    let error = fixture.call_account(vec![capitalise], 0).await.unwrap_err();
    assert!(
        error.to_string().contains("DebtsOutstanding"),
        "self-funding must still need a clean slate: {error:#}"
    );
    let error = fixture
        .account
        .methods()
        .close_session(vec![])
        .with_contracts(&[
            &fixture.deployment.pool,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("DebtsOutstanding"),
        "a voluntary close must still need the debt repaid: {error:#}"
    );

    // Now close the short in kind and leave properly. The base never moved, so
    // the round trip is flat and the parent gets exactly its collateral back -
    // the `decapitalised` memo is what stops the netted 1_000_000 being taxed
    // as profit he never made.
    fixture
        .rest_order(sale, quantity, fixture.base_asset, quantity)
        .await;
    let buy_back = fixture.book_call(sale, quantity, fixture.collateral_asset, sale);
    let repay_in_kind =
        fixture.pool_call(fn_selector!(repay()), quantity, fixture.base_asset, None);
    fixture
        .call_account(vec![buy_back, fixture.settle_book_call(), repay_in_kind], 2)
        .await
        .unwrap();
    assert_eq!(fixture.debt(fixture.base_asset).await, 0);

    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let closed = fixture.closed_event(&fixture.close_session().await);
    assert_eq!(closed.reason, SettlementReason::UserClose);
    assert_eq!(closed.bad_debt, 0);
    assert_eq!(
        closed.platform_total, 0,
        "a flat round trip owes the platform nothing: {:?}",
        closed.payout_platform
    );
    assert_eq!(
        closed.payout_parent,
        vec![(fixture.collateral_asset, COLLATERAL)]
    );
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        parent_before + u128::from(COLLATERAL)
    );
}

/// The netting must not hand back borrowing power. The line falls by at most
/// the amount netted while the draw falls by exactly it, so the headroom a
/// session has under its loan cap is the same number on both sides of the call
/// - which is why the cap needs no re-check inside it.
#[tokio::test]
async fn netting_leaves_the_loan_cap_headroom_exactly_where_it_was() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let drawn = 1_000_000u64;
    let draw = fixture.draw_call(drawn);
    fixture.call_account(vec![draw], 1).await.unwrap();
    let before = fixture.session().await;
    let headroom = before.credit_line - before.drawn_quote;
    assert_eq!(headroom, 9_000_000);

    let repay = fixture.repay_from_collateral_call(drawn);
    fixture.call_account(vec![repay], 0).await.unwrap();
    let after = fixture.session().await;
    assert_eq!(after.drawn_quote, 0);
    assert_eq!(after.credit_line, before.credit_line - drawn);
    assert_eq!(after.credit_line - after.drawn_quote, headroom);

    // To the last unit: the whole headroom draws, and one more does not.
    let draw = fixture.draw_call(headroom + 1);
    let error = fixture.call_account(vec![draw], 1).await.unwrap_err();
    assert!(
        error.to_string().contains("LoanCapExceeded"),
        "the netting must not widen the cap: {error:#}"
    );
    let draw = fixture.draw_call(headroom);
    fixture.call_account(vec![draw], 1).await.unwrap();
    assert_eq!(fixture.session().await.drawn_quote, headroom);
}

/// Above the tier cap the line stops tracking collateral, so a netting that
/// drops the draw does NOT drop the line with it and the session gets its
/// headroom back. That is the cap's doing, not the netting's, and it creates
/// nothing: the line after the call is `min(k + collateral, cap)` to the unit -
/// exactly what a plain deposit of that collateral earns, with no memory of the
/// draw netted away. The pool's cash and exposure only ever improve across it.
#[tokio::test]
async fn netting_at_the_tier_cap_returns_headroom_the_collateral_still_earns() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    // `k` is the line the tier grants against no collateral at all; `cap` is
    // `line * max_credit_line_bps`, the ceiling collateral can never buy past.
    const K: u64 = 8_000_000;
    const CAP: u64 = 20_000_000;
    let line_for = |collateral: u64| (K + collateral).min(CAP);

    // Over-collateralise until the line pins to the cap with room to spare:
    // 20_000_000 of collateral would earn 28_000_000 uncapped.
    fixture.fund_collateral(18_000_000).await;
    let funded = fixture.session().await;
    assert_eq!(funded.collateral, 20_000_000);
    assert_eq!(funded.credit_line, CAP);
    assert_eq!(funded.capitalised, 0, "an outside funder buys no share");

    let drawn = 5_000_000u64;
    let draw = fixture.draw_call(drawn);
    fixture.call_account(vec![draw], 1).await.unwrap();
    let before = fixture.session().await;
    let headroom_before = before.credit_line - before.drawn_quote;
    assert_eq!(headroom_before, 15_000_000);
    let pool_cash_before = fixture.pool_balance(fixture.collateral_asset).await;
    let value_before = fixture.session_value().await;
    assert_eq!(value_before, 28_000_000);

    let repay = fixture.repay_from_collateral_call(drawn);
    fixture.call_account(vec![repay], 0).await.unwrap();

    let after = fixture.session().await;
    assert_eq!(after.drawn_quote, 0);
    assert_eq!(after.collateral, 15_000_000);
    // Still capped, so the line did not move and the headroom grew by the whole
    // netted amount. Said out loud because it is the one number that does.
    assert_eq!(after.credit_line, CAP);
    assert_eq!(
        after.credit_line - after.drawn_quote,
        headroom_before + drawn
    );
    // It earned that line, it did not inherit it: nothing is reachable here
    // that a deposit of the same collateral could not reach directly.
    assert_eq!(after.credit_line, line_for(after.collateral));
    // `V` is invariant even though the line held still, because `credit_line`
    // cancels between the two legs. Not a coin moved either way.
    assert_eq!(fixture.session_value().await, value_before);
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        pool_cash_before
    );

    // Re-drawing the whole line is what the cap always allowed against this
    // collateral, and one unit past it is still refused.
    let draw = fixture.draw_call(CAP + 1);
    let error = fixture.call_account(vec![draw], 1).await.unwrap_err();
    assert!(
        error.to_string().contains("LoanCapExceeded"),
        "the cap must still bind after a netting: {error:#}"
    );
    let draw = fixture.draw_call(CAP);
    fixture.call_account(vec![draw], 1).await.unwrap();
    assert_eq!(fixture.session().await.drawn_quote, CAP);

    // And netting the collateral away entirely drops the line out of the capped
    // band the moment the collateral stops earning it - all the way back to the
    // bare `k` the tier grants for nothing.
    let repay = fixture.repay_from_collateral_call(15_000_000);
    fixture.call_account(vec![repay], 0).await.unwrap();
    let uncapped = fixture.session().await;
    assert_eq!(uncapped.collateral, 0);
    assert_eq!(uncapped.drawn_quote, CAP - 15_000_000);
    assert_eq!(uncapped.credit_line, line_for(uncapped.collateral));
    assert_eq!(uncapped.credit_line, K);
    // Through all of it the pool never paid out and its claim only shrank.
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        pool_cash_before - CAP
    );
}

/// The case the design has to survive: a loan at the tier cap, a crash that
/// wipes the position out, and a loss past every unit of collateral the user
/// posted. The netting is available to him the whole way down - and it moves
/// not one unit of that loss onto the pool. The same journey is liquidated
/// twice, netted and not, and the bad debt the pool books is identical.
#[tokio::test]
async fn a_crash_past_the_whole_collateral_books_the_same_bad_debt_either_way() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;

    async fn capped_loan_then_crash(netted: bool) -> (SessionClosed, u64) {
        let mut fixture = PropFixture::new().await;
        // 12_000_000 is the LEAST collateral that pins the line to the
        // 20_000_000 cap, so this is the most the tier will ever lend against
        // the least collateral that earns it - the thinnest legal position.
        fixture.fund_collateral(10_000_000).await;
        let drawn = 20_000_000u64;
        let quantity = 10_000_000_000u64;
        let session = fixture.session().await;
        assert_eq!(session.collateral, 12_000_000);
        assert_eq!(session.credit_line, drawn);

        fixture
            .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
            .await;
        let draw = fixture.draw_call(drawn);
        let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, drawn);
        fixture
            .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
            .await
            .unwrap();
        assert_eq!(fixture.account_balance(fixture.base_asset).await, quantity);
        assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);

        // The base falls to a hundredth of what he paid: the position is worth
        // 200_000 against a 20_000_000 draw, and 12_000_000 of collateral
        // cannot begin to cover the gap.
        fixture.publish_base_price(20_000_000_000_000_000u128).await;
        let value_before = fixture.session_value().await;
        assert_eq!(value_before, 200_000);
        assert!(fixture.is_liquidatable().await);

        if netted {
            // Every unit of collateral he has, and not one more.
            let repay = fixture.repay_from_collateral_call(12_000_000);
            fixture.call_account(vec![repay], 0).await.unwrap();
            let after = fixture.session().await;
            assert_eq!(after.collateral, 0);
            assert_eq!(after.drawn_quote, 8_000_000);
            assert_eq!(after.credit_line, 8_000_000);
            assert_eq!(fixture.session_value().await, value_before);
            assert!(fixture.is_liquidatable().await);

            let repay = fixture.repay_from_collateral_call(1);
            let error = fixture.call_account(vec![repay], 0).await.unwrap_err();
            assert!(
                error.to_string().contains("InsufficientBalance"),
                "the collateral is spent and the netting must say so: {error:#}"
            );
        }

        let closed = fixture.closed_event(&fixture.liquidate().await);
        (closed, fixture.bad_debt().await)
    }

    let (plain, plain_book) = capped_loan_then_crash(false).await;
    let (netted, netted_book) = capped_loan_then_crash(true).await;

    assert_eq!(plain.reason, SettlementReason::Liquidation);
    assert_eq!(netted.reason, plain.reason);
    assert_eq!(plain.v, 200_000);
    assert_eq!(netted.v, plain.v);
    // 20_000_000 lent against a position worth 198_000 after the haircut, less
    // the 12_000_000 of collateral that absorbs the loss first. The netting
    // consumed that same 12_000_000 up front instead - same hole, same side.
    assert_eq!(plain.bad_debt, 7_802_000);
    assert_eq!(netted.bad_debt, plain.bad_debt);
    assert_eq!(plain_book, plain.bad_debt);
    assert_eq!(netted_book, plain_book);
    // Nobody is paid out of a hole this deep, in either world, and the whole
    // position goes to the liquidator to work off-contract.
    assert_eq!(plain.user_net, 0);
    assert_eq!(netted.user_net, plain.user_net);
    assert_eq!(plain.platform_total, 0);
    assert_eq!(netted.platform_total, plain.platform_total);
    assert!(plain.payout_parent.is_empty() && netted.payout_parent.is_empty());
    assert!(plain.payout_platform.is_empty() && netted.payout_platform.is_empty());
}

/// `withdraw`'s account leg is share-bearing because, with `drawn_quote` and
/// every in-kind debt at zero, anything resting on the account could only have
/// been TRADED there. The netting is the one call that breaks that premise: it
/// moves funded collateral out against the draw and leaves it on the account as
/// PRINCIPAL, which `withdrawal_portions` then drains FIRST. Without consuming
/// the `decapitalised` memo, the user pays a profit share on his own capital -
/// and settlement cannot give it back, because the share base saturates at zero.
///
/// Both halves are pinned here in one journey: the netted principal comes back
/// untaxed, and the profit earned on top of it is still charged in full.
#[tokio::test]
async fn netting_returns_principal_untaxed_while_real_profit_still_pays() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let principal = 1_000_000u64;
    let quantity = 500_000_000u64;
    let sale = 1_500_000u64;
    let profit = sale - principal;
    // Netting spends funded collateral, and `withdraw` holds the tier's entry
    // ticket as a STANDING floor, so the session needs headroom above
    // `required_collateral` for the withdrawal below to be legal at all. Top up
    // from an outside funder first: this test is about the SHARE, not the floor.
    let topped_up = COLLATERAL + 2_000_000;
    fixture.fund_collateral(2_000_000).await;
    assert_eq!(fixture.session().await.collateral, topped_up);

    // Draw, then net it straight back off. The cash stays on the account, but
    // it is now the user's OWN collateral, not borrowed quote.
    let draw = fixture.draw_call(principal);
    fixture.call_account(vec![draw], 1).await.unwrap();
    let repay = fixture.repay_from_collateral_call(principal);
    let response = fixture.call_account(vec![repay], 0).await.unwrap();
    let netted = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<QuoteRepaidFromCollateral>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(netted[0].decapitalised_total, principal);
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        principal
    );
    assert_eq!(fixture.session().await.collateral, topped_up - principal);

    // Trade that principal into a real 500_000 of profit: buy the base at 2.0
    // and sell it back at 3.0.
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, principal);
    fixture
        .call_account(vec![buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    fixture
        .rest_order(3_000_000, quantity, fixture.collateral_asset, sale)
        .await;
    let sell = fixture.book_call(3_000_000, quantity, fixture.base_asset, quantity);
    fixture
        .call_account(vec![sell, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        sale
    );

    // Take the whole account balance out. `withdrawal_portions` drains the
    // account leg first, so this is the exact call that used to tax principal.
    let parent_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, sale)),
    );
    let response = fixture.call_account(vec![withdraw], 2).await.unwrap();
    let withdrawn = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<MarginWithdrawn>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(withdrawn.len(), 1);
    assert_eq!(withdrawn[0].amount, sale);
    assert_eq!(withdrawn[0].from_account, sale);
    assert_eq!(withdrawn[0].from_pool, 0);
    // 10% of the 500_000 he actually earned, and NOT one unit of the
    // 1_000_000 of his own capital the netting parked on the account.
    assert_eq!(
        withdrawn[0].share_qty,
        profit / 10,
        "the netted principal must not be taxed as profit"
    );
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        parent_before + u128::from(sale - profit / 10)
    );

    // The memo is spent, so settlement does not correct the same principal a
    // second time, and the books reconcile: the whole remaining collateral
    // comes back, 500_000 was earned, 50_000 of it shared, and nothing else
    // moved.
    let remaining = topped_up - principal;
    let closed = fixture.closed_event(&fixture.close_session().await);
    assert_eq!(closed.reason, SettlementReason::UserClose);
    assert_eq!(closed.bad_debt, 0);
    assert_eq!(closed.platform_total, 0);
    assert_eq!(
        closed.payout_parent,
        vec![(fixture.collateral_asset, remaining)]
    );
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        parent_before + u128::from(sale - profit / 10 + remaining)
    );
}

/// The netting reads its account from `caller_contract()`, so it can only ever
/// touch the session of whoever is calling. A wallet has no session to net.
#[tokio::test]
async fn only_a_contract_with_a_session_can_net_a_draw() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let draw = fixture.draw_call(1_000_000);
    fixture.call_account(vec![draw], 1).await.unwrap();

    let error = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .repay_from_collateral(1_000_000)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("CallerNotContract"),
        "a wallet must not be able to net anybody's draw: {error:#}"
    );
    assert_eq!(fixture.session().await.drawn_quote, 1_000_000);
    assert_eq!(fixture.session().await.collateral, COLLATERAL);
}

/// A long that fell. He drew quote and bought the base; the base halved. He
/// cannot repay the draw without selling into the loss, and `withdraw` demands
/// `drawn_quote == 0`, so without the netting he is stuck holding the position.
#[tokio::test]
async fn a_long_that_fell_nets_its_draw_away_and_closes_cleanly() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    fixture
        .rest_order(cost, quantity, fixture.base_asset, quantity)
        .await;

    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(cost, quantity, fixture.collateral_asset, cost);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    assert_eq!(fixture.account_balance(fixture.base_asset).await, quantity);
    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);

    // The base halves: the position is worth 1_000_000 against a 2_000_000
    // draw, and there is no cash left anywhere to return.
    fixture
        .publish_base_price(1_000_000_000_000_000_000u128)
        .await;
    let value_before = fixture.session_value().await;
    assert_eq!(value_before, 9_000_000);

    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let error = fixture.call_account(vec![withdraw], 2).await.unwrap_err();
    assert!(
        error.to_string().contains("QuoteOutstanding"),
        "the draw is what traps him: {error:#}"
    );

    let repay = fixture.repay_from_collateral_call(cost);
    fixture.call_account(vec![repay], 0).await.unwrap();
    let after = fixture.session().await;
    assert_eq!(after.drawn_quote, 0);
    assert_eq!(after.collateral, COLLATERAL - cost);
    assert_eq!(fixture.session_value().await, value_before);

    // The draw is gone, so `QuoteOutstanding` no longer bites - but the netting
    // spent every unit of funded collateral to get there, and the tier's entry
    // ticket is a STANDING floor. A partial exit is refused while the session
    // sits under it, on the account leg exactly as on the pool leg.
    let released = 100_000_000u64;
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, released)),
    );
    let error = fixture.call_account(vec![withdraw], 2).await.unwrap_err();
    assert!(
        error.to_string().contains("BelowTierCollateral"),
        "a session funded below its tier floor must not release anything: {error:#}"
    );

    // He is not trapped, though - the full exit has no such floor, and returns
    // the WHOLE position at par. The netting moved 2_000_000 out of funded
    // collateral, which inflates measured profit by exactly that much; the
    // session's `decapitalised` memo takes it straight back out, so the
    // platform charges no share on a position that LOST money.
    let closed = fixture.closed_event(&fixture.close_session().await);
    assert_eq!(closed.reason, SettlementReason::UserClose);
    assert_eq!(closed.platform_total, 0);
    assert!(
        closed.payout_platform.is_empty(),
        "a netted draw must not be taxed as profit: {:?}",
        closed.payout_platform
    );
    assert_eq!(closed.payout_parent, vec![(fixture.base_asset, quantity)]);
    assert_eq!(closed.bad_debt, 0);
}

/// A short that rose. He borrowed the base, sold it, and bought it back higher
/// with drawn quote. The in-kind debt is settled but the draw is not, and there
/// is no cash left to return it with.
#[tokio::test]
async fn a_short_that_rose_nets_its_draw_away_and_closes_cleanly() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let quantity = 1_000_000_000u64;
    let sale = 2_000_000u64;
    let buy_back = 3_000_000u64;
    fixture
        .rest_order(sale, quantity, fixture.collateral_asset, sale)
        .await;

    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let sell = fixture.book_call(sale, quantity, fixture.base_asset, quantity);
    fixture
        .call_account(vec![borrow, sell, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        sale
    );

    // The base rises by half: buying the borrowed quantity back costs
    // 3_000_000 against the 2_000_000 the sale raised.
    fixture
        .publish_base_price(3_000_000_000_000_000_000u128)
        .await;
    fixture
        .rest_order(buy_back, quantity, fixture.base_asset, quantity)
        .await;

    let draw = fixture.draw_call(buy_back - sale);
    let buy = fixture.book_call(buy_back, quantity, fixture.collateral_asset, buy_back);
    let repay_in_kind =
        fixture.pool_call(fn_selector!(repay()), quantity, fixture.base_asset, None);
    fixture
        .call_account(
            vec![draw, buy, fixture.settle_book_call(), repay_in_kind],
            2,
        )
        .await
        .unwrap();

    let before = fixture.session().await;
    assert_eq!(before.drawn_quote, buy_back - sale);
    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);
    assert_eq!(fixture.account_balance(fixture.base_asset).await, 0);
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_debts(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
    let value_before = fixture.session_value().await;

    let repay = fixture.repay_from_collateral_call(before.drawn_quote);
    fixture.call_account(vec![repay], 0).await.unwrap();
    let after = fixture.session().await;
    assert_eq!(after.drawn_quote, 0);
    assert_eq!(after.collateral, COLLATERAL - before.drawn_quote);
    assert_eq!(fixture.session_value().await, value_before);

    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let closed = fixture.closed_event(&fixture.close_session().await);
    assert_eq!(closed.reason, SettlementReason::UserClose);
    assert_eq!(closed.bad_debt, 0);
    assert_eq!(closed.platform_total, 0);
    assert_eq!(
        closed.payout_parent,
        vec![(fixture.collateral_asset, after.collateral)]
    );
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        parent_before + u128::from(after.collateral)
    );
}

/// The settlement-level reconciliation, and the reason `decapitalised` exists.
///
/// A voluntary close demands the pool be owed NOTHING, so the same profitable
/// journey is run twice with the two legal ways of getting there: selling into
/// the position and paying the draw back in cash, versus netting it against
/// posted collateral. The two leave the user holding completely different
/// baskets - 2_000_000 of funded collateral plus half the position, against no
/// collateral and all of it - yet the platform must walk away with the same
/// money, because the user earned the same 2_000_000 either way. The netting
/// shifts 2_000_000 from funded collateral into measured profit, so without the
/// `decapitalised` correction the platform would charge its share on 4_000_000
/// of "profit" instead of the 2_000_000 actually made.
#[tokio::test]
async fn netting_leaves_the_platforms_settlement_take_exactly_where_it_was() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;

    async fn profitable_long_then_close(netted: bool) -> SessionClosed {
        let mut fixture = PropFixture::new().await;
        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();

        // The base doubles: 2_000_000 of real, share-bearing profit.
        fixture
            .publish_base_price(4_000_000_000_000_000_000u128)
            .await;

        if netted {
            // Route A: net the draw against posted collateral. No coins move,
            // the whole position stays on the account.
            let repay = fixture.repay_from_collateral_call(cost);
            fixture.call_account(vec![repay], 0).await.unwrap();
            let session = fixture.session().await;
            assert_eq!(session.drawn_quote, 0);
            assert_eq!(session.collateral, 0);
            assert_eq!(fixture.account_balance(fixture.base_asset).await, quantity);
        } else {
            // Route B: sell half the position at the new mark and hand the
            // 2_000_000 straight back. Collateral is untouched; half the base
            // is gone.
            let sold = quantity / 2;
            fixture
                .rest_order(4_000_000, sold, fixture.collateral_asset, cost)
                .await;
            let sell = fixture.book_call(4_000_000, sold, fixture.base_asset, sold);
            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 session = fixture.session().await;
            assert_eq!(session.drawn_quote, 0);
            assert_eq!(session.collateral, COLLATERAL);
            assert_eq!(
                fixture.account_balance(fixture.base_asset).await,
                quantity - sold
            );
        }
        fixture.closed_event(&fixture.close_session().await)
    }

    /// What the platform actually walked away with, priced at the closing
    /// marks: base at 4.0 (9 decimals) into collateral units (6 decimals).
    fn realised_take(closed: &SessionClosed, collateral: AssetId) -> u128 {
        closed
            .payout_platform
            .iter()
            .map(|(asset, amount)| {
                if *asset == collateral {
                    u128::from(*amount)
                } else {
                    u128::from(*amount) * 4 / 1_000
                }
            })
            .sum()
    }

    let plain = profitable_long_then_close(false).await;
    let netted = profitable_long_then_close(true).await;
    let collateral_asset = AssetId::new([0x31; 32]);

    // 10% of the 2_000_000 the position actually earned, in both worlds.
    assert_eq!(plain.platform_total, 200_000);
    assert_eq!(netted.platform_total, plain.platform_total);
    assert_eq!(realised_take(&plain, collateral_asset), 200_000);
    assert_eq!(realised_take(&netted, collateral_asset), 200_000);
    // The user is whole in both too, up to the single base unit the in-kind
    // split rounds in the pool's favour when a shortfall has to be covered.
    assert!(
        plain.user_net.abs_diff(netted.user_net) <= 1,
        "the route to a clean slate moved the user's settlement: {} vs {}",
        plain.user_net,
        netted.user_net
    );
    assert_eq!(plain.bad_debt, 0);
    assert_eq!(netted.bad_debt, 0);
}

/// The other half of the share story, and the shape that would leak if the
/// correction ever double counted: profit CAPITALISED into collateral already
/// owes the platform its share, and netting takes that collateral back out.
/// Striking the capitalised balance and deferring the remainder are two halves
/// of ONE correction - together they move the share base by exactly the amount
/// netted, matching the exactly-that-much rise in measured profit. Applying
/// both to the full amount would erase a real claim, and the pool would eat it
/// at close with an empty basket to blame.
#[tokio::test]
async fn capitalised_profit_survives_a_netting_and_is_still_shared_at_close() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let quantity = 1_000_000_000u64;
    let cost = 2_000_000u64;
    let sale = 3_000_000u64;
    let profit = sale - cost;

    // Buy the base with drawn quote, watch it rise by half, sell it back and
    // return the draw: 1_000_000 of realised, share-bearing profit in cash.
    fixture
        .rest_order(cost, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(cost);
    let buy = fixture.book_call(cost, 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;
    fixture
        .rest_order(sale, quantity, fixture.collateral_asset, sale)
        .await;
    let sell = fixture.book_call(sale, 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();
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        profit
    );

    // Capitalise it: the profit becomes funded collateral and stops showing up
    // in measured P&L, which is exactly what `capitalised` is for.
    let capitalise = fixture.pool_call(
        fn_selector!(add_collateral(ContractId)),
        profit,
        fixture.collateral_asset,
        Some(call_data!(fixture.child_id)),
    );
    fixture.call_account(vec![capitalise], 0).await.unwrap();
    let capitalised = fixture.session().await;
    assert_eq!(capitalised.collateral, COLLATERAL + profit);
    assert_eq!(capitalised.capitalised, profit);

    // Draw against it and net the draw straight back off: the capitalised
    // balance is struck, and nothing is deferred because it covered the whole
    // netting.
    let draw = fixture.draw_call(profit);
    fixture.call_account(vec![draw], 1).await.unwrap();
    let repay = fixture.repay_from_collateral_call(profit);
    let response = fixture.call_account(vec![repay], 0).await.unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<QuoteRepaidFromCollateral>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].from_capitalised, profit);
    assert_eq!(events[0].capitalised_total, 0);
    assert_eq!(
        events[0].decapitalised_total, 0,
        "the netting was covered by the capitalised balance, so deferring any \
         of it as well would count the same correction twice",
    );

    let netted = fixture.session().await;
    assert_eq!(netted.collateral, COLLATERAL);
    assert_eq!(netted.drawn_quote, 0);
    assert_eq!(netted.capitalised, 0);
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        profit
    );

    // The profit is back in the account and back in measured P&L, so the
    // platform still collects its 10% of the 1_000_000 the user really made.
    let closed = fixture.closed_event(&fixture.close_session().await);
    assert_eq!(closed.reason, SettlementReason::UserClose);
    assert_eq!(closed.platform_total, profit / 10);
    assert_eq!(
        closed.payout_platform,
        vec![(fixture.collateral_asset, profit / 10)]
    );
    assert_eq!(
        closed.payout_parent,
        vec![(fixture.collateral_asset, COLLATERAL + profit - profit / 10)]
    );
    assert_eq!(closed.bad_debt, 0);
}

/// Found while proving the netting cannot underflow, and pre-existing:
/// `prolong` reprices the line off the collateral NET of accrued fees, so a
/// long-lived session can end up owing more quote than its line expresses.
/// Subtracting that unsigned reverts, and this is the single valuation path
/// behind `liquidate`, `expire_session` and `get_session_lines` - so the
/// session could be neither valued nor closed, with the pool's principal
/// outstanding the whole time.
#[tokio::test]
async fn a_session_prolonged_past_its_line_can_still_be_valued_and_liquidated() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let drawn = 9_000_000u64;
    let draw = fixture.draw_call(drawn);
    fixture.call_account(vec![draw], 1).await.unwrap();
    // 300 six-hour extensions accrue 1_800_000 of fees against 2_000_000 of
    // collateral, pricing the line at 8_200_000 - under the 9_000_000 drawn.
    let prolong = fixture.prolong_call(300);
    fixture.call_account(vec![prolong], 1).await.unwrap();

    let session = fixture.session().await;
    assert_eq!(session.fees_accrued, 1_800_000);
    assert_eq!(session.credit_line, 8_200_000);
    assert!(
        session.credit_line < session.drawn_quote,
        "the fixture must reach the overdrawn state this test is about"
    );

    let lines = fixture.lines().await;
    // The 800_000 deficit sits on the NEGATIVE leg beside the fees, not clamped
    // away: 1_800_000 of equity the line does not express plus the 9_000_000 of
    // drawn cash still on the account, against 2_600_000.
    assert_eq!(lines.positive, U256::from(10_800_000u64));
    assert_eq!(lines.negative, U256::from(2_600_000u64));
    assert_eq!(fixture.session_value().await, 8_200_000);
    // Clamping the deficit at zero would have reported 9_000_000 here - too
    // healthy by exactly the deficit, and enough to clear the line below.
    assert!(
        lines.positive <= lines.negative + lines.threshold,
        "an overdrawn session must be liquidatable, not merely valuable"
    );

    let response = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .liquidate(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
        .unwrap();
    let closed = response.decode_logs_with_type::<SessionClosed>().unwrap();
    assert_eq!(closed.len(), 1);
    assert_eq!(closed[0].reason, SettlementReason::Liquidation);
    assert_eq!(closed[0].v, 8_200_000);
    assert!(!closed[0].v_is_negative);
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
}

/// The netting is deliberately gated on NEITHER `paused` NOR expiry. It only
/// ever shrinks the pool's outstanding cash, so neither an emergency stop nor a
/// lapsed deadline may trap a user inside a draw - the same reasoning that
/// leaves `return_quote` and `repay` open.
#[tokio::test]
async fn netting_survives_a_pause_and_an_elapsed_deadline() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let half = 500_000u64;
    let draw = fixture.draw_call(half * 2);
    fixture.call_account(vec![draw], 1).await.unwrap();

    fixture
        .deployment
        .pool
        .methods()
        .pause()
        .call()
        .await
        .unwrap();
    let draw = fixture.draw_call(1);
    let error = fixture.call_account(vec![draw], 1).await.unwrap_err();
    assert!(
        error.to_string().contains("Paused"),
        "the pause must actually be in force: {error:#}"
    );
    let repay = fixture.repay_from_collateral_call(half);
    fixture.call_account(vec![repay], 0).await.unwrap();
    fixture
        .deployment
        .pool
        .methods()
        .unpause()
        .call()
        .await
        .unwrap();

    // Outlive the pool session with the account's own signing session, so the
    // clock below expires only the thing under test.
    let session = fixture.session().await;
    fixture
        .account
        .methods()
        .set_session(ParallelSessionArgs {
            nonce: U256::one(),
            session_id: Identity::Address(fixture.user.address()),
            expiry: Time {
                unix: session.expires_at + 86_400,
            },
            contract_ids: vec![],
        })
        .with_contract_ids(&[fixture.deployment.oracle_id])
        .call()
        .await
        .unwrap();

    let provider = fixture.outsider.try_provider().unwrap();
    let latest = provider
        .latest_block_time()
        .await
        .unwrap()
        .expect("local chain has a latest block time");
    let expired_time = latest
        .checked_add_signed(chrono::TimeDelta::seconds(
            (session.expires_at.saturating_sub(latest.timestamp() as u64) + 1) as i64,
        ))
        .expect("test expiry timestamp is representable");
    provider
        .produce_blocks(1, Some(expired_time))
        .await
        .unwrap();

    let repay = fixture.repay_from_collateral_call(half);
    fixture.call_account(vec![repay], 0).await.unwrap();
    let after = fixture.session().await;
    assert_eq!(after.drawn_quote, 0);
    assert_eq!(after.collateral, COLLATERAL - half * 2);

    // And the keeper's exit is still there afterwards.
    expire_fixture_session(&fixture).await;
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
}

/// The tier's entry ticket is a STANDING floor, and this is the attack that
/// proved it was not. `withdraw` bounded `BelowTierCollateral` on the
/// `from_pool` leg only, which was sound while account cash could only be
/// TRADED profit. `repay_from_collateral` breaks that premise: it debits
/// `collateral` and parks the principal on the account, where
/// `withdrawal_portions` drains it FIRST - so `draw -> net -> withdraw` walked
/// the entire posted collateral out of a LIVE session through the unguarded
/// leg, in one atomic transaction, and left it running an 8_000_000 line with
/// nothing behind it.
///
/// All three routes are pinned here, because the first fix I tried closed only
/// the first: the principal can be taken as quote, or converted to a tier asset
/// and taken in kind, and either way the session must not be able to re-lever
/// afterwards.
#[tokio::test]
async fn netting_cannot_walk_funded_collateral_below_the_tier_floor() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;
    let floor = LINE / 5; // required_collateral = 2_000_000 = the whole fixture stake

    // The direct route was always shut: with collateral AT the floor there is
    // no pool-leg headroom, so not one unit comes out.
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, 1u64)),
    );
    let error = fixture.call_account(vec![withdraw], 2).await.unwrap_err();
    assert!(
        error.to_string().contains("BelowTierCollateral"),
        "the pool leg must still hold the floor: {error:#}"
    );

    // Route 1 - net, then take the principal out as quote through the account
    // leg. This is the one that used to succeed.
    let drawn = 1_624_999u64;
    let draw = fixture.draw_call(drawn);
    let net = fixture.repay_from_collateral_call(drawn);
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, drawn)),
    );
    let error = fixture
        .call_account(vec![draw, net, withdraw], 6)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("BelowTierCollateral"),
        "the account leg must hold the same floor: {error:#}"
    );

    // Nothing landed: the whole batch reverted, so the session is untouched.
    let session = fixture.session().await;
    assert_eq!(session.collateral, COLLATERAL);
    assert_eq!(session.drawn_quote, 0);
    assert_eq!(fixture.account_balance(fixture.collateral_asset).await, 0);

    // Route 2 - net, convert the principal into a tier asset, then take it out
    // in kind. The floor reads `collateral`, never the withdrawn asset, so
    // changing the principal's clothes buys nothing.
    let quantity = 500_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(1_000_000);
    let net = fixture.repay_from_collateral_call(1_000_000);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, 1_000_000);
    fixture
        .call_account(vec![draw, net, buy, fixture.settle_book_call()], 3)
        .await
        .unwrap();
    let session = fixture.session().await;
    assert_eq!(session.collateral, COLLATERAL - 1_000_000);
    assert!(
        session.collateral < floor,
        "the walk did put it under the floor"
    );
    assert_eq!(fixture.account_balance(fixture.base_asset).await, quantity);

    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let error = fixture.call_account(vec![withdraw], 2).await.unwrap_err();
    assert!(
        error.to_string().contains("BelowTierCollateral"),
        "an in-kind exit must not escape the floor either: {error:#}"
    );

    // Route 3 - and a session sitting under the floor cannot re-lever into the
    // pool's own capital, because the line it would draw against is the one the
    // collateral no longer earns. `k` is still 8_000_000 of line here.
    assert_eq!(session.credit_line, LINE - LINE / 5 + session.collateral);
    let redraw = fixture.draw_call(session.credit_line);
    fixture.call_account(vec![redraw], 2).await.unwrap();
    let levered = fixture.session().await;
    assert_eq!(levered.drawn_quote, levered.credit_line);
    // It IS reachable - the floor guards value LEAVING, not borrowing - but the
    // principal never left, so it is still sitting in `holdings` backing the
    // draw, and the session is exactly as healthy as before.
    assert!(
        !fixture.is_liquidatable().await,
        "the netted principal is still on the account, so the session is sound"
    );
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, 1u64)),
    );
    let error = fixture.call_account(vec![withdraw], 2).await.unwrap_err();
    assert!(
        error.to_string().contains("QuoteOutstanding"),
        "and it still cannot take anything out: {error:#}"
    );
}

/// Control for the memo ledger across a long interleaving: three
/// `draw -> repay_from_collateral` cycles build a 3_000_000 memo while OUTSIDE
/// top-ups (which are not share-bearing and never touch the memo) keep the
/// session above its floor. The pile is then traded into a real 1_500_000 of
/// profit and taken out. The platform must charge its share on the profit and
/// on nothing else.
#[tokio::test]
async fn repeated_netting_with_outside_top_ups_still_taxes_only_profit() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    // Headroom first, so the nettings never drive the session under its floor.
    fixture.fund_collateral(4_000_000).await;
    let mut netted = 0u64;
    for _ in 0..3 {
        let draw = fixture.draw_call(1_000_000);
        let net = fixture.repay_from_collateral_call(1_000_000);
        fixture.call_account(vec![draw, net], 2).await.unwrap();
        netted += 1_000_000;
    }
    let session = fixture.session().await;
    assert_eq!(session.collateral, COLLATERAL + 4_000_000 - netted);
    assert_eq!(session.drawn_quote, 0);
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        netted
    );

    // Trade the netted pile into a genuine 1_500_000: buy at 2.0, sell at 3.0.
    let quantity = 1_500_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, netted);
    fixture
        .call_account(vec![buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    let sale = 4_500_000u64;
    fixture
        .rest_order(3_000_000, quantity, fixture.collateral_asset, sale)
        .await;
    let sell = fixture.book_call(3_000_000, quantity, fixture.base_asset, quantity);
    fixture
        .call_account(vec![sell, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        sale
    );

    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, sale)),
    );
    let response = fixture.call_account(vec![withdraw], 3).await.unwrap();
    let withdrawn = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<MarginWithdrawn>(&response.tx_status.receipts)
        .unwrap();
    // 10% of the 1_500_000 earned, and nothing on the 3_000_000 of principal
    // three separate nettings parked on the account.
    assert_eq!(
        withdrawn[0].share_qty,
        (sale - netted) / 10,
        "the memo must survive repeated nettings and outside top-ups intact"
    );
}

/// A voluntary close settles at PAR, and par is only the honest price when the
/// pool is owed nothing. `settle_session` used to gate on the IN-KIND debt index
/// alone, so a user who never called `borrow` closed with an empty index while
/// still owing the entire quote draw - and took the `liq_price_factor` haircut
/// with him on a session a keeper was already entitled to seize. Measured at
/// the time: 200_000 to the owner against the 118_000 a keeper would have left
/// him, exactly 1% of the 8_200_000 position.
///
/// Both halves of "owed" are now required at zero, matching `withdraw` and
/// self-funding. The keeper's price is what the pool keeps.
#[tokio::test]
async fn a_voluntary_close_is_refused_while_the_quote_draw_is_outstanding() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let drawn = 10_000_000u64;
    let quantity = 5_000_000_000u64;
    fixture
        .rest_order(2_000_000, quantity, fixture.base_asset, quantity)
        .await;
    let draw = fixture.draw_call(drawn);
    let buy = fixture.book_call(2_000_000, quantity, fixture.collateral_asset, drawn);
    fixture
        .call_account(vec![draw, buy, fixture.settle_book_call()], 2)
        .await
        .unwrap();

    // Base to 1.64: the position marks 8_200_000 against a 10_000_000 draw, and
    // the session crosses the liquidation line.
    fixture
        .publish_base_price(1_640_000_000_000_000_000u128)
        .await;
    assert!(fixture.is_liquidatable().await);
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_debts(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        "no in-kind debt was ever created - only a quote draw"
    );

    // The empty in-kind index is no longer enough.
    let error = fixture
        .account
        .methods()
        .close_session(vec![])
        .with_contracts(&[
            &fixture.deployment.pool,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("QuoteOutstanding"),
        "a par close must not be available while the pool is still owed cash: {error:#}"
    );

    // Netting every unit of collateral does not buy the par exit either - the
    // draw outruns the collateral, so some of it survives.
    let repay = fixture.repay_from_collateral_call(COLLATERAL);
    fixture.call_account(vec![repay], 0).await.unwrap();
    let after = fixture.session().await;
    assert_eq!(after.collateral, 0);
    assert_eq!(after.drawn_quote, drawn - COLLATERAL);
    let error = fixture
        .account
        .methods()
        .close_session(vec![])
        .with_contracts(&[
            &fixture.deployment.pool,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .with_variable_output_policy(VariableOutputPolicy::EstimateMinimum)
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("QuoteOutstanding"),
        "still owed 8_000_000: {error:#}"
    );

    // And the keeper's exit is right there, priced with the haircut the pool
    // needs to unwind a basket it did not choose to hold.
    let closed = fixture.closed_event(&fixture.liquidate().await);
    assert_eq!(closed.reason, SettlementReason::Liquidation);
    assert_eq!(closed.bad_debt, 0);
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
}

/// The in-kind sibling of the quote netting, and the position it exists for: a
/// short that moved against the user. He borrowed the base and sold it; to
/// close in kind he must BUY it back at a price he can no longer afford, and
/// every clean exit - `withdraw`, self-funding, the voluntary close - demands an
/// empty debt index. This converts the obligation straight out of collateral,
/// priced at the ASK because buying it back is what the pool must now do.
#[tokio::test]
async fn repay_base_from_collateral_closes_a_short_the_user_cannot_buy_back() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let quantity = 1_000_000_000u64;
    let sale = 2_000_000u64;
    // What the position marks at the ask is exactly what the pool CHARGES:
    // the PLAIN ask, no `liq_price_factor` widening. The conversion's whole
    // premium over the mark is `BASE_REPAY_FEE_PPM`, nothing else.
    let marked = 3_000_000u64;
    let charged = marked;
    let fee = charged / 10_000; // 100 ppm of an even value, no rounding
    // Headroom, so the whole short can be closed from collateral.
    fixture.fund_collateral(4_000_000).await;
    let funded = COLLATERAL + 4_000_000;

    // Short: borrow the base and sell it at 2.0.
    fixture
        .rest_order(2_000_000, quantity, fixture.collateral_asset, sale)
        .await;
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let sell = fixture.book_call(2_000_000, quantity, fixture.base_asset, quantity);
    fixture
        .call_account(vec![borrow, sell, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    assert_eq!(fixture.debt(fixture.base_asset).await, quantity);
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        sale
    );

    // The base rises by half. Buying it back costs 3_000_000 against the
    // 2_000_000 the sale raised - he is 1_000_000 short and holds no base.
    fixture
        .publish_base_price(3_000_000_000_000_000_000u128)
        .await;
    let pool_cash_before = fixture.pool_balance(fixture.collateral_asset).await;
    let account_cash_before = fixture.account_balance(fixture.collateral_asset).await;
    let platform_cash_before = fixture
        .deployer
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();

    // The fee leaves in this call now, so the transaction carries an output for
    // it - the same builder change prolongation needed.
    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, quantity);
    let response = fixture.call_account(vec![repay], 1).await.unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<BaseDebtRepaidFromCollateral>(
            &response.tx_status.receipts,
        )
        .unwrap();

    assert_eq!(events.len(), 1);
    assert_eq!(events[0].asset_id, fixture.base_asset);
    assert_eq!(events[0].amount, quantity);
    // Struck at the ASK, not the bid: closing a short is a purchase.
    assert_eq!(events[0].ask, U256::from(3_000_000_000_000_000_000u64));
    assert_eq!(
        events[0].value, charged,
        "the plain ask, with no liq_price_factor widening"
    );
    // 100 ppm of the charged value - one basis point, the order book's scale.
    assert_eq!(events[0].fee, fee);
    assert_eq!(events[0].debt_total, 0);
    assert_eq!(events[0].decapitalised_total, charged);
    assert_eq!(events[0].from_capitalised, 0);

    let after = fixture.session().await;
    assert_eq!(after.collateral, funded - charged);
    // The fee is charged BESIDE the ledger - NOT debited from `collateral` as
    // well, which would bill it twice. It is now also PAID in this same call,
    // and `fees_accrued` records both facts with one number.
    assert_eq!(after.fees_accrued, fee);
    assert_eq!(
        after.credit_line,
        LINE - LINE / 5 + after.collateral - after.fees_accrued
    );
    assert_eq!(fixture.debt(fixture.base_asset).await, 0);
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_debts(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        "the debt index must be clear, which is what unblocks every exit"
    );
    // The CONVERSION still moves no coins - the debt is extinguished against
    // the ledger, exactly like its quote sibling. The only thing that leaves is
    // the fee, straight to the platform, which is the whole of the difference
    // from the accrual model.
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        pool_cash_before - fee
    );
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        platform_cash_before + u128::from(fee)
    );
    // The account is untouched either way: the fee comes out of the pool's
    // balance against the user's collateral claim, never off his own cash.
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        account_cash_before
    );

    // And the clean exit is open now. He shorted at 2.0 and closed at 3.0, so
    // he is down 1_000_000 plus the 300 fee - and the platform collects nothing
    // FURTHER, because it already has the fee and a loss carries no share.
    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let closed = fixture.closed_event(&fixture.close_session().await);
    assert_eq!(closed.reason, SettlementReason::UserClose);
    assert_eq!(closed.bad_debt, 0);
    // The fee was collected at the repayment, so the close claims nothing.
    assert_eq!(closed.platform_total, 0);
    assert_eq!(closed.fees_accrued, fee);
    // 6_000_000 in, the short cost 1_030_304 more to close than the sale
    // raised, and the platform took the 304 fee and nothing else - a loss
    // carries no profit share. The parent's cheque is UNCHANGED by paying the
    // fee earlier: settlement takes `fees_accrued` off the funded cash instead
    // of claiming it, and the two cancel to the unit.
    let expected = funded - (charged - sale) - fee;
    assert_eq!(
        closed.payout_parent,
        vec![(fixture.collateral_asset, expected)]
    );
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        parent_before + u128::from(expected)
    );
    let _ = marked;
}

/// The guards, and the rounding that stops the fee being sliced away. Charged
/// on the quote value and rounded UP, so a repayment small enough that 100 ppm
/// floors to zero still pays one unit - the rule every other fee here follows.
#[tokio::test]
async fn repay_base_from_collateral_guards_its_inputs_and_rounds_the_fee_up() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let quantity = 1_000_000_000u64;
    fixture.fund_collateral(4_000_000).await;
    fixture
        .rest_order(2_000_000, quantity, fixture.collateral_asset, 2_000_000)
        .await;
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let sell = fixture.book_call(2_000_000, quantity, fixture.base_asset, quantity);
    fixture
        .call_account(vec![borrow, sell, fixture.settle_book_call()], 2)
        .await
        .unwrap();

    // The quote leg is not an in-kind debt and nets without a price.
    let repay = fixture.repay_base_from_collateral_call(fixture.collateral_asset, 1);
    let error = fixture.call_account(vec![repay], 1).await.unwrap_err();
    assert!(
        error.to_string().contains("UseRepayQuote"),
        "the collateral asset must be routed to the quote netting: {error:#}"
    );

    // Bounded by the debt in both directions.
    for bad in [0u64, quantity + 1] {
        let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, bad);
        let error = fixture.call_account(vec![repay], 1).await.unwrap_err();
        assert!(
            error.to_string().contains("OverRepay"),
            "unexpected error for amount {bad}: {error:#}"
        );
    }

    // A sliver: 2_500_000 base units at 2.0 is 5_000 of quote, and 100 ppm of
    // that is 0.5 - which must round UP, not away.
    let sliver = 2_500_000u64;
    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, sliver);
    let response = fixture.call_account(vec![repay], 1).await.unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<BaseDebtRepaidFromCollateral>(
            &response.tx_status.receipts,
        )
        .unwrap();
    // 5_000 at the plain ask - the charge, with no widening on top.
    assert_eq!(events[0].value, 5_000);
    assert_eq!(events[0].fee, 1, "a floored fee would be free");
    assert_eq!(events[0].debt_total, quantity - sliver);
    assert_eq!(fixture.session().await.fees_accrued, 1);

    // And it cannot spend collateral the session does not have: the remaining
    // debt marks well past the funded balance once the price runs.
    fixture
        .publish_base_price(100_000_000_000_000_000_000u128)
        .await;
    let repay =
        fixture.repay_base_from_collateral_call(fixture.base_asset, quantity - sliver);
    let error = fixture.call_account(vec![repay], 1).await.unwrap_err();
    assert!(
        error.to_string().contains("InsufficientBalance"),
        "collateral must bound the conversion: {error:#}"
    );
}

// ---------------------------------------------------------------------------
// RED TEAM: adversarial coverage for `repay_base_from_collateral`.
//
// Every test below was written to BREAK the new call, not to document it. The
// ones that fail are findings; the ones that pass are attacks the contract
// turned away and are kept as regression cover.
// ---------------------------------------------------------------------------

/// ACCEPTED BEHAVIOUR, exactly bounded. `repay_base_from_collateral` pays the
/// ORACLE ASK with NO haircut and carries no health gate, so the same
/// underwater short run twice - seized by a keeper, and escaped through the
/// conversion - pays the owner MORE on the escape. What he keeps is the
/// `liq_price_factor` provision a seizure would have collected, less the
/// conversion's own fee.
///
/// This is the design's chosen trade, not a finding: the escape hands the pool
/// a clean quote credit instead of a basket to unwind, and the ppm fee is the
/// whole price of that convenience. The test pins the giveaway to the exact
/// provision-minus-fee difference so a pricing regression on either side -
/// the conversion or the settlement - moves a number someone has to look at.
#[tokio::test]
async fn red_team_a_liquidatable_short_buys_a_par_exit_out_of_the_keepers_hands() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;

    // The same journey both times, and the session is underwater on the PRICE
    // rather than on fees - which is what keeps the par exit affordable.
    //
    // The two conditions pull against each other. Liquidatable means
    // `V = k + collateral + proceeds - debt < k + maintenance`; affordable
    // means `debt + fee <= collateral`, since the fee leaves the pool the
    // moment it is charged. Together they demand `proceeds < maintenance`, so
    // the short must be SMALL and the move against it LARGE: 100_000_000 base
    // sold at 2.0 for 200_000, then marked at 19.6 for a 1_960_000 debt
    // against 2_000_000 of collateral. `V` lands at 8_240_000, under the
    // tier's 8_250_000 threshold, and the 196 fee still fits.
    async fn underwater_short(escaped: bool) -> (SessionClosed, u64) {
        let mut fixture = PropFixture::new().await;
        let quantity = 100_000_000u64;

        fixture
            .rest_order(2_000_000, quantity, fixture.collateral_asset, 200_000)
            .await;
        let borrow = fixture.pool_call(
            fn_selector!(borrow(AssetId, u64)),
            0,
            AssetId::default(),
            Some(call_data!(fixture.base_asset, quantity)),
        );
        let sell = fixture.book_call(2_000_000, quantity, fixture.base_asset, quantity);
        fixture
            .call_account(vec![borrow, sell, fixture.settle_book_call()], 2)
            .await
            .unwrap();

        fixture
            .publish_base_price(19_600_000_000_000_000_000u128)
            .await;

        assert_eq!(fixture.session_value().await, 8_240_000);
        assert!(
            fixture.is_liquidatable().await,
            "the keeper must already own this session or the test means nothing"
        );

        let parent_before = fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap();
        let closed = if escaped {
            let repay =
                fixture.repay_base_from_collateral_call(fixture.base_asset, quantity);
            fixture.call_account(vec![repay], 1).await.unwrap();
            // The escape does not even pretend to fix the session's health: it
            // is STILL under the liquidation line the instant before it closes
            // itself at par.
            assert!(
                fixture.is_liquidatable().await,
                "the par exit is taken by a session the keeper still owns"
            );
            fixture.closed_event(&fixture.close_session().await)
        } else {
            fixture.closed_event(&fixture.liquidate().await)
        };
        let parent_after = fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap();
        (closed, (parent_after - parent_before) as u64)
    }

    let (seized, seized_paid) = underwater_short(false).await;
    let (escaped, escaped_paid) = underwater_short(true).await;

    assert_eq!(seized.reason, SettlementReason::Liquidation);
    assert_eq!(escaped.reason, SettlementReason::UserClose);
    assert_eq!(seized.bad_debt, 0);
    assert_eq!(escaped.bad_debt, 0);

    // The escape pays the owner exactly the provision the seizure would have
    // collected, less the conversion fee. The debt marks at 1_960_000; a
    // seizure charges it widened to ceil(1_960_000 * 10_000 / 9_900)
    // = 1_979_798, the conversion charges the plain mark plus its 196 fee.
    let provision = 1_979_798u64 - 1_960_000;
    let fee = 196u64;
    assert_eq!(
        escaped_paid,
        seized_paid + provision - fee,
        "the conversion must sell the liquidation provision for its fee and \
         nothing else (seized event {seized:#?}, escaped event {escaped:#?})"
    );
}

/// ACCEPTED BEHAVIOUR, and the exact opposite of what the quote netting pins:
/// a base repay CAN lift a session out of the keeper's hands.
///
/// Closing a base debt removes that debt's `absorption_cost`, and the live
/// liquidation threshold is `k + max(absorption_cost, maintenance)`. Above the
/// maintenance floor the threshold therefore FALLS by roughly 101 bps of the
/// value repaid, while `V` falls only by the conversion's ppm fee - charged at
/// the PLAIN ask, the call gives up the neutrality the widened ask used to
/// buy, and a session just past the line steps back over it. Accepted for the
/// same reason the par exit is: the pool trades a basket it would have had to
/// unwind for a clean quote credit, so an owner de-risking his own session is
/// the outcome the pool wants, not an attack on it.
#[tokio::test]
async fn red_team_repay_base_from_collateral_unliquidates_a_session_the_keeper_owns() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    // A short big enough that the debt's own absorption cost, not the tier's
    // fixed 250_000 maintenance, is what sets the liquidation threshold.
    let quantity = 6_500_000_000u64;
    fixture.fund_collateral(11_260_000).await;
    fixture
        .rest_order(2_000_000, quantity, fixture.collateral_asset, 13_000_000)
        .await;
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let sell = fixture.book_call(2_000_000, quantity, fixture.base_asset, quantity);
    fixture
        .call_account(vec![borrow, sell, fixture.settle_book_call()], 2)
        .await
        .unwrap();

    // The base doubles. The debt marks at 26_000_000 and its absorption cost
    // (262_627) overtakes the tier's maintenance floor.
    fixture
        .publish_base_price(4_000_000_000_000_000_000u128)
        .await;
    let before = fixture.lines().await;
    let threshold_before = before.threshold.as_u128() as u64;
    let value_before = fixture.session_value().await;
    assert!(
        fixture.is_liquidatable().await,
        "the keeper must already own this session or the test means nothing"
    );

    // 600_000 of collateral - 2.3% of the marked debt - and a 60 unit fee.
    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, 150_000_000);
    let response = fixture.call_account(vec![repay], 1).await.unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<BaseDebtRepaidFromCollateral>(
            &response.tx_status.receipts,
        )
        .unwrap();
    let value = events[0].value;
    let fee = events[0].fee;

    // The charge is the plain mark: 150_000_000 base at 4.0 is 600_000, and
    // the fee is 100 ppm of it.
    assert_eq!(value, 600_000);
    assert_eq!(fee, 60);

    let after = fixture.lines().await;
    let threshold_after = after.threshold.as_u128() as u64;
    let value_after = fixture.session_value().await;
    // The two sides of the escape, each pinned to its own arithmetic: `V`
    // falls by exactly the fee (the repay itself swaps 600_000 of collateral
    // for 600_000 of debt at the same plain mark), while the threshold gives
    // up the repaid slice's whole absorption provision. The provision outruns
    // the fee ~100:1, which is precisely what lets the session step back over
    // the line.
    assert_eq!(value_after, value_before - i128::from(fee));
    let released = threshold_before - threshold_after;
    assert!(
        released > fee,
        "the release must outrun the fee for the escape to exist: \
         released {released}, fee {fee}"
    );
    assert!(
        !fixture.is_liquidatable().await,
        "the plain-ask conversion de-risks the session past the line; value \
         {value}, fee {fee}, threshold {threshold_before} -> {threshold_after}"
    );

    // The keeper's exit is genuinely closed, on chain and not just in the
    // reader: the seizure reverts and the session lives on.
    let error = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .liquidate(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
        .unwrap_err();
    assert!(
        error.to_string().contains("NotLiquidatable"),
        "the keeper must be refused after the escape: {error:#}"
    );
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .has_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
}

/// An EXPIRED session must not be able to pick its own mark. `expire_session`
/// prices the SAME obligation at `liq_price_factor`, so leaving this call open
/// past the deadline would be a race between the owner and the keeper over who
/// gets to choose it - which is why this one carries `require_live` where its
/// value-neutral quote sibling does not.
///
/// The in-kind `repay` stays ungated, so a user holding the asset is never
/// trapped by the liveness gate.
#[tokio::test]
async fn red_team_an_expired_short_cannot_pick_its_own_mark() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let quantity = 1_000_000_000u64;
    fixture.fund_collateral(4_000_000).await;
    fixture
        .rest_order(2_000_000, quantity, fixture.collateral_asset, 2_000_000)
        .await;
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let sell = fixture.book_call(2_000_000, quantity, fixture.base_asset, quantity);
    fixture
        .call_account(vec![borrow, sell, fixture.settle_book_call()], 2)
        .await
        .unwrap();

    // Outlive the pool session with the account's own signing session, so the
    // clock below expires only the thing under test.
    let session = fixture.session().await;
    fixture
        .account
        .methods()
        .set_session(ParallelSessionArgs {
            nonce: U256::one(),
            session_id: Identity::Address(fixture.user.address()),
            expiry: Time {
                unix: session.expires_at + 86_400,
            },
            contract_ids: vec![],
        })
        .with_contract_ids(&[fixture.deployment.oracle_id])
        .call()
        .await
        .unwrap();

    let provider = fixture.outsider.try_provider().unwrap();
    let latest = provider
        .latest_block_time()
        .await
        .unwrap()
        .expect("local chain has a latest block time");
    let expired_time = latest
        .checked_add_signed(chrono::TimeDelta::seconds(
            (session.expires_at.saturating_sub(latest.timestamp() as u64) + 1) as i64,
        ))
        .expect("test expiry timestamp is representable");
    provider
        .produce_blocks(1, Some(expired_time))
        .await
        .unwrap();

    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, quantity);
    let error = fixture.call_account(vec![repay], 1).await.unwrap_err();
    assert!(
        error.to_string().contains("SessionEnded"),
        "an expired session must not choose the mark its keeper would have set: {error:#}"
    );

    // The keeper's exit is there, and it applies the forced haircut.
    expire_fixture_session(&fixture).await;
    assert!(
        !fixture
            .deployment
            .pool
            .methods()
            .has_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );
}

/// A wide oracle spread cannot be farmed. Both legs are
/// checked: a bare short, where the call must charge the same ASK the risk gate
/// already marks the debt at, so `V` moves by the fee alone; and a debt fully
/// offset by a holding of the same asset, where `portfolio_legs` nets the two to
/// zero but the call charges the ask anyway and leaves the survivor marked at
/// the BID - the user eats the spread and the pool keeps it.
#[tokio::test]
async fn red_team_a_wide_oracle_spread_is_charged_on_the_ask_and_cannot_be_farmed() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let quantity = 1_000_000_000u64;
    fixture.fund_collateral(18_000_000).await;
    // Bid 2.0, ask 3.0 - a full point of spread, which `publish_base_price`
    // cannot express.
    fixture
        .deployment
        .price_feed
        .methods()
        .publish_prices(vec![PriceInput {
            asset: fixture.base_asset,
            bid: 2_000_000_000_000_000_000u128,
            ask: 3_000_000_000_000_000_000u128,
            timestamp: fixture.next_publish_time(),
        }])
        .call()
        .await
        .unwrap();

    // Leg one: a bare short. Borrow, sell at 2.0, repay from collateral.
    fixture
        .rest_order(2_000_000, quantity, fixture.collateral_asset, 2_000_000)
        .await;
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let sell = fixture.book_call(2_000_000, quantity, fixture.base_asset, quantity);
    fixture
        .call_account(vec![borrow, sell, fixture.settle_book_call()], 2)
        .await
        .unwrap();

    let before = fixture.session_value().await;
    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, quantity);
    let response = fixture.call_account(vec![repay], 1).await.unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<BaseDebtRepaidFromCollateral>(
            &response.tx_status.receipts,
        )
        .unwrap();
    assert_eq!(
        events[0].ask,
        U256::from(3_000_000_000_000_000_000u64),
        "the sell side of the book is what a buy-back costs"
    );
    // 3_000_000 at the plain ask - the ASK is what a buy-back costs, and
    // with no widening the fee is the only charge over the mark.
    assert_eq!(
        events[0].value, 3_000_000,
        "priced at the ask, never the bid or a mid"
    );
    assert_eq!(events[0].fee, 300);
    // The gate marks this debt at the same plain ask the charge uses, so the
    // conversion is V-neutral except for the fee.
    assert_eq!(fixture.session_value().await, before - 300);

    // Leg two: a debt fully covered by a holding of the same asset. The gate
    // nets them to zero; the call still charges the ask and leaves the coins
    // marked at the bid.
    let before = fixture.session_value().await;
    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();
    assert_eq!(
        fixture.session_value().await,
        before,
        "a debt covered in kind is worth nothing to the gate either way"
    );
    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, quantity);
    fixture.call_account(vec![repay], 1).await.unwrap();
    assert_eq!(
        fixture.session_value().await,
        before - (3_000_000 - 2_000_000) - 300,
        "the survivor is marked at the BID while the charge is the ASK, so the \
         user pays the whole spread plus the fee to convert a self-covered debt"
    );
}

/// Slicing a repayment cannot beat doing it once. Both the
/// quote value and the fee round UP per call, so N slices cost at least what one
/// call costs, and a dust slice pays a 100% fee rather than a free one.
#[tokio::test]
async fn red_team_slicing_a_base_repay_never_beats_doing_it_once() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;

    async fn short_then_repay(slices: u64) -> (u64, u64) {
        let mut fixture = PropFixture::new().await;
        let quantity = 1_000_000_000u64;
        fixture.fund_collateral(4_000_000).await;
        fixture
            .rest_order(2_000_000, quantity, fixture.collateral_asset, 2_000_000)
            .await;
        let borrow = fixture.pool_call(
            fn_selector!(borrow(AssetId, u64)),
            0,
            AssetId::default(),
            Some(call_data!(fixture.base_asset, quantity)),
        );
        let sell = fixture.book_call(2_000_000, quantity, fixture.base_asset, quantity);
        fixture
            .call_account(vec![borrow, sell, fixture.settle_book_call()], 2)
            .await
            .unwrap();

        let before = fixture.session().await.collateral;
        let slice = quantity / slices;
        for index in 0..slices {
            let amount = if index + 1 == slices {
                quantity - slice * (slices - 1)
            } else {
                slice
            };
            let repay =
                fixture.repay_base_from_collateral_call(fixture.base_asset, amount);
            fixture.call_account(vec![repay], 1).await.unwrap();
        }
        let after = fixture.session().await;
        assert_eq!(fixture.debt(fixture.base_asset).await, 0);
        (before - after.collateral, after.fees_accrued)
    }

    let (one_value, one_fee) = short_then_repay(1).await;
    let (many_value, many_fee) = short_then_repay(7).await;
    // 2_000_000 at the plain ask; 100 ppm of that is 200.
    assert_eq!(one_value, 2_000_000);
    assert_eq!(one_fee, 200);
    assert!(
        many_value >= one_value && many_fee >= one_fee,
        "seven slices cost {many_value}/{many_fee} against {one_value}/{one_fee} for one"
    );

    // And dust is never free: one base unit is worth a fraction of a collateral
    // unit, and both the value and the fee round up to one.
    let mut fixture = PropFixture::new().await;
    let quantity = 1_000_000_000u64;
    fixture.fund_collateral(4_000_000).await;
    fixture
        .rest_order(2_000_000, quantity, fixture.collateral_asset, 2_000_000)
        .await;
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let sell = fixture.book_call(2_000_000, quantity, fixture.base_asset, quantity);
    fixture
        .call_account(vec![borrow, sell, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, 1);
    let response = fixture.call_account(vec![repay], 1).await.unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<BaseDebtRepaidFromCollateral>(
            &response.tx_status.receipts,
        )
        .unwrap();
    // One base unit marks at 1 after the round-up.
    assert_eq!(events[0].value, 1);
    assert_eq!(events[0].fee, 1, "dust pays a whole unit, never zero");
}

/// BOUNDARY. `withdraw` calls the tier's entry ticket a STANDING
/// floor - "no withdrawal may leave the session funded below it" - and
/// `netting_cannot_walk_funded_collateral_below_the_tier_floor` is the attack
/// that made it unconditional. `repay_base_from_collateral` walks straight past
/// it: it is bounded by `value <= session.collateral` and by nothing else, so it
/// takes funded collateral to ZERO on a LIVE session, which then still draws its
/// whole 8_000_000 line with no posted margin behind it.
///
/// `withdraw` still holds the money in - that guard is genuinely unconditional -
/// but the floor itself is no longer standing.
#[tokio::test]
async fn the_tier_floor_bounds_withdrawals_not_conversions() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    // The session opens at exactly the tier's entry ticket, 2_000_000: 1e9
    // base marks at 2_000_000 and is CHARGED at exactly that plain mark.
    let quantity = 1_000_000_000u64;
    assert_eq!(fixture.session().await.collateral, COLLATERAL);

    // Borrow the base and keep it: 2_000_000 of value moves onto the account.
    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();

    // Pay the debt off out of collateral. The tier FLOOR still does not bound
    // this - only the fee does: the 1 bp charged on the closed debt is money
    // leaving for the platform, so the collateral must cover it as well as the
    // principal.
    let base_repay_fee = 200u64;
    fixture.fund_collateral(base_repay_fee).await;
    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, quantity);
    fixture.call_account(vec![repay], 1).await.unwrap();
    let after = fixture.session().await;
    // Everything the floor would have protected is gone - the conversion took
    // the collateral to exactly the fees it owes, far below the tier floor.
    // Everything the floor would have protected is gone: the conversion took
    // the collateral down to exactly the fee it owes, far below the tier
    // floor. What it cannot do is take it BELOW that and leave the platform
    // paid out of the pool's own inventory.
    assert_eq!(after.fees_accrued, base_repay_fee);
    assert_eq!(after.collateral, base_repay_fee);
    assert_eq!(after.credit_line, LINE - LINE / 5);
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .has_session(fixture.child_id)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        "and the session is still live"
    );

    // `withdraw` does hold - its floor guard is phrased on the collateral and
    // fires unconditionally, so the value cannot actually leave this way.
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let error = fixture.call_account(vec![withdraw], 2).await.unwrap_err();
    assert!(
        error.to_string().contains("BelowTierCollateral"),
        "the withdrawal floor must still hold: {error:#}"
    );

    // The session can re-lever against the bare `k` the tier grants for nothing.
    let draw = fixture.draw_call(after.credit_line);
    fixture.call_account(vec![draw], 1).await.unwrap();
    let drawn = fixture.session().await;
    assert_eq!(drawn.drawn_quote, LINE - LINE / 5);
    // The fee it still owes is all that is left of the collateral.
    assert_eq!(drawn.collateral, base_repay_fee);

    // And that is where the pool's protection actually lives. The floor guards
    // value LEAVING - it fired above - not value CONVERTING, exactly as
    // `repay_from_collateral` may net a draw against the last unit of
    // collateral. Flooring the conversion would trap the distressed short this
    // call exists to release. What bounds the risk is the liquidation gate, and
    // it is intact: the moment the position turns, the keeper takes it.
    fixture.publish_base_price(10_000_000_000_000_000u128).await;
    assert!(
        fixture.is_liquidatable().await,
        "a session running on the pool's own capital must be seizable the instant \
         its equity goes"
    );
    let closed = fixture.closed_event(&fixture.liquidate().await);
    assert_eq!(closed.reason, SettlementReason::Liquidation);
}

/// The remaining guards. The pause the call inherits really
/// bites, an asset that was never borrowed has no debt row to close, and the
/// in-kind `repay` really is the ungated escape the pause comment promises.
#[tokio::test]
async fn red_team_the_base_repay_guards_hold_under_a_pause_and_an_unknown_asset() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let quantity = 1_000_000_000u64;
    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();

    // An asset that is not in the tier and was never borrowed has no debt.
    let stranger = AssetId::new([0x77; 32]);
    let repay = fixture.repay_base_from_collateral_call(stranger, 1);
    let error = fixture.call_account(vec![repay], 1).await.unwrap_err();
    assert!(
        error.to_string().contains("OverRepay"),
        "an unborrowed asset has nothing to close: {error:#}"
    );

    fixture
        .deployment
        .pool
        .methods()
        .pause()
        .call()
        .await
        .unwrap();
    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, quantity);
    let error = fixture.call_account(vec![repay], 1).await.unwrap_err();
    assert!(
        error.to_string().contains("Paused"),
        "the marked repay must stop with every other marked operation: {error:#}"
    );

    // The promised escape hatch: in-kind `repay` is ungated, so a user holding
    // the asset is never trapped by the pause.
    let repay_in_kind =
        fixture.pool_call(fn_selector!(repay()), quantity, fixture.base_asset, None);
    fixture.call_account(vec![repay_in_kind], 0).await.unwrap();
    assert_eq!(fixture.debt(fixture.base_asset).await, 0);
}

// ---------------------------------------------------------------------------
// AUDIT: independent review of `repay_base_from_collateral`.
// ---------------------------------------------------------------------------

/// AUDIT - FINDING. `repay_from_collateral` justifies skipping the loan-cap
/// re-check in so many words: "the line falls by at most `amount` while the
/// draw falls by exactly `amount`, so a session inside its cap stays inside
/// it." The in-kind sibling inherits the omission but not the argument.
///
/// `require_loan_cap` prices an in-kind debt at the PLAIN ask (`mark`). This
/// call charges that same mark plus a convenience fee and reprices the line
/// off the reduced collateral. So the measured exposure falls by `mark` while
/// the line falls by `mark + fee` - and the cap slack shrinks by the FEE on
/// every call, with nothing left to notice. A session sitting exactly on its
/// line is left OVER it.
#[tokio::test]
async fn audit_base_repay_leaves_the_session_over_its_loan_cap() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    // 5e8 base marks at 1_000_000 on the plain ask of 2.0 - the exact number
    // `require_loan_cap` adds - so a 9_000_000 draw sits the session on the
    // last unit of its 10_000_000 line.
    let quantity = 500_000_000u64;
    let mark = 1_000_000u64;
    let drawn = 9_000_000u64;

    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 draw = fixture.draw_call(drawn);
    fixture.call_account(vec![draw], 1).await.unwrap();

    let before = fixture.session().await;
    assert_eq!(before.collateral, COLLATERAL);
    assert_eq!(before.credit_line, LINE);
    assert_eq!(before.drawn_quote, drawn);
    // Exactly at the cap: the pool refuses one more unit of exposure.
    let over = fixture.draw_call(1);
    let error = fixture.call_account(vec![over], 1).await.unwrap_err();
    assert!(
        error.to_string().contains("LoanCapExceeded"),
        "the session must start ON its cap for this test to mean anything: {error:#}"
    );

    // Close the whole in-kind debt out of collateral.
    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, quantity);
    let response = fixture.call_account(vec![repay], 1).await.unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<BaseDebtRepaidFromCollateral>(
            &response.tx_status.receipts,
        )
        .unwrap();
    let value = events[0].value;
    let fee = events[0].fee;
    assert_eq!(value, 1_000_000, "the plain mark, no widening");
    assert_eq!(fee, 100, "100 ppm of 1_000_000");

    let after = fixture.session().await;
    assert_eq!(after.collateral, COLLATERAL - value);
    assert_eq!(after.drawn_quote, drawn, "the draw is untouched");
    assert_eq!(fixture.debt(fixture.base_asset).await, 0);

    // The exposure the cap measures is now the draw alone, and the line no
    // longer covers it.
    // collateral 2_000_000 -> 1_000_000, fees_accrued 100: drawn_quote
    // 9_000_000 against a credit_line of 8_999_900, a standing breach of
    // exactly the fee.
    assert!(
        after.drawn_quote > after.credit_line,
        "the loan cap must still hold after a repayment: drawn {} against a line of {}",
        after.drawn_quote,
        after.credit_line
    );
    assert_eq!(
        after.drawn_quote - after.credit_line,
        (value - mark) + fee,
        "the breach is exactly the fee the line gave up and the cap's \
         plain-ask measure never saw"
    );

    // It is a state the session simply sits in: healthy on the gate, refused by
    // every writer that re-checks, and corrected by nobody.
    assert!(
        !fixture.is_liquidatable().await,
        "the over-cap session is not seizable, so the breach persists"
    );
    let draw = fixture.draw_call(1);
    let error = fixture.call_account(vec![draw], 1).await.unwrap_err();
    assert!(error.to_string().contains("LoanCapExceeded"), "{error:#}");
}

/// AUDIT - CLEAN. The `decapitalised` memo this call writes is denominated in
/// quote and consumed by `withdraw`'s COLLATERAL_ASSET leg - a consumer whose
/// stated justification ("principal the netting parked on the account") is not
/// what happened here: the collateral went to extinguish an ASSET debt and
/// nothing was parked anywhere. Run the whole session and count.
///
/// It reconciles to the unit. The memo is not a claim about where the coins
/// went, it is a fixed correction to the settlement profit measure, and
/// `withdraw` removes exactly as much future measured profit as it exempts.
/// Spending it early is arithmetically the same as spending it at close.
#[tokio::test]
async fn audit_base_repay_memo_taxes_exactly_the_realised_gain_through_withdraw() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let quantity = 1_000_000_000u64;
    let sale = 2_000_000u64;
    // Outside money, so none of the collateral is share-bearing `capitalised`
    // and the profit share below has exactly one thing to measure.
    fixture.fund_collateral(8_000_000).await;
    let funded = COLLATERAL + 8_000_000;
    assert_eq!(fixture.session().await.collateral, funded);

    // Short: borrow the base and sell it at 2.0.
    fixture
        .rest_order(2_000_000, quantity, fixture.collateral_asset, sale)
        .await;
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let sell = fixture.book_call(2_000_000, quantity, fixture.base_asset, quantity);
    fixture
        .call_account(vec![borrow, sell, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    assert_eq!(
        fixture.account_balance(fixture.collateral_asset).await,
        sale
    );

    // The base halves, so the short is in the money and the conversion is
    // cheap. Close it from collateral rather than buying the base back.
    fixture
        .publish_base_price(1_000_000_000_000_000_000u128)
        .await;
    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, quantity);
    let response = fixture.call_account(vec![repay], 1).await.unwrap();
    let repaid = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<BaseDebtRepaidFromCollateral>(
            &response.tx_status.receipts,
        )
        .unwrap();
    let value = repaid[0].value;
    let fee = repaid[0].fee;
    assert_eq!(value, 1_000_000);
    assert_eq!(fee, 100);
    assert_eq!(repaid[0].decapitalised_total, value);
    assert_eq!(fixture.session().await.decapitalised, value);
    // What he actually made: the sale raised `sale`, closing cost `value`.
    let realised = sale - value;

    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();

    // Take the whole account balance out while the memo is still live. This is
    // the leg that exempts `from_account` up to the memo.
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, sale)),
    );
    let response = fixture.call_account(vec![withdraw], 4).await.unwrap();
    let withdrawn = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<MarginWithdrawn>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(withdrawn.len(), 1);
    // `fees_accrued` is reserved on the account leg and paid from the pool leg.
    assert_eq!(withdrawn[0].from_account, sale - fee);
    assert_eq!(withdrawn[0].from_pool, fee);
    // 10% of what the memo did NOT exempt.
    assert_eq!(withdrawn[0].share_qty, (sale - fee - value).div_ceil(10));
    // And the withdrawal SPENT the memo. It was paid out here, so settlement
    // must find nothing left to subtract - the correction is applied once
    // whichever call gets to the principal first.
    assert_eq!(fixture.session().await.decapitalised, 0);

    let closed = fixture.closed_event(&fixture.close_session().await);
    assert_eq!(closed.reason, SettlementReason::UserClose);
    assert_eq!(closed.bad_debt, 0);
    // Three collection points now, not two: the share taken at the withdrawal,
    // the share taken at the close, and `fees_accrued` - the conversion fee,
    // which left at the repayment call rather than waiting for settlement.
    // Summing all three is what keeps this a statement about the platform's
    // TAKE rather than about the closing event.
    assert_eq!(closed.fees_accrued, fee);
    let platform_total =
        withdrawn[0].share_qty + closed.platform_total + closed.fees_accrued;
    let parent_gain = (fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap()
        - parent_before) as u64;

    // Nothing created, nothing destroyed.
    assert_eq!(
        parent_gain + platform_total,
        funded + realised,
        "parent {parent_gain} + platform {platform_total} must be the {funded} funded \
         plus the {realised} realised"
    );
    // And the platform's whole take is the share on the REALISED gain plus the
    // conversion fee. The memo neither over- nor under-exempts: the only slack
    // is one unit of ceiling, in the platform's favour.
    // funded 10_000_000, value 1_000_000, fee 100, realised 1_000_000: the
    // share collects at the withdrawal and the close, the fee at the
    // repayment. Paying the fee early moved it out of the closing column and
    // into the repayment column; the total did not move.
    let expected = realised.div_ceil(10) + fee;
    assert!(
        platform_total >= expected && platform_total <= expected + 2,
        "platform took {platform_total} against {expected} = 10% of the {realised} \
         realised plus the {fee} fee (withdraw {}, close {}, repayment {})",
        withdrawn[0].share_qty,
        closed.platform_total,
        closed.fees_accrued
    );
}

/// AUDIT - CLEAN. The uncovered health shape: a debt PARTLY covered in kind, so
/// closing it flips the asset leg from the negative side to the positive one.
/// The keeper's gap must not improve across that flip either - the call
/// charges the ASK while the survivor is only ever marked at the BID, so `V`
/// drops by the spread and the fee while the threshold (pinned to the
/// maintenance floor here) does not move at all.
#[tokio::test]
async fn audit_base_repay_never_narrows_the_gap_when_the_asset_leg_flips_sides() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;

    let quantity = 1_000_000_000u64;
    let sold = 500_000_000u64;
    fixture.fund_collateral(4_000_000).await;

    // Borrow 1e9 and sell HALF: net short 5e8, with 5e8 still held.
    fixture
        .rest_order(2_000_000, sold, fixture.collateral_asset, 1_000_000)
        .await;
    let borrow = fixture.pool_call(
        fn_selector!(borrow(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.base_asset, quantity)),
    );
    let sell = fixture.book_call(2_000_000, sold, fixture.base_asset, sold);
    fixture
        .call_account(vec![borrow, sell, fixture.settle_book_call()], 2)
        .await
        .unwrap();
    assert_eq!(fixture.debt(fixture.base_asset).await, quantity);
    assert_eq!(fixture.account_balance(fixture.base_asset).await, sold);

    let before = fixture.lines().await;
    let before_v = fixture.session_value().await;
    let before_gap = before_v - i128::try_from(before.threshold.as_u128()).unwrap();
    assert_eq!(before_v, 14_000_000);

    // Close the WHOLE debt from collateral. The leg it was on turns into a
    // 5e8 holding.
    let repay = fixture.repay_base_from_collateral_call(fixture.base_asset, quantity);
    let response = fixture.call_account(vec![repay], 1).await.unwrap();
    let events = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<BaseDebtRepaidFromCollateral>(
            &response.tx_status.receipts,
        )
        .unwrap();
    assert_eq!(events[0].value, 2_000_000, "the WHOLE 1e9 at the plain ask");
    assert_eq!(events[0].fee, 200);
    assert_eq!(fixture.debt(fixture.base_asset).await, 0);

    let after = fixture.lines().await;
    let after_v = fixture.session_value().await;
    let after_gap = after_v - i128::try_from(after.threshold.as_u128()).unwrap();
    assert!(
        after_v < before_v,
        "V must fall across the flip: {before_v} -> {after_v}"
    );
    assert!(
        after_gap < before_gap,
        "the gap to the liquidation line must never widen: {before_gap} -> {after_gap}"
    );
    assert_eq!(
        before_gap - after_gap,
        i128::from((events[0].value - 2_000_000) + events[0].fee),
        "the gap gives up exactly the fee - the charge equals the plain mark and \
         the bid/ask spread is zero here, so nothing else is charged"
    );
}

/// A PLAIN registry upgrade — one that knows nothing about margin — must
/// not drop the registry's prop wiring.
///
/// This is the devnet outage, reduced: `deploy_trade_account_registry`
/// rebuilds the registry's implementation blob from a fresh deploy config,
/// and every configurable that config does not repeat reverts to its
/// default. The five `PROP_*` values default to ZERO, so the upgrade
/// leaves `prop_register_contract` CALLing address zero and every margin
/// registration reverts with `ContractNotFound`. Only the margin SYSTEM
/// phase writes those values back, and the ordinary steady state skips it.
///
/// The `default()` half is the point of the test: it pins the bug, so a
/// `live_prop_config` that quietly stopped preserving anything could not
/// pass by asserting a value it never had to restore.
#[tokio::test]
async fn a_plain_registry_upgrade_keeps_the_prop_wiring() {
    use crate::trade_account_registry::{
        TradeAccountRegistryConfigurables,
        TradeAccountRegistryDeployConfig,
        TradeAccountRegistryManager,
    };

    let fixture = PropFixture::new().await;
    let registry = TradeAccountRegistryManager::new(
        fixture.deployer.clone(),
        fixture.deployment.registry_id,
    );
    let oracle_id = fixture.deployment.oracle_id;

    let wiring = async |registry: &TradeAccountRegistryManager<Wallet>| {
        let oracle = registry
            .registry
            .methods()
            .get_prop_oracle_id()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value;
        let account_proxy = registry
            .registry
            .methods()
            .default_prop_bytecode()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value;
        (oracle, account_proxy)
    };

    // The fixture's registry is margin-wired: that is the state an
    // upgrade has to carry across.
    let (live_oracle, live_account_proxy) = wiring(&registry).await;
    assert_eq!(live_oracle, oracle_id);
    assert_ne!(live_account_proxy, ContractId::zeroed());

    // Captured BEFORE the upgrade, exactly as the deploy does it — the
    // values are read off the chain, so a caller that reads them after
    // clobbering them would read zeros back.
    let preserved = registry
        .live_prop_config(TradeAccountRegistryConfigurables::default())
        .await
        .unwrap();

    // THE FIX: a plain upgrade that threads the live wiring through.
    registry
        .upgrade(
            ContractId::zeroed(),
            ContractId::zeroed(),
            &TradeAccountRegistryDeployConfig {
                registry_config: preserved,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    let (oracle_after_fix, proxy_after_fix) = wiring(&registry).await;
    assert_eq!(
        oracle_after_fix, oracle_id,
        "the upgrade must preserve PROP_ACCOUNT_ORACLE_CONTRACT_ID"
    );
    assert_eq!(
        proxy_after_fix, live_account_proxy,
        "the upgrade must preserve DEFAULT_PROP_ACCOUNT_PROXY"
    );

    // THE BUG: the same upgrade built from a bare default config. Zeroed
    // wiring is what made every devnet registration revert.
    registry
        .upgrade(
            ContractId::zeroed(),
            ContractId::zeroed(),
            &TradeAccountRegistryDeployConfig::default(),
        )
        .await
        .unwrap();
    let (oracle_after_bug, proxy_after_bug) = wiring(&registry).await;
    assert_eq!(
        oracle_after_bug,
        ContractId::zeroed(),
        "a default-config upgrade zeroes the oracle - the regression this guards"
    );
    assert_eq!(proxy_after_bug, ContractId::zeroed());

    // And the repair is idempotent from a zeroed registry: nothing is
    // left to read, so the caller must supply the values again — which is
    // precisely why the margin system phase, not the plain upgrade, owns
    // them.
    let carried: Configurables = registry
        .live_prop_config(TradeAccountRegistryConfigurables::default())
        .await
        .unwrap()
        .into();
    assert!(
        carried.offsets_with_data.is_empty(),
        "a zeroed registry has no wiring to carry, and must not invent any"
    );
}

/// A pool's ADDRESS must survive a change to the pool, or an "upgrade"
/// silently FORKS the pool and orphans the funded one.
///
/// The proxy is seeded with a bootstrap blob so its address does not
/// depend on the implementation's CONFIGURABLES — but the bootstrap id is
/// itself a hash of the pool BYTECODE, so anything that moves the
/// derivation moves the pool. That is how devnet ended up with a second,
/// empty pool while the funded one kept every session.
///
/// `salt` stands in for the bytecode here: it is the other input to the
/// same derivation, and unlike the bytecode it can be perturbed without
/// rebuilding contracts. The first half proves the derivation really does
/// move; the second proves `existing_pool` overrides it.
#[tokio::test]
async fn a_pinned_pool_survives_a_derivation_change() {
    let fixture = PropFixture::new().await;
    let funded_pool = fixture.deployment.pool_id;

    // A different derivation input, standing in for a release that
    // changes the pool's bytecode.
    let mut moved = PropDeployConfig::new(fixture.collateral_asset);
    moved.salt = Salt::new([0x5a; 32]);

    // THE BUG, enacted rather than predicted: unpinned, the same system
    // deploys a DIFFERENT pool, leaving `funded_pool` orphaned.
    let derived = PropDeployment::deploy(&fixture.deployer, &moved)
        .await
        .unwrap();
    assert_ne!(
        derived.pool_id, funded_pool,
        "the derivation must actually move, or this test proves nothing"
    );

    // THE FIX: pinned, the same moved derivation resolves the pool that
    // already exists instead of forking again.
    moved.existing_pool = Some(funded_pool);
    let deployed = PropDeployment::deploy(&fixture.deployer, &moved)
        .await
        .unwrap();
    assert_eq!(
        deployed.pool_id, funded_pool,
        "a pinned pool must win over the derivation in the real run"
    );

    // Not merely the same id: the SAME pool, still carrying the fixture's
    // session. A fork would hand back a pristine one.
    let session = PropMarginPoolContract::new(deployed.pool_id, fixture.deployer.clone())
        .methods()
        .get_session(fixture.child_id)
        .simulate(Execution::state_read_only())
        .await
        .unwrap()
        .value;
    assert!(
        session.is_some(),
        "the pinned pool must be the funded one, not a fresh deployment"
    );
}

/// `FeesNotCovered` cannot fire. It is dead, and this pins why.
///
/// The two gates `withdraw` runs, in order, are
///
///   collateral - from_pool - fees_accrued >= required_collateral   (floor)
///   collateral - from_pool                >= fees_accrued          (fees)
///
/// and `validate_tier` proves `required_collateral != 0`. So clearing the
/// floor already means `collateral - from_pool >= required_collateral +
/// fees_accrued`, which is STRICTLY greater than `fees_accrued` — the
/// second gate can never see a value the first did not already pass. That
/// was not true before the floor was measured net of fees; it is now.
///
/// The test drives the state that would once have tripped the fee gate —
/// fees large against collateral, and a withdrawal that would leave the
/// session funded below them — and shows the FLOOR refuses it first, at a
/// far smaller amount than the fee gate would ever have bitten at.
#[tokio::test]
async fn the_fee_cover_gate_is_unreachable_behind_the_net_floor() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;
    let floor = LINE / 5; // required_collateral, the tier's entry ticket

    // Headroom to withdraw from, then fees worth a meaningful slice of it:
    // 100 days at the tier's 6_000 Day price.
    fixture.fund_collateral(1_000_000).await;
    // ONE variable output: the prolongation fee is transferred to the
    // platform payout inside the call.
    fixture
        .call_account(vec![fixture.prolong_call(100)], 1)
        .await
        .unwrap();

    let session = fixture.session().await;
    let collateral = session.collateral;
    let fees = session.fees_accrued;
    assert_eq!(collateral, COLLATERAL + 1_000_000);
    assert_eq!(fees, 600_000, "100 days at the Day price");

    // What each gate would bound the withdrawal at:
    //   floor: collateral - fees - required_collateral
    //   fees : collateral - fees            (far larger)
    let floor_allows = collateral - fees - floor;
    let fees_would_allow = collateral - fees;
    assert!(
        floor_allows < fees_would_allow,
        "the floor must bind first: {floor_allows} vs {fees_would_allow}"
    );

    // One unit past the FLOOR is refused by the floor — not by the fee
    // gate, which is still nowhere near.
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, floor_allows + 1)),
    );
    let error = fixture.call_account(vec![withdraw], 2).await.unwrap_err();
    let rendered = error.to_string();
    assert!(
        rendered.contains("BelowTierCollateral"),
        "the net floor is what binds: {error:#}"
    );
    assert!(
        !rendered.contains("FeesNotCovered"),
        "the fee gate must be unreachable: {error:#}"
    );

    // And exactly the floor's allowance passes, leaving the session funded
    // at the ticket with every fee still covered many times over.
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, floor_allows)),
    );
    fixture.call_account(vec![withdraw], 2).await.unwrap();
    let after = fixture.session().await;
    assert_eq!(after.collateral, collateral - floor_allows);
    assert_eq!(after.collateral - after.fees_accrued, floor);
}

/// A REDEPLOY moves the account implementation every margin account runs.
///
/// `INITIAL_PROP_ACCOUNT_IMPL` reaches storage only through the oracle's
/// one-time `initialize`, and a redeploy skips that branch — so baking a
/// fresh `account_blob_id` into the oracle's configurables and retargeting
/// its proxy, both of which the deploy does and both of which SUCCEED,
/// still left `get_prop_account_impl` answering with the previous blob.
/// Every account kept running the old bytecode while the deploy reported a
/// clean upgrade. This is the same defect the cosigner was given an
/// explicit reconcile for, and the price feed was given `set_price_feed`
/// for; the account implementation was the one left behind.
///
/// The drift is staged by pointing the oracle at a DIFFERENT real blob
/// (`validate_blob` asks only that the blob exists, so the pool's own
/// serves) rather than by perturbing the account bytecode, which has no
/// configurables to move. What the test proves is the reconcile: the
/// deploy must put the pointer back where the run's own artifacts say it
/// belongs, not leave whatever it finds.
#[tokio::test]
async fn a_redeploy_reconciles_the_account_implementation_on_the_oracle() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let fixture = PropFixture::new().await;
    let oracle = &fixture.deployment.oracle;
    let correct = ContractId::from(fixture.deployment.account_blob_id);

    assert_eq!(
        oracle
            .methods()
            .get_prop_account_impl()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(correct),
        "the first deploy initializes the pointer"
    );

    // Drift: some other real blob, as a stale implementation would be.
    let stale = ContractId::from(fixture.deployment.pool_blob_id);
    assert_ne!(stale, correct, "the stand-in must actually differ");
    oracle
        .methods()
        .set_prop_account_impl(stale)
        .call()
        .await
        .unwrap();

    // The same system, deployed again — the oracle already exists, so the
    // `initialize` branch is skipped and only an explicit reconcile can
    // move the pointer back.
    let mut config = PropDeployConfig::new(fixture.collateral_asset);
    config.max_offchain_age_seconds = Some(TEST_MAX_OFFCHAIN_AGE_SECONDS);
    let again = PropDeployment::deploy(&fixture.deployer, &config)
        .await
        .unwrap();
    assert_eq!(
        again.oracle_id, fixture.deployment.oracle_id,
        "the redeploy must resolve the SAME oracle, or this proves nothing"
    );

    assert_eq!(
        oracle
            .methods()
            .get_prop_account_impl()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(correct),
        "the redeploy must put the account implementation back"
    );
}

#[tokio::test]
async fn admin_controls_user_discounts() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let fixture = PropFixture::new().await;
    let user = Identity::Address(fixture.user.address());
    let raw = |tier_id: Option<u64>| {
        let pool = fixture.deployment.pool.clone();
        async move {
            pool.methods()
                .get_user_discount(user, tier_id)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value
        }
    };
    let resolved = |tier_id: u64| {
        let pool = fixture.deployment.pool.clone();
        async move {
            pool.methods()
                .resolve_user_discount(user, tier_id)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value
        }
    };

    // No grant in either slot: the user pays list price everywhere.
    assert_eq!(raw(None).await, None);
    assert_eq!(raw(Some(TIER_ID)).await, None);
    assert_eq!(resolved(TIER_ID).await, None);

    let wide = UserDiscount {
        discount_bps: 2_500,
        scope: DiscountScope::FirstPremium,
    };
    let tier_override = UserDiscount {
        discount_bps: 7_500,
        scope: DiscountScope::AllPremiums,
    };

    // Pricing favours is its OWN role, not a power of office: even the
    // ADMIN is refused until the role is granted.
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .set_user_discount(user, None, Some(wide.clone()))
            .call()
            .await
            .is_err()
    );

    // And the role's door is the admin's alone: a stranger cannot let
    // himself in.
    let manager = Identity::Address(fixture.outsider.address());
    let manager_pool = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone());
    assert!(
        manager_pool
            .methods()
            .grant_role(DISCOUNT_MANAGER_ROLE, manager)
            .call()
            .await
            .is_err()
    );
    fixture
        .deployment
        .pool
        .methods()
        .grant_role(DISCOUNT_MANAGER_ROLE, manager)
        .call()
        .await
        .unwrap();
    assert!(
        fixture
            .deployment
            .pool
            .methods()
            .has_role(DISCOUNT_MANAGER_ROLE, manager)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
    );

    // More than everything cannot be forgiven, in either slot.
    for slot in [None, Some(TIER_ID)] {
        assert!(
            manager_pool
                .methods()
                .set_user_discount(
                    user,
                    slot,
                    Some(UserDiscount {
                        discount_bps: 10_001,
                        scope: DiscountScope::AllPremiums,
                    }),
                )
                .call()
                .await
                .is_err()
        );
    }

    // The user-wide grant lands in its slot and resolves for every tier.
    let response = manager_pool
        .methods()
        .set_user_discount(user, None, Some(wide.clone()))
        .call()
        .await
        .unwrap();
    let events = response
        .decode_logs_with_type::<UserDiscountChanged>()
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].user, user);
    assert_eq!(events[0].tier_id, None);
    assert_eq!(events[0].discount, Some(wide.clone()));
    assert!(events[0].timestamp.unix != 0);
    assert_eq!(raw(None).await, Some(wide.clone()));
    assert_eq!(raw(Some(TIER_ID)).await, None);
    assert_eq!(resolved(TIER_ID).await, Some(wide.clone()));
    assert_eq!(resolved(TIER_ID + 1).await, Some(wide.clone()));

    // A tier override shadows the wide grant WHOLE - rate and scope - for
    // its tier alone, and leaves the wide slot untouched.
    let response = manager_pool
        .methods()
        .set_user_discount(user, Some(TIER_ID), Some(tier_override.clone()))
        .call()
        .await
        .unwrap();
    let events = response
        .decode_logs_with_type::<UserDiscountChanged>()
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].tier_id, Some(TIER_ID));
    assert_eq!(events[0].discount, Some(tier_override.clone()));
    assert_eq!(raw(None).await, Some(wide.clone()));
    assert_eq!(raw(Some(TIER_ID)).await, Some(tier_override.clone()));
    assert_eq!(resolved(TIER_ID).await, Some(tier_override.clone()));
    assert_eq!(resolved(TIER_ID + 1).await, Some(wide.clone()));

    // Clearing the override uncovers the wide grant again...
    let response = manager_pool
        .methods()
        .set_user_discount(user, Some(TIER_ID), None)
        .call()
        .await
        .unwrap();
    let events = response
        .decode_logs_with_type::<UserDiscountChanged>()
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].tier_id, Some(TIER_ID));
    assert_eq!(events[0].discount, None);
    assert_eq!(raw(Some(TIER_ID)).await, None);
    assert_eq!(resolved(TIER_ID).await, Some(wide.clone()));

    // ...and clearing the wide grant leaves list price everywhere.
    let response = manager_pool
        .methods()
        .set_user_discount(user, None, None)
        .call()
        .await
        .unwrap();
    let events = response
        .decode_logs_with_type::<UserDiscountChanged>()
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].tier_id, None);
    assert_eq!(events[0].discount, None);
    assert_eq!(raw(None).await, None);
    assert_eq!(resolved(TIER_ID).await, None);

    // Revocation closes the door as fast as the grant opened it.
    fixture
        .deployment
        .pool
        .methods()
        .revoke_role(DISCOUNT_MANAGER_ROLE, manager)
        .call()
        .await
        .unwrap();
    assert!(
        manager_pool
            .methods()
            .set_user_discount(user, None, Some(wide))
            .call()
            .await
            .is_err()
    );
}

/// A `FirstPremium` grant prices the door and nothing else: the entry premium
/// is discounted and ROUNDED DOWN, while a later prolongation by the same
/// user pays list price.
#[tokio::test]
async fn a_discounted_entry_pays_the_rounded_down_premium() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;
    let parent = Identity::Address(fixture.user.address());
    fixture
        .deployment
        .pool
        .methods()
        .grant_role(
            DISCOUNT_MANAGER_ROLE,
            Identity::Address(fixture.deployer.address()),
        )
        .call()
        .await
        .unwrap();

    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            parent,
            None,
            Some(UserDiscount {
                discount_bps: 2_500,
                scope: DiscountScope::FirstPremium,
            }),
        )
        .call()
        .await
        .unwrap();

    // An entry fee chosen so a quarter off does not divide evenly:
    // 100_001 * 7_500 / 10_000 = 75_000.75, and the user pays 75_000.
    let open_fee = 100_001u64;
    let tier_params = TierParams {
        line: LINE,
        leverage: 5,
        duration: 64_800,
        maintenance_bps: 250,
        open_buffer_bps: 375,
        liq_price_factor: 9_900,
        prolong_fee: [0, 6_000, 76_000, 738_000],
        max_credit_line_bps: 20_000,
        max_price_age: u64::MAX,
        open_fee,
        profit_share_bps: 1_000,
        price_band_bps: 1_000,
    };
    fixture
        .deployment
        .pool
        .methods()
        .publish_tier_version(TIER_ID, tier_params, vec![fixture.order_book.contract_id])
        .with_contract_ids(&[
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .call()
        .await
        .unwrap();

    let child = fixture
        .deployment
        .deploy_account(&fixture.user, parent, 1)
        .await
        .unwrap();
    let account = PropAccountContract::new(child.contract_id(), fixture.user.clone());
    let platform_before = fixture
        .deployer
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let opened_response = account
        .methods()
        .start_session(TIER_ID, COLLATERAL, ProlongPeriod::SixHours)
        .call_params(CallParameters::new(
            COLLATERAL,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .with_contract_ids(&[
            fixture.deployment.oracle_id,
            fixture.deployment.pool_id,
            fixture.deployment.registry_id,
        ])
        .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
        .call()
        .await
        .unwrap();
    let opened = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<SessionOpened>(&opened_response.tx_status.receipts)
        .unwrap();
    assert_eq!(opened.len(), 1);
    assert_eq!(opened[0].open_fee, 75_000);
    assert_eq!(opened[0].fees_accrued, 75_000);
    // The platform was paid the DISCOUNTED figure, and the line prices off
    // the collateral net of it: `k` (8_000_000) + 2_000_000 - 75_000.
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        platform_before + 75_000
    );
    assert_eq!(opened[0].credit_line, 9_925_000);

    // The same user prolongs the FIXTURE session: the grant stops at the
    // door, so the Day fee is the tier's own 6_000, `times` over.
    let prolong = fixture.prolong_call(3);
    let response = fixture.call_account(vec![prolong], 1).await.unwrap();
    let prolonged = response
        .decode_logs_with_type::<SessionProlonged>()
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].fee, 18_000);
}

/// An `AllPremiums` grant reaches prolongation, comes off the whole bill
/// AFTER the `times` multiply, and rounds the fee DOWN. At `10_000` bps the
/// covered premiums are simply free - the period stays offered, because
/// `PeriodNotOffered` judges the tier's list price rather than the user's.
#[tokio::test]
async fn an_all_premiums_discount_prices_prolongation_rounded_down() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;
    let parent = Identity::Address(fixture.user.address());
    fixture
        .deployment
        .pool
        .methods()
        .grant_role(
            DISCOUNT_MANAGER_ROLE,
            Identity::Address(fixture.deployer.address()),
        )
        .call()
        .await
        .unwrap();

    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            parent,
            None,
            Some(UserDiscount {
                discount_bps: 3_333,
                scope: DiscountScope::AllPremiums,
            }),
        )
        .call()
        .await
        .unwrap();

    // Three Days list at 18_000; 18_000 * 6_667 / 10_000 = 12_000.6, so the
    // user pays 12_000 - one round-down on the whole bill, not one per term.
    let times = 3u64;
    let platform_before = fixture
        .deployer
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let pool_before = fixture.pool_balance(fixture.collateral_asset).await;
    let before = fixture.session().await;
    let prolong = fixture.prolong_call(times);
    let response = fixture.call_account(vec![prolong], 1).await.unwrap();
    let prolonged = response
        .decode_logs_with_type::<SessionProlonged>()
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].fee, 12_000);
    assert_eq!(prolonged[0].fees_accrued, 12_000);
    // The discount changes the price of time, never the amount of it.
    assert_eq!(prolonged[0].seconds, 86_400 * times);
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        platform_before + 12_000
    );
    assert_eq!(
        fixture.pool_balance(fixture.collateral_asset).await,
        pool_before - 12_000
    );
    let after = fixture.session().await;
    assert_eq!(after.expires_at, before.expires_at + 86_400 * times);
    assert_eq!(after.fees_accrued, 12_000);

    // Total forgiveness: the same period, free of charge.
    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            parent,
            None,
            Some(UserDiscount {
                discount_bps: 10_000,
                scope: DiscountScope::AllPremiums,
            }),
        )
        .call()
        .await
        .unwrap();
    let prolong = fixture.prolong_call(1);
    let response = fixture.call_account(vec![prolong], 1).await.unwrap();
    let prolonged = response
        .decode_logs_with_type::<SessionProlonged>()
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].fee, 0);
    assert_eq!(prolonged[0].fees_accrued, 12_000);
}

/// A grant pinned to a tier prices that tier alone: on any other tier the
/// same user pays list price.
#[tokio::test]
async fn a_tier_scoped_discount_ignores_other_tiers() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;
    let parent = Identity::Address(fixture.user.address());
    fixture
        .deployment
        .pool
        .methods()
        .grant_role(
            DISCOUNT_MANAGER_ROLE,
            Identity::Address(fixture.deployer.address()),
        )
        .call()
        .await
        .unwrap();

    // Pinned to a tier the session is NOT on: list price.
    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            parent,
            Some(TIER_ID + 1),
            Some(UserDiscount {
                discount_bps: 5_000,
                scope: DiscountScope::AllPremiums,
            }),
        )
        .call()
        .await
        .unwrap();
    let prolong = fixture.prolong_call(1);
    let response = fixture.call_account(vec![prolong], 1).await.unwrap();
    let prolonged = response
        .decode_logs_with_type::<SessionProlonged>()
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].fee, 6_000);

    // Re-pinned to the session's own tier: half the Day fee.
    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            parent,
            Some(TIER_ID),
            Some(UserDiscount {
                discount_bps: 5_000,
                scope: DiscountScope::AllPremiums,
            }),
        )
        .call()
        .await
        .unwrap();
    let prolong = fixture.prolong_call(1);
    let response = fixture.call_account(vec![prolong], 1).await.unwrap();
    let prolonged = response
        .decode_logs_with_type::<SessionProlonged>()
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].fee, 3_000);
    assert_eq!(prolonged[0].fees_accrued, 9_000);
}

/// The two slots at work together. A user-wide grant prices every tier until
/// a tier override shadows it - WHOLE, rate and scope, never a blend - and a
/// ZERO override is the carve-out: that one tier back at list price while the
/// wide grant keeps pricing the rest.
#[tokio::test]
async fn a_tier_override_beats_the_user_wide_grant() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let mut fixture = PropFixture::new().await;
    let parent = Identity::Address(fixture.user.address());
    fixture
        .deployment
        .pool
        .methods()
        .grant_role(
            DISCOUNT_MANAGER_ROLE,
            Identity::Address(fixture.deployer.address()),
        )
        .call()
        .await
        .unwrap();

    // Half off everywhere.
    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            parent,
            None,
            Some(UserDiscount {
                discount_bps: 5_000,
                scope: DiscountScope::AllPremiums,
            }),
        )
        .call()
        .await
        .unwrap();
    let prolong = fixture.prolong_call(1);
    let response = fixture.call_account(vec![prolong], 1).await.unwrap();
    let prolonged = response
        .decode_logs_with_type::<SessionProlonged>()
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].fee, 3_000);

    // A quarter-off override on the session's tier: WORSE than the wide
    // grant, and it still wins - an override is a replacement, not a floor.
    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            parent,
            Some(TIER_ID),
            Some(UserDiscount {
                discount_bps: 2_500,
                scope: DiscountScope::AllPremiums,
            }),
        )
        .call()
        .await
        .unwrap();
    let prolong = fixture.prolong_call(1);
    let response = fixture.call_account(vec![prolong], 1).await.unwrap();
    let prolonged = response
        .decode_logs_with_type::<SessionProlonged>()
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].fee, 4_500);

    // The zero override: this tier carved back to list price while the wide
    // grant stays in force for every other.
    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(
            parent,
            Some(TIER_ID),
            Some(UserDiscount {
                discount_bps: 0,
                scope: DiscountScope::AllPremiums,
            }),
        )
        .call()
        .await
        .unwrap();
    let prolong = fixture.prolong_call(1);
    let response = fixture.call_account(vec![prolong], 1).await.unwrap();
    let prolonged = response
        .decode_logs_with_type::<SessionProlonged>()
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].fee, 6_000);
    assert_eq!(
        fixture
            .deployment
            .pool
            .methods()
            .resolve_user_discount(parent, TIER_ID + 1)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value,
        Some(UserDiscount {
            discount_bps: 5_000,
            scope: DiscountScope::AllPremiums,
        })
    );

    // Clearing the override uncovers the wide grant for this tier again.
    fixture
        .deployment
        .pool
        .methods()
        .set_user_discount(parent, Some(TIER_ID), None)
        .call()
        .await
        .unwrap();
    let prolong = fixture.prolong_call(1);
    let response = fixture.call_account(vec![prolong], 1).await.unwrap();
    let prolonged = response
        .decode_logs_with_type::<SessionProlonged>()
        .unwrap();
    assert_eq!(prolonged.len(), 1);
    assert_eq!(prolonged[0].fee, 3_000);
    assert_eq!(prolonged[0].fees_accrued, 16_500);
}

/// `remove_user_discount` clears the slot it addresses, the same way
/// `set_user_discount` addresses one - a tier's override, or the
/// user-wide grant - behind the same role, and reports through its own
/// event so an audit can tell "priced at zero" from "no longer priced".
///
/// Clearing the wide grant deliberately leaves a tier override standing:
/// an override is the whole price for its tier, so removing the user's
/// discount there means removing that slot too.
#[tokio::test]
async fn removing_a_discount_clears_the_slot_it_addresses() {
    let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
    let fixture = PropFixture::new().await;
    let user = Identity::Address(fixture.user.address());
    const DISCOUNT_MANAGER_ROLE: u64 = 1;
    fixture
        .deployment
        .pool
        .methods()
        .grant_role(
            DISCOUNT_MANAGER_ROLE,
            Identity::Address(fixture.deployer.address()),
        )
        .call()
        .await
        .unwrap();

    let grant = |bps| UserDiscount {
        discount_bps: bps,
        scope: DiscountScope::AllPremiums,
    };
    let resolved = |tier_id: u64| {
        let pool = fixture.deployment.pool.clone();
        async move {
            pool.methods()
                .resolve_user_discount(user, tier_id)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value
        }
    };

    for (slot, bps) in [(None, 1_000u64), (Some(TIER_ID), 5_000)] {
        fixture
            .deployment
            .pool
            .methods()
            .set_user_discount(user, slot, Some(grant(bps)))
            .call()
            .await
            .unwrap();
    }

    // Only the role may remove, exactly as only the role may grant.
    assert!(
        fixture
            .deployment
            .pool
            .clone()
            .with_account(fixture.outsider.clone())
            .methods()
            .remove_user_discount(user, None)
            .call()
            .await
            .is_err()
    );

    // The WIDE grant: gone for every tier it priced, while the override
    // keeps pricing its own.
    let response = fixture
        .deployment
        .pool
        .methods()
        .remove_user_discount(user, None)
        .call()
        .await
        .unwrap();
    let events = response
        .decode_logs_with_type::<UserDiscountsRemoved>()
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].user, user);
    assert_eq!(events[0].tier_id, None);
    assert!(events[0].removed);
    assert!(events[0].timestamp.unix != 0);
    assert_eq!(resolved(TIER_ID).await, Some(grant(5_000)));
    assert_eq!(resolved(TIER_ID + 1).await, None);

    // The OVERRIDE: its tier falls back to list price, since the wide
    // grant is already gone.
    let response = fixture
        .deployment
        .pool
        .methods()
        .remove_user_discount(user, Some(TIER_ID))
        .call()
        .await
        .unwrap();
    let events = response
        .decode_logs_with_type::<UserDiscountsRemoved>()
        .unwrap();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].tier_id, Some(TIER_ID));
    assert!(events[0].removed);
    assert_eq!(resolved(TIER_ID).await, None);

    // Removing an empty slot is a logged no-op, not a revert - an
    // operator clearing twice must not need to care.
    let response = fixture
        .deployment
        .pool
        .methods()
        .remove_user_discount(user, Some(TIER_ID))
        .call()
        .await
        .unwrap();
    let events = response
        .decode_logs_with_type::<UserDiscountsRemoved>()
        .unwrap();
    assert_eq!(events.len(), 1);
    assert!(!events[0].removed);
}