o2-tools 0.4.1-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
//! The prepaid ("Turbo") overlay: forfeited entries, the free
//! performance-gated rollover, blocked top-ups, the atomic v2 publication
//! and the sales switch.
//!
//! Every behaviour here is keyed on the `TurboTerms` sidecar a tier version
//! may carry. The legacy suites prove the other half of the contract: a tier
//! WITHOUT terms — every session the fixture opens — behaves exactly as it
//! always did, and these tests re-prove it in-place where the two cohorts
//! meet (top-ups, the sales switch).

use super::*;
use crate::prop::{
    CollateralForfeited,
    RolloverWithdrawalRecorded,
    SessionRolledOver,
    TierEnabledChanged,
    TierVersionPublishedV2,
    TurboTerms,
};

/// A tier id the fixture never uses, so the fixture's own session stays on
/// its legacy terms while these tests sell the prepaid ones beside it.
const TURBO_TIER_ID: u64 = 7;
/// `line / leverage` — the deposit half of the price, forfeited at close.
const TURBO_DEPOSIT: u64 = 250_000;
/// The fee half of the price, paid to the platform inside the opening call.
const TURBO_FEE: u64 = 25_000;
/// What the user actually sends: the whole price, deposit and fee together.
/// The fee accrues out of it, leaving exactly `required_collateral` funded.
const TURBO_ENTRY: u64 = TURBO_DEPOSIT + TURBO_FEE;
/// 9% of the line: the profit a rollover demands above the anchor.
const ROLLOVER_BAR: u64 = 900_000;

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

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

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

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

/// One call, one publication: the economics, the terms and the books land
/// atomically, and the version they create is sellable only after all of
/// them exist. Returns the version new sessions will pin.
async fn publish_turbo_tier(fixture: &PropFixture, terms: TurboTerms) -> u32 {
    let response = fixture
        .deployment
        .pool
        .methods()
        .publish_tier_v2(
            TURBO_TIER_ID,
            turbo_tier_params(),
            terms.clone(),
            vec![fixture.order_book.contract_id],
        )
        .with_contract_ids(&[
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .call()
        .await
        .unwrap();
    let version = response.value;
    let published = response
        .decode_logs_with_type::<TierVersionPublishedV2>()
        .unwrap();
    assert_eq!(published.len(), 1);
    assert_eq!(published[0].tier_id, TURBO_TIER_ID);
    assert_eq!(published[0].version, version);
    assert_eq!(published[0].terms, terms);
    assert_eq!(published[0].rollover_window_seconds, 21_600);
    assert_eq!(published[0].threshold_floor, 9_850_000);
    // The V2 publication does NOT emit the legacy event: a pre-restructure
    // consumer must skip this tier, never render it as refundable.
    assert!(
        response
            .decode_logs_with_type::<TierVersionPublished>()
            .unwrap()
            .is_empty()
    );
    version
}

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

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

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

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

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

/// The keeper's expiry attempt, kept fallible so a test can prove the pool
/// REFUSES it while a rollover is earned.
async fn try_expire(fixture: &PropFixture) -> Result<CallResponse<()>> {
    Ok(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?)
}

/// The free rollover, from a wallet with no claim on the session:
/// eligibility is the whole authorization, exactly like `auto_prolong_session`.
async fn try_rollover(fixture: &PropFixture) -> Result<CallResponse<()>> {
    Ok(fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .rollover_session(fixture.child_id)
        .with_contracts(&[
            &fixture.account,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .call()
        .await?)
}

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

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

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

    // An escalator with no anchor to measure from is dead protection.
    let mut anchorless = turbo_terms(DRAWDOWN_SCHEDULE);
    anchorless.rollover_profit_bps = 0;
    anchorless.max_rollovers = 0;
    let error = pool
        .methods()
        .publish_tier_v2(
            TURBO_TIER_ID,
            turbo_tier_params(),
            anchorless,
            vec![fixture.order_book.contract_id],
        )
        .with_contract_ids(&[
            fixture.order_book.contract_id,
            fixture.deployment.price_feed_id,
        ])
        .call()
        .await
        .unwrap_err();
    assert!(error.to_string().contains("InvalidTurboTerms"), "{error:#}");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// The forfeit survives a `draw -> repay_from_collateral` round-trip. Netting
/// drives funded `collateral` to zero while the deposit sits parked on the
/// account as principal, so a forfeit bounded on `funded` would read zero and
/// hand the whole ticket back. Bounded on `user_cash` - which the parked
/// principal rides back into - the deposit is taken in full, exactly as a
/// break-even close does.
#[tokio::test]
async fn a_round_tripped_deposit_is_still_forfeited_whole() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms([0, 0, 0, 0])).await;

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

    // Draw the deposit and net it straight back against funded collateral:
    // `drawn_quote` returns to zero, `collateral` falls by the deposit, and
    // the deposit's worth of quote is left resting on the account. Nothing
    // was traded and nothing was lost - only the ledgers moved.
    let draw = fixture.draw_call(TURBO_DEPOSIT);
    fixture.call_account(vec![draw], 1).await.unwrap();
    let repay = fixture.repay_from_collateral_call(TURBO_DEPOSIT);
    fixture.call_account(vec![repay], 0).await.unwrap();
    assert_eq!(
        fixture.session().await.collateral,
        TURBO_FEE,
        "the netting drove funded collateral down to the accrued fee alone"
    );

    // A break-even close: despite `funded` reading only the fee, the ticket
    // is forfeited whole and the user walks away with nothing.
    let parent_before = fixture
        .user
        .get_asset_balance(&fixture.collateral_asset)
        .await
        .unwrap();
    let response = fixture.close_session().await;
    let closed = fixture.closed_event(&response);
    assert_eq!(closed.user_net, 0);
    assert!(closed.payout_parent.is_empty());
    let forfeited = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<CollateralForfeited>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(forfeited.len(), 1);
    assert_eq!(
        forfeited[0].amount, TURBO_DEPOSIT,
        "the round-tripped deposit is forfeited in full, not handed back"
    );
    assert_eq!(
        fixture
            .deployer
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        platform_before + TURBO_ENTRY as u128,
        "the platform's take is the whole price despite the round-trip"
    );
    assert_eq!(
        fixture
            .user
            .get_asset_balance(&fixture.collateral_asset)
            .await
            .unwrap(),
        parent_before,
        "the round-trip returns the user nothing"
    );
}

/// The prepaid tier refuses every funder, while the legacy session beside it
/// keeps the rescue lever it was sold with — the two cohorts coexisting on
/// one pool is the whole compatibility story.
#[tokio::test]
async fn no_one_may_top_up_a_turbo_session_but_a_legacy_one_still_can() {
    let fixture = PropFixture::new().await;

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

    publish_turbo_tier(&fixture, turbo_terms([0, 0, 0, 0])).await;
    open_turbo_session(&fixture).await;
    let error = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .add_collateral(fixture.child_id)
        .call_params(CallParameters::new(
            100_000,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("TopUpsDisabled"),
        "a prepaid stake cannot be topped up, by anyone: {error:#}"
    );
}

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

    // The window has not opened: a week minus six hours still to run.
    let error = try_rollover(&fixture).await.unwrap_err();
    assert!(error.to_string().contains("RolloverNotDue"), "{error:#}");

    advance_past_expiry(&fixture).await;

    // Past the deadline the window is open by definition — but nothing was
    // earned, so the roll is refused and expiry may proceed.
    let error = try_rollover(&fixture).await.unwrap_err();
    assert!(error.to_string().contains("RolloverNotEarned"), "{error:#}");

    let response = try_expire(&fixture).await.unwrap();
    let closed = fixture.closed_event(&response);
    assert!(matches!(closed.reason, SettlementReason::Expiry));
    let forfeited = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<CollateralForfeited>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(forfeited.len(), 1);
    assert_eq!(forfeited[0].amount, TURBO_DEPOSIT);
}

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

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

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

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

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

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

/// A withdrawal leaves the anchor FIXED and grows a separate `withdrawn`
/// tally. The drawdown floor is measured from the anchor, so a withdrawal
/// cannot widen it; the tally is what keeps the banked profit counting toward
/// the next rollover.
#[tokio::test]
async fn withdrawing_banked_profit_leaves_the_anchor_fixed() {
    let mut fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms([0, 0, 0, 0])).await;
    open_turbo_session(&fixture).await;

    // Cash resting on the account with no draw and no debt is profit by
    // construction — placed directly, as the withdraw suite does.
    let banked = 100_000u64;
    fixture
        .user
        .force_transfer_to_contract(
            fixture.child_id,
            banked,
            fixture.collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
    // `withdraw` reserves `fees_accrued` on the account leg — the fee slice
    // of banked profit stays put until settlement, where it rides out as
    // ordinary surplus (never forfeited: the forfeit is capped at the
    // deposit). So the withdrawable slice is the banked cash NET of the fee,
    // and the deposit itself is untouchable behind the tier floor.
    let withdrawable = banked - TURBO_FEE;
    let withdraw = fixture.pool_call(
        fn_selector!(withdraw(AssetId, u64)),
        0,
        AssetId::default(),
        Some(call_data!(fixture.collateral_asset, withdrawable)),
    );
    let response = fixture.call_account(vec![withdraw], 2).await.unwrap();
    let recorded = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<RolloverWithdrawalRecorded>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(recorded.len(), 1);
    assert_eq!(recorded[0].amount, withdrawable);
    assert_eq!(recorded[0].withdrawn_total, withdrawable);
    // The anchor is the period-start baseline and does NOT move on a
    // withdrawal - only the withdrawn tally grows. The floor stays put.
    let view = rollover_view(&fixture).await;
    assert_eq!(view.anchor, LINE);
    assert_eq!(view.withdrawn, withdrawable);
}

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

    let k = LINE - LINE / 40;
    // Flat, at open: the floor is 3% below the line, under the principal.
    let threshold = fixture.lines().await.threshold;
    assert_eq!(threshold, U256::from(LINE - LINE * 300 / 10_000));
    assert!(
        threshold < U256::from(k),
        "the sold drawdown reaches past k"
    );

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // Week 4 is profitable TOO - but the cap is spent, so the deadline wins
    // and the account ends, forfeiting the stake and paying the profit out.
    fixture.publish_base_price(6_500_000_000_000_000_000).await;
    advance_past_expiry(&fixture).await;
    let error = try_rollover(&fixture).await.unwrap_err();
    assert!(
        error.to_string().contains("RolloverExhausted"),
        "three free weeks is the whole grant: {error:#}"
    );
    let response = try_expire(&fixture).await.unwrap();
    let closed = fixture.closed_event(&response);
    assert!(matches!(closed.reason, SettlementReason::Expiry));
    assert!(
        closed.user_net != 0,
        "the month's profit goes home with the user"
    );
    assert!(!closed.payout_parent.is_empty());
    let forfeited = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<CollateralForfeited>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(forfeited.len(), 1);
    assert_eq!(forfeited[0].amount, TURBO_DEPOSIT);
}

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

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

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

    let response = fixture.liquidate().await;
    let closed = fixture.closed_event(&response);
    assert!(matches!(closed.reason, SettlementReason::Liquidation));
    // Money, to the unit: profit = -2_000_000 drawn + 1_800_000*0.99
    // credited = -218_000; the 250_000 stake (net of the 25_000 fee already
    // paid) absorbs it and the 32_000 residue is forfeited; the user is
    // paid nothing.
    let forfeited = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<CollateralForfeited>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(forfeited.len(), 1);
    assert_eq!(forfeited[0].amount, 32_000);
    assert!(closed.payout_parent.is_empty());
    assert_eq!(closed.user_net, 0);
}

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

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

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

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

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

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

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

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

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

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

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

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

/// "Extend Account: 20% discount for buying future turbo accounts" — the
/// on-chain half of that story: a granted FirstPremium discount prices the
/// next prepaid entry's fee down, and the forfeited deposit is untouched
/// by it (the discount forgives fees, never the stake).
#[tokio::test]
async fn a_repurchase_discount_prices_the_next_entry_fee_down() {
    let fixture = PropFixture::new().await;
    publish_turbo_tier(&fixture, turbo_terms(DRAWDOWN_SCHEDULE)).await;
    open_turbo_session(&fixture).await;
    // The first account runs its course.
    fixture.close_session().await;

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

    // The discount lowers the PRICE, so the exact entry is smaller too:
    // the whole deposit plus the discounted fee, nothing over.
    let discounted_fee = TURBO_FEE * 8 / 10;
    let opened =
        start_turbo_session_paying(&fixture, TURBO_DEPOSIT + discounted_fee).await;
    assert_eq!(
        opened.open_fee, discounted_fee,
        "20% off the entry fee, reported as charged"
    );
    assert_eq!(opened.fees_accrued, discounted_fee);

    // The stake is not discountable - at the close it is forfeited whole.
    let response = fixture.close_session().await;
    let forfeited = fixture
        .deployment
        .pool
        .log_decoder()
        .decode_logs_with_type::<CollateralForfeited>(&response.tx_status.receipts)
        .unwrap();
    assert_eq!(forfeited.len(), 1);
    assert_eq!(forfeited[0].amount, TURBO_DEPOSIT);
}

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

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

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

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

    // Under-posting past the required collateral is the existing floor; a
    // penny below the exact price (but at or above the deposit) is the new
    // one. Exactly the price opens.
    let opened = start_turbo_session_paying(&fixture, TURBO_ENTRY).await;
    assert_eq!(opened.collateral, TURBO_ENTRY);
    assert_eq!(opened.open_fee, TURBO_FEE);
    assert_eq!(opened.fees_accrued, TURBO_FEE, "charged once, at open");

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

    // And no top-up reopens the door the exact-price rule just shut — not
    // from the owner...
    let error = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.user.clone())
        .methods()
        .add_collateral(fixture.child_id)
        .call_params(CallParameters::new(
            1_000,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .call()
        .await
        .unwrap_err();
    assert!(error.to_string().contains("TopUpsDisabled"), "{error:#}");

    // ...nor from an unrelated third party trying to gift room in.
    let error = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .add_collateral(fixture.child_id)
        .call_params(CallParameters::new(
            1_000,
            fixture.collateral_asset,
            u64::MAX,
        ))
        .unwrap()
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("TopUpsDisabled"),
        "a gifted top-up games the drawdown limit as much as the owner's: {error:#}"
    );

    // The stake is untouched by all of it.
    assert_eq!(fixture.session().await.collateral, TURBO_ENTRY);
}

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

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

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

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

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

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

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

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

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

    // The cap is spent: even if it were somehow profitable, no roll remains.
    advance_past_expiry(&fixture).await;
    let error = try_rollover(&fixture).await.unwrap_err();
    assert!(
        error.to_string().contains("Rollover"),
        "the fourth week has no free roll left: {error:#}"
    );

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

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

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

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

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

    // The fixture's own live session is on the LEGACY tier. A permissionless
    // rollover attempt on it is refused: it has no terms, so it sells none.
    let error = fixture
        .deployment
        .pool
        .clone()
        .with_account(fixture.outsider.clone())
        .methods()
        .rollover_session(fixture.child_id)
        .with_contracts(&[
            &fixture.account,
            &fixture.deployment.oracle,
            &fixture.order_book.order_book,
            &fixture.deployment.price_feed,
        ])
        .call()
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("RolloverNotOffered"),
        "a legacy session was never sold a rollover: {error:#}"
    );

    // Now on a turbo session: the paid auto-renewal cannot be armed, because
    // a prepaid tier prices no period — the free rollover is its only
    // extension.
    open_turbo_session(&fixture).await;
    let arm = fixture.pool_call(
        fn_selector!(set_auto_prolong(Option<ProlongPeriod>)),
        0,
        AssetId::default(),
        Some(call_data!(Some(ProlongPeriod::Day))),
    );
    let error = fixture.call_account(vec![arm], 0).await.unwrap_err();
    assert!(
        error.to_string().contains("PeriodNotOffered"),
        "a prepaid tier prices no period to arm: {error:#}"
    );
}

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

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

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

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

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