o2-deploy 0.3.21-rc

Contract deployment logic for Fuel O2 exchange
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
//! Contract deployment logic for the Fuel O2 exchange.
//!
//! This crate extracts the core deploy workflow from the `api` package,
//! making it reusable from both the API binary and the standalone `o2-deploy` CLI.

use anyhow::Context;
use fuel_core_client::client::types::primitives::{
    ContractId,
    Salt,
};
use fuel_core_types::fuel_types::BlockHeight;
use fuels::{
    accounts::{
        Account,
        ViewOnlyAccount,
    },
    prelude::Execution,
    types::{
        Identity,
        SizedAsciiString,
    },
};
use o2_api_types::{
    domain::book::{
        AssetConfig,
        MarketIdAssets,
        OrderBookConfig,
    },
    parse::HexDisplayFromStr,
};
use o2_tools::{
    order_book::OrderBookManager,
    order_book_deploy::{
        OrderBookBlacklist,
        OrderBookConfigurables,
        OrderBookDeploy,
        OrderBookDeployConfig,
        OrderBookWhitelist,
    },
    order_book_registry::{
        OrderBookRegistryDeployConfig,
        OrderBookRegistryManager,
    },
    trade_account_deploy::{
        DeployConfig,
        TradeAccountDeploy,
        TradeAccountDeployConfig,
        TradingAccountOracle,
    },
    trade_account_registry::{
        TradeAccountRegistryConfigurables,
        TradeAccountRegistryDeployConfig,
        TradeAccountRegistryManager,
    },
    trial_trade_account_deploy::{
        DeployConfig as TrialDeployConfig,
        TrialTradeAccountDeploy,
        TrialTradeAccountDeployConfig,
        TrialTradingAccountOracle,
    },
};
use serde_with::serde_as;
use std::ops::{
    Deref,
    DerefMut,
};

pub use o2_tools::prop_deploy::{
    ExistingRegistry,
    PropDeployConfig,
    PropDeployment,
};

/// Access-control role that authorizes order-book maintenance actions
/// (`force_cancel_orders`, `cancel_blacklist_orders`, `eject_trigger_order`).
///
/// Must match `ORDERBOOK_MAINTAINER_ROLE` in `contracts/order-book/src/main.sw`.
const ORDERBOOK_MAINTAINER_ROLE: u64 = 1;

/// Access-control role on the prop margin pool that authorizes
/// `set_user_discount` - the ONLY caller that function accepts, the admin
/// included, so whoever prices user discounts must hold it.
///
/// Must match `DISCOUNT_MANAGER_ROLE` in
/// `contracts/prop-margin-pool/src/main.sw`.
const DISCOUNT_MANAGER_ROLE: u64 = 1;

/// Deploy the independent prop-account system.
///
/// This is additive to the existing exchange deployment: callers can choose
/// when to deploy the direct account oracle, mock price feed, proxied registry,
/// and proxied margin pool.
pub async fn deploy_prop_system<W>(
    wallet: &W,
    config: &PropDeployConfig,
) -> anyhow::Result<PropDeployment<W>>
where
    W: Account + Clone,
{
    PropDeployment::deploy(wallet, config).await
}

fn to_registry_market_id(m: &MarketIdAssets) -> o2_tools::order_book_registry::MarketId {
    o2_tools::order_book_registry::MarketId {
        base_asset: m.base_asset,
        quote_asset: m.quote_asset,
    }
}

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

#[serde_as]
#[derive(Debug, serde::Serialize, Clone, Default)]
pub struct MarketsConfigOutput {
    pub starting_height: u32,
    #[serde_as(as = "HexDisplayFromStr")]
    pub trade_account_registry_id: ContractId,
    #[serde_as(as = "HexDisplayFromStr")]
    pub trade_account_registry_blob_id: ContractId,
    #[serde_as(as = "HexDisplayFromStr")]
    pub trade_account_oracle_id: ContractId,
    #[serde_as(as = "HexDisplayFromStr")]
    pub trial_trade_account_oracle_id: ContractId,
    #[serde_as(as = "HexDisplayFromStr")]
    pub trade_account_root: ContractId,
    #[serde_as(as = "HexDisplayFromStr")]
    pub trade_account_proxy: ContractId,
    #[serde_as(as = "HexDisplayFromStr")]
    pub trade_account_blob_id: ContractId,
    #[serde_as(as = "Option<HexDisplayFromStr>")]
    pub order_book_whitelist_id: Option<ContractId>,
    #[serde_as(as = "Option<HexDisplayFromStr>")]
    pub order_book_blacklist_id: Option<ContractId>,
    #[serde_as(as = "HexDisplayFromStr")]
    pub order_book_registry_id: ContractId,
    #[serde_as(as = "HexDisplayFromStr")]
    pub order_book_registry_blob_id: ContractId,
    #[serde_as(as = "Option<HexDisplayFromStr>")]
    pub fast_bridge_asset_registry_proxy_id: Option<ContractId>,
    #[serde_as(as = "Option<HexDisplayFromStr>")]
    pub price_feed_id: Option<ContractId>,
    #[serde_as(as = "Option<HexDisplayFromStr>")]
    pub margin_pool_id: Option<ContractId>,
    #[serde_as(as = "Option<HexDisplayFromStr>")]
    pub margin_oracle_id: Option<ContractId>,
    /// The `margin` section, echoed back with the ids this run resolved
    /// folded in. CI writes the output OVER the deploy config, so anything
    /// the output drops is destroyed: without this the first margin deploy
    /// would erase the tier catalogue, the pool config, the publishers and
    /// the initial prices, and every later run would silently do no margin
    /// work at all.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub margin: Option<MarginConfig>,
    pub pairs: Vec<OrderBookConfig>,
}

/// Intermediate type for deserializing order book configs with string-encoded numbers.
#[serde_as]
#[derive(Debug, Clone, serde::Deserialize)]
struct OrderBookConfigDeHelper {
    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
    blob_id: Option<ContractId>,
    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
    contract_id: Option<ContractId>,
    #[serde_as(as = "serde_with::DisplayFromStr")]
    taker_fee: u64,
    #[serde_as(as = "serde_with::DisplayFromStr")]
    maker_fee: u64,
    #[serde_as(as = "serde_with::DisplayFromStr")]
    min_order: u64,
    #[serde_as(as = "serde_with::DisplayFromStr")]
    dust: u64,
    price_window: u8,
    #[serde(default)]
    allow_fractional_price: bool,
    base: AssetConfig,
    quote: AssetConfig,
}

impl From<OrderBookConfigDeHelper> for OrderBookConfig {
    fn from(h: OrderBookConfigDeHelper) -> Self {
        let ids = MarketIdAssets {
            base_asset: h.base.asset,
            quote_asset: h.quote.asset,
        };
        let market_id = ids.market_id();
        OrderBookConfig {
            contract_id: h.contract_id,
            blob_id: h.blob_id,
            market_id,
            taker_fee: h.taker_fee,
            maker_fee: h.maker_fee,
            min_order: h.min_order,
            dust: h.dust,
            price_window: h.price_window,
            allow_fractional_price: h.allow_fractional_price,
            base: h.base,
            quote: h.quote,
        }
    }
}

#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct MarketsConfigPartial {
    pub starting_height: u32,
    pub trade_account_registry_id: Option<ContractId>,
    pub order_book_registry_id: Option<ContractId>,
    pub trade_account_oracle_id: Option<ContractId>,
    pub trial_trade_account_oracle_id: Option<ContractId>,
    pub order_book_whitelist_id: Option<ContractId>,
    pub order_book_blacklist_id: Option<ContractId>,
    pub fast_bridge_asset_registry_proxy_id: Option<ContractId>,
    pub pairs: Vec<OrderBookConfig>,
    /// Optional `margin` section: the prop-account margin stack (price
    /// feed, pool, account oracle, in-place registry upgrade) plus the
    /// tier catalogue, deployed/upgraded idempotently after the books.
    pub margin: Option<MarginConfig>,
}

impl<'de> serde::Deserialize<'de> for MarketsConfigPartial {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(serde::Deserialize, Default)]
        struct Helper {
            #[serde(default)]
            starting_height: u32,
            trade_account_registry_id: Option<ContractId>,
            order_book_registry_id: Option<ContractId>,
            trade_account_oracle_id: Option<ContractId>,
            trial_trade_account_oracle_id: Option<ContractId>,
            order_book_whitelist_id: Option<ContractId>,
            order_book_blacklist_id: Option<ContractId>,
            fast_bridge_asset_registry_proxy_id: Option<ContractId>,
            #[serde(default)]
            pairs: Vec<OrderBookConfigDeHelper>,
            #[serde(default)]
            margin: Option<MarginConfig>,
        }
        let h = Helper::deserialize(deserializer)?;
        if let Some(margin) = &h.margin
            && margin.price_feed_id.is_some()
        {
            return Err(serde::de::Error::custom(
                "`margin.price_feed_id` moved into `margin.price_feed.id`. \
                 Refusing to load a config that uses the retired spelling: it \
                 would be ignored, a fresh feed would be derived, and the pool \
                 would be repointed at an oracle with no publisher. Move the id \
                 (and `publishers` / `supported_assets`) under \
                 `margin.price_feed`.",
            ));
        }
        Ok(MarketsConfigPartial {
            starting_height: h.starting_height,
            trade_account_registry_id: h.trade_account_registry_id,
            order_book_registry_id: h.order_book_registry_id,
            trade_account_oracle_id: h.trade_account_oracle_id,
            trial_trade_account_oracle_id: h.trial_trade_account_oracle_id,
            order_book_whitelist_id: h.order_book_whitelist_id,
            order_book_blacklist_id: h.order_book_blacklist_id,
            fast_bridge_asset_registry_proxy_id: h.fast_bridge_asset_registry_proxy_id,
            pairs: h.pairs.into_iter().map(Into::into).collect(),
            margin: h.margin,
        })
    }
}

/// One tier of the margin catalogue. Mirrors the on-chain `TierParams`
/// plus the tier id and the markets (order books) it covers. `line`
/// follows the config convention of u64 amounts as strings.
#[serde_as]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MarginTierConfig {
    pub tier_id: u64,
    /// Credit line in collateral-asset base units, as a decimal string.
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub line: u64,
    pub leverage: u64,
    pub duration: u64,
    pub maintenance_bps: u64,
    pub open_buffer_bps: u64,
    pub liq_price_factor: u64,
    /// Flat fee for one prolongation of each period, in WHOLE collateral
    /// units as a decimal string - `"13.5"` at 9 decimals means
    /// `13_500_000_000` base units. Indexed six hours, day, week, month; a
    /// zero means the period is not offered.
    pub prolong_fee: [String; 4],
    pub max_credit_line_bps: u64,
    pub max_price_age: u64,
    /// Flat fee charged once at open, in WHOLE collateral units as a decimal
    /// string. Same form as `prolong_fee`.
    pub open_fee: String,
    pub profit_share_bps: u64,
    pub price_band_bps: u64,
    /// Markets in this tier, referencing already-configured pairs by
    /// "BASE/QUOTE" symbol or by hex market id.
    pub markets: Vec<String>,
}

/// One asset the price feed must know the decimals of. Registering the
/// decimals is what makes an asset SUPPORTED by the feed; publishing a
/// price for it is a separate, later act. Declaring assets here therefore
/// lets a freshly deployed feed be configured up front, before any
/// publisher has produced a single quote.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MarginSupportedAsset {
    pub asset: fuels::types::AssetId,
    pub decimals: u8,
}

/// The `price_feed` sub-section: everything about the ORACLE the pool values
/// against, kept apart from the pool's own settings because it is a separate
/// contract with its own lifecycle, ownership and roles.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct MarginPriceFeedConfig {
    /// Reuse an existing feed. `None` deploys the production price feed
    /// behind its own SRC-14 proxy.
    pub id: Option<ContractId>,
    /// Submission-age bound in seconds, reconciled compare-first. `None`
    /// leaves whatever the feed enforces today.
    pub max_offchain_age_seconds: Option<u64>,
    /// Identities that must HOLD the submitter role, each prefixed with its
    /// kind (`address:0x..` for a wallet, `contract:0x..` for a publishing
    /// contract). Reconciled compare-first: an identity that already holds it
    /// costs no transaction. When empty, nothing is granted and only the
    /// feed's owner may publish.
    #[serde(default)]
    pub publishers: Vec<String>,
    /// Identities that must NOT hold the submitter role, same prefixed form,
    /// revoked only if currently held.
    ///
    /// An explicit list on purpose. The feed stores roles as a bitmap keyed
    /// BY ACCOUNT with no reverse index, so neither the contract nor this
    /// deploy can enumerate who holds the role - "revoke everyone not in
    /// `publishers`" is not a question that can be asked on chain, and
    /// inferring it from config absence would silently kick out a publisher
    /// granted out of band.
    ///
    /// Revoking stops FUTURE writes only. A price the publisher already
    /// pushed stays live until it ages out or is invalidated explicitly.
    #[serde(default)]
    pub remove_publishers: Vec<String>,
    /// Assets the feed supports, registered by their decimals before any price
    /// exists. Reconciled compare-first: an asset the feed already knows at the
    /// SAME decimals is skipped, an unknown one is registered, and a
    /// DISAGREEMENT is refused rather than overwritten. The pool pins an
    /// asset's decimals on first use and rejects a later change, so silently
    /// moving them here would strand it.
    #[serde(default)]
    pub supported_assets: Vec<MarginSupportedAsset>,
}

/// Optional `margin` section of the deploy config: the prop margin pool,
/// the prop account oracle, the price feed and the tier catalogue.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct MarginConfig {
    /// The price feed: its own contract, its own section.
    #[serde(default)]
    pub price_feed: MarginPriceFeedConfig,
    /// The RETIRED flat spelling of `price_feed.id`, present only so that a
    /// stale config is REJECTED rather than silently ignored.
    ///
    /// Silence here is catastrophic rather than untidy: an unread feed id
    /// means the run derives a FRESH feed, and the pool-feed reconcile then
    /// moves a live pool onto an oracle nobody publishes to. Every
    /// valuation, liquidation and session open fails afterwards.
    ///
    /// Never serialized, so the write-back drops it once migrated.
    #[serde(default, skip_serializing)]
    pub price_feed_id: Option<ContractId>,
    /// TIER-ONLY mode: run no system deploy, only reconcile the tier
    /// catalogue (and the feed's roster/assets when configured) against
    /// this already-deployed pool.
    pub margin_pool_id: Option<ContractId>,
    /// Identity receiving the platform profit share, prefixed with its
    /// kind (`address:0x..` / `contract:0x..`). Defaults to the deployer.
    pub platform_payout: Option<String>,
    /// Identities that must HOLD the pool's discount-manager role - the
    /// only role `set_user_discount` accepts, the admin included - each
    /// prefixed with its kind (`address:0x..` / `contract:0x..`).
    /// Reconciled compare-first: an identity that already holds it costs
    /// no transaction. When empty, nothing is granted and NOBODY can
    /// price user discounts.
    ///
    /// A ROSTER, so it lives in the config beside the feed's `publishers`
    /// rather than in a deploy flag: the cosigner and the liquidator are
    /// flags because they name the operator's own key and payee, while
    /// this is a list the deployment owns and carries forward run to run.
    #[serde(default)]
    pub discount_managers: Vec<String>,
    /// Identities that must NOT hold the discount-manager role, same
    /// prefixed form, revoked only if currently held.
    ///
    /// An explicit list for the same reason `remove_publishers` is one:
    /// roles are a bitmap keyed BY ACCOUNT with no reverse index, so
    /// "revoke everyone not in `discount_managers`" is not a question
    /// that can be asked on chain, and inferring it from config absence
    /// would silently kick out a manager granted out of band.
    ///
    /// Revoking stops FUTURE writes only: discounts the manager already
    /// granted stay in force until cleared.
    #[serde(default)]
    pub remove_discount_managers: Vec<String>,
    /// Collateral asset of the pool. Defaults to the quote asset of the
    /// first configured pair.
    pub collateral_asset: Option<fuels::types::AssetId>,
    /// Collateral asset decimals. REQUIRED: a wrong figure misprices every
    /// valuation the pool makes, so there is no default to fall back to.
    pub collateral_decimals: Option<u8>,
    /// Maximum order books one tier version may hold. Defaults to 80.
    pub max_tier_books: Option<u64>,
    /// Fee charged by `repay_base_from_collateral`, in PARTS PER MILLION of the
    /// quote value of the debt closed - the order book's `TAKER_FEE` scale, so
    /// `100` is one basis point. Defaults to 100.
    ///
    /// It is a pool CONFIGURABLE, so changing it here only takes effect on a
    /// deploy or an implementation upgrade (`--upgrade-bytecode`), never on a
    /// tier-only reconcile against an already-deployed pool.
    pub base_repay_fee_ppm: Option<u64>,
    /// The desired tier catalogue; reconciled idempotently (§ tier engine):
    /// unchanged tiers are untouched, grown book lists use `add_books`,
    /// any param change publishes a NEW version.
    #[serde(default)]
    pub tiers: Vec<MarginTierConfig>,
}

#[derive(Debug, Clone, Default)]
pub struct OwnershipTransferOptions {
    pub new_proxy_owner: Option<fuels::types::Address>,
    pub new_contract_owner: Option<fuels::types::Address>,
    /// Accounts to revoke `ORDERBOOK_MAINTAINER_ROLE` from on each order book
    /// (via `owner_revoke_role`) before granting the new maintainers, so the role
    /// is rotated rather than accumulating holders across upgrades.
    pub revoke_orderbook_maintainers: Vec<fuels::types::Address>,
    /// Accounts to grant `ORDERBOOK_MAINTAINER_ROLE` to on each order book (via
    /// `owner_grant_role`) before ownership is transferred away.
    pub new_orderbook_maintainers: Vec<fuels::types::Address>,
}

/// Parameters for a deploy invocation.
#[derive(Debug, Clone)]
pub struct DeployParams {
    pub deploy_config: MarketsConfigPartial,
    pub output: Option<String>,
    pub deploy_whitelist: bool,
    pub deploy_blacklist: bool,
    pub upgrade_bytecode: bool,
    pub new_proxy_owner: Option<fuels::types::Address>,
    pub new_contract_owner: Option<fuels::types::Address>,
    /// Cosigner address for trial trade accounts. When set, the trial trade
    /// account implementation is (re)deployed on the trial oracle and this
    /// cosigner is configured on it; when absent, the configured cosigner is
    /// left untouched (the implementation still follows the regular
    /// seed/upgrade lifecycle).
    pub trial_cosigner: Option<fuels::types::Address>,
    /// Identity allowed to register (activate) trial trade accounts on the
    /// registry. When set, it is written via
    /// `set_trial_trade_account_creator` if it differs from the current one
    /// — registries upgraded in place start with the creator unset, which
    /// denies all trial registrations. When absent, the creator is left
    /// untouched.
    pub trial_creator: Option<Identity>,
    /// Reconcile margin CONFIGURATION only, leaving BYTECODE — the pool, the
    /// oracle, the price-feed implementation — and the registry's prop wiring
    /// untouched.
    ///
    /// It does still reconcile the things that are configuration rather than
    /// code: the tier catalogue, the feed's publisher roster, its supported
    /// assets, its submission-age bound, and the pool's feed pointer. That is
    /// the point of the mode — rotating a publisher must not need a redeploy.
    ///
    /// An explicit switch rather than an inference from the markets
    /// config: the mode decides WHETHER the system phase runs, which is
    /// unrelated to WHICH pool the config names. Conflating the two meant
    /// the ordinary steady state disabled the phase that owns the
    /// registry's prop configurables, so an upgrade that dropped them was
    /// never repaired.
    pub margin_tier_only: bool,
    /// Cosigner address for prop/margin accounts. When set, it is written to
    /// the prop account oracle if it differs from the live one; when absent,
    /// the configured cosigner is left untouched. Deliberately NOT sourced
    /// from the deploy config and NOT defaulted to the deployer: a cosigner
    /// the backend does not hold the key for makes margin silently inert.
    pub margin_cosigner: Option<fuels::types::Address>,
    /// Recipient of the residue from forced margin exits (liquidation and
    /// expiry). Same opt-in rule as `margin_cosigner`: set it and it is
    /// reconciled, omit it and the live value stands. Never defaulted to the
    /// deployer - the deploy key must not silently become the payee.
    pub margin_liquidator: Option<Identity>,
    pub revoke_orderbook_maintainers: Vec<fuels::types::Address>,
    pub new_orderbook_maintainers: Vec<fuels::types::Address>,
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Load a JSON config file, returning `T::default()` when the path is empty.
pub fn load_config_from_file<T>(config_path: &str) -> anyhow::Result<T>
where
    T: Default + serde::de::DeserializeOwned,
{
    if config_path.is_empty() {
        return Ok(T::default());
    }
    let current_dir = std::env::current_dir()?;
    let path = current_dir.join(config_path);
    tracing::info!("Loading config from {}", path.display());
    let file = std::fs::File::open(&path)?;
    let config: T = serde_json::from_reader(file)?;
    Ok(config)
}

// ---------------------------------------------------------------------------
// Core deploy logic
// ---------------------------------------------------------------------------

/// Deploy (or upgrade) the full set of O2 contracts.
///
/// The wallet type `W` must implement `Account + Clone + Signer` (e.g.
/// `fuels::prelude::WalletUnlocked` or the KMS-backed `O2Wallet` from the API).
pub async fn deploy<W>(
    wallet: W,
    params: DeployParams,
) -> anyhow::Result<MarketsConfigOutput>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    tracing::info!("Starting Fuel o2 Registries and Markets");
    let mut markets_config_partial = params.deploy_config.clone();
    let starting_height: BlockHeight = markets_config_partial.starting_height.into();
    let trade_account_oracle_id = markets_config_partial.trade_account_oracle_id;
    let trial_trade_account_oracle_id =
        markets_config_partial.trial_trade_account_oracle_id;
    let order_book_registry_id = markets_config_partial.order_book_registry_id;
    let trade_account_registry_id = markets_config_partial.trade_account_registry_id;
    let fast_bridge_asset_registry_proxy_id =
        markets_config_partial.fast_bridge_asset_registry_proxy_id;

    let mut salt = Salt::zeroed();
    salt.deref_mut()[..4].copy_from_slice(&starting_height.deref().to_be_bytes());

    let (trade_account_oracle_deploy, trade_account_blob_id) =
        deploy_trade_account_oracle(
            wallet.clone(),
            params.upgrade_bytecode,
            trade_account_oracle_id,
            salt,
        )
        .await?;
    // The trial oracle is a dedicated contract (already-deployed trade
    // account oracles are immutable and cannot gain the trial functions), so
    // it deploys separately and the registry references both oracle ids.
    let trial_trade_account_oracle_id = deploy_trial_trade_account_oracle(
        wallet.clone(),
        params.upgrade_bytecode,
        trial_trade_account_oracle_id,
        params.trial_cosigner,
        salt,
    )
    .await?;
    let (trade_account_registry, trade_account_registry_blob_id) =
        deploy_trade_account_registry(
            wallet.clone(),
            params.upgrade_bytecode,
            trade_account_oracle_deploy.clone(),
            trial_trade_account_oracle_id,
            trade_account_registry_id,
            salt,
        )
        .await?;
    let order_book_blacklist_id = deploy_order_book_blacklist(
        wallet.clone(),
        params.deploy_blacklist,
        markets_config_partial.order_book_blacklist_id,
        salt,
    )
    .await?;
    let order_book_whitelist_id = deploy_order_book_whitelist(
        wallet.clone(),
        params.deploy_whitelist,
        markets_config_partial.order_book_whitelist_id,
        salt,
    )
    .await?;
    let (order_book_registry, order_book_registry_blob_id) = deploy_order_book_registry(
        wallet.clone(),
        params.upgrade_bytecode,
        order_book_registry_id,
        salt,
    )
    .await?;
    let pairs = deploy_order_books(
        wallet.clone(),
        params.upgrade_bytecode,
        order_book_blacklist_id,
        order_book_whitelist_id,
        order_book_registry.clone(),
        &mut markets_config_partial.pairs,
        OwnershipTransferOptions {
            new_proxy_owner: params.new_proxy_owner,
            new_contract_owner: params.new_contract_owner,
            revoke_orderbook_maintainers: params.revoke_orderbook_maintainers.clone(),
            new_orderbook_maintainers: params.new_orderbook_maintainers.clone(),
        },
    )
    .await?;

    let order_book_registry_id = order_book_registry.contract_id;
    let trade_account_registry_id = trade_account_registry.contract_id;
    let trade_account_oracle_id = trade_account_oracle_deploy.oracle_id;

    let trade_account_proxy = trade_account_registry
        .registry
        .methods()
        .default_bytecode()
        .simulate(Execution::state_read_only())
        .await?
        .value
        .context(
            "Trade account registry default bytecode should exist after initialization",
        )?;
    let trade_account_root = trade_account_registry
        .registry
        .methods()
        .factory_bytecode_root()
        .simulate(Execution::state_read_only())
        .await?
        .value
        .context("Trade account registry factory bytecode root should exist after initialization")?;

    // The margin phase runs BEFORE ownership transfer: the in-place
    // registry upgrade and the pool/tier governance calls need the deployer
    // to still hold the proxies and the pool admin role.
    let margin_ids = match &markets_config_partial.margin {
        Some(margin) => Some(
            deploy_margin(
                &wallet,
                margin,
                salt,
                params.margin_tier_only,
                trade_account_registry_id,
                trade_account_oracle_id,
                trial_trade_account_oracle_id,
                &pairs,
                params.margin_cosigner,
                params.margin_liquidator,
                params.upgrade_bytecode,
            )
            .await?,
        ),
        None => None,
    };

    // Registries upgraded in place start with the trial creator unset (the
    // configurable seed only applies on the first initialize), so the deploy
    // writes it explicitly when provided. Must run before ownership transfer.
    if let Some(trial_creator) = params.trial_creator {
        let current_creator = trade_account_registry
            .get_trial_trade_account_creator()
            .await?;
        if current_creator != trial_creator {
            tracing::info!("Setting trial trade account creator to {trial_creator:?}");
            trade_account_registry
                .set_trial_trade_account_creator(trial_creator)
                .await?;
        }
    }

    transfer_ownership(
        &wallet,
        &params,
        &order_book_registry,
        &trade_account_registry,
        &trade_account_oracle_deploy,
        trial_trade_account_oracle_id,
        order_book_blacklist_id,
        order_book_whitelist_id,
    )
    .await?;

    let deploy_result = MarketsConfigOutput {
        starting_height: starting_height.into(),
        trade_account_registry_id,
        trade_account_registry_blob_id,
        trade_account_proxy,
        trade_account_blob_id,
        trade_account_root: ContractId::from(trade_account_root.0),
        trade_account_oracle_id,
        trial_trade_account_oracle_id,
        order_book_whitelist_id,
        order_book_blacklist_id,
        order_book_registry_id,
        order_book_registry_blob_id,
        pairs,
        fast_bridge_asset_registry_proxy_id,
        price_feed_id: margin_ids.map(|ids| ids.price_feed_id),
        margin_pool_id: margin_ids.map(|ids| ids.margin_pool_id),
        margin_oracle_id: margin_ids.and_then(|ids| ids.margin_oracle_id),
        // Carry the section through, with the resolved ids written back so a
        // re-run reads them and drops into tier-only mode against the pool it
        // already deployed. A DRY RUN must not: its ids are predictions for
        // contracts that were never created, and writing them would send the
        // next real run into tier-only mode against a pool that does not
        // exist, skipping the system deploy entirely.
        margin: markets_config_partial.margin.clone().map(|mut margin| {
            if let Some(ids) = margin_ids {
                margin.price_feed.id = Some(ids.price_feed_id);
                margin.margin_pool_id = Some(ids.margin_pool_id);
            }
            margin
        }),
    };

    if let Some(output_path) = params.output {
        let json = serde_json::to_string_pretty(&deploy_result)?;
        tracing::info!("Deploy result saved to {}", output_path);
        std::fs::write(output_path, json)?;
    }

    Ok(deploy_result)
}

// ---------------------------------------------------------------------------
// Margin (prop) deployment
// ---------------------------------------------------------------------------

/// The margin stack's resolved ids, echoed on the deploy output.
#[derive(Debug, Clone, Copy)]
pub struct MarginIds {
    pub price_feed_id: ContractId,
    pub margin_pool_id: ContractId,
    pub margin_oracle_id: Option<ContractId>,
}

/// The margin phase of [`deploy`]: the prop system deployed/resumed
/// deterministically (salted ids, exists-checked steps), the SHARED
/// trade-account registry upgraded IN PLACE to carry the prop
/// configurables, and the tier catalogue reconciled. With `tier_only` the
/// system deploy is skipped and only the feed and tier reconciliation runs
/// against the pool the config names.
///
/// Every step is compare-first: it reads the live value and sends nothing
/// when the chain already agrees. A settled system therefore costs a run of
/// reads and no transactions, which is what a rehearsal used to be for.
#[allow(clippy::too_many_arguments)]
async fn deploy_margin<W>(
    wallet: &W,
    margin: &MarginConfig,
    salt: fuels::types::Salt,
    tier_only: bool,
    trade_account_registry_id: ContractId,
    trade_account_oracle_id: ContractId,
    trial_trade_account_oracle_id: ContractId,
    pairs: &[OrderBookConfig],
    margin_cosigner: Option<fuels::types::Address>,
    margin_liquidator: Option<Identity>,
    upgrade_bytecode: bool,
) -> anyhow::Result<MarginIds>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    use o2_tools::prop::{
        PriceFeedContract,
        PropAccountOracleContract,
        PropMarginPoolContract,
    };

    let collateral_asset = match margin.collateral_asset {
        Some(collateral_asset) => collateral_asset,
        None => {
            pairs
                .first()
                .context(
                    "margin.collateral_asset is not set and there are no pairs to \
                     default it from",
                )?
                .quote
                .asset
        }
    };
    // The cosigner and the liquidator arrive as DEPLOY PARAMETERS, not from
    // the config file: both name a key or a payee that belongs to the
    // operator running the deploy, and both are opt-in - provide one and it
    // is reconciled, omit it and whatever is live stands.
    let cosigner = margin_cosigner;
    let platform_payout = margin
        .platform_payout
        .as_deref()
        .map(parse_margin_identity)
        .transpose()?;
    let liquidator = margin_liquidator;

    let mut prop_config = PropDeployConfig::new(collateral_asset);
    // No default: a wrong decimals figure misprices every valuation the pool
    // makes, and it is invisible until money moves.
    prop_config.collateral_decimals = margin.collateral_decimals.context(
        "margin.collateral_decimals is required - set it to the collateral \
         asset's decimals in the deploy config",
    )?;
    prop_config.max_tier_books = margin.max_tier_books.unwrap_or(80);
    prop_config.base_repay_fee_ppm = margin.base_repay_fee_ppm.unwrap_or(100);
    prop_config.cosigner = cosigner;
    prop_config.platform_payout = platform_payout;
    prop_config.liquidator = liquidator;
    prop_config.salt = salt;
    prop_config.existing_price_feed = margin.price_feed.id;
    prop_config.max_offchain_age_seconds = margin.price_feed.max_offchain_age_seconds;
    // The config names WHICH pool; it no longer decides whether the system
    // phase runs. Pinning it also keeps an upgrade from forking the pool
    // when a release changes the pool bytecode.
    prop_config.existing_pool = margin.margin_pool_id;
    prop_config.existing_registry = Some(ExistingRegistry {
        registry_id: trade_account_registry_id,
        trade_account_oracle_id,
        trial_trade_account_oracle_id,
    });

    anyhow::ensure!(
        !(tier_only && margin.margin_pool_id.is_none()),
        "--margin-tier-only was requested but the markets config names no \
         `margin.margin_pool_id`: there is no pool to reconcile tiers against"
    );

    // Resolve the system: tier-only mode, or a real deploy-or-resume.
    let (price_feed_id, margin_pool_id, margin_oracle_id) = if let (
        true,
        Some(margin_pool_id),
    ) =
        (tier_only, margin.margin_pool_id)
    {
        tracing::info!("Margin: tier-only mode against pool {margin_pool_id}");
        let price_feed_id = match margin.price_feed.id {
            Some(price_feed_id) => price_feed_id,
            None => {
                PropMarginPoolContract::new(margin_pool_id, wallet.clone())
                    .methods()
                    .price_feed()
                    .simulate(Execution::state_read_only())
                    .await
                    .context("read the pool's price feed")?
                    .value
            }
        };
        // Read the oracle back off the registry rather than reporting
        // `None`. The caller writes what it gets straight into
        // markets.json, so a `None` here NULLS a live, known-good id —
        // the same class of mistake as writing ids a rehearsal never
        // deployed.
        let margin_oracle_id =
            TradeAccountRegistryManager::new(wallet.clone(), trade_account_registry_id)
                .registry
                .methods()
                .get_prop_oracle_id()
                .simulate(Execution::state_read_only())
                .await
                .map(|result| result.value)
                .ok()
                .filter(|oracle_id| *oracle_id != ContractId::zeroed());
        (price_feed_id, margin_pool_id, margin_oracle_id)
    } else {
        let deployment = deploy_prop_system(wallet, &prop_config).await?;
        tracing::info!(
            "Margin: oracle {}, pool {}, feed {} (shared registry {} upgraded in place)",
            deployment.oracle_id,
            deployment.pool_id,
            deployment.price_feed_id,
            deployment.registry_id,
        );
        (
            deployment.price_feed_id,
            deployment.pool_id,
            Some(deployment.oracle_id),
        )
    };

    // -- the payout parties ----------------------------------------------
    // Reconciled compare-first against the LIVE pool, so a re-run is a
    // no-op and an absent config key never overwrites what the pool has.
    // A pool not deployed yet gets both values through its INITIAL_*
    // configurables on the real run.
    let pool_deployed = wallet
        .try_provider()?
        .contract_exists(&margin_pool_id)
        .await?;
    if pool_deployed {
        let pool = PropMarginPoolContract::new(margin_pool_id, wallet.clone());
        if let Some(platform_payout) = platform_payout {
            let current = pool
                .methods()
                .platform_payout()
                .simulate(Execution::state_read_only())
                .await
                .context("read the pool's platform payout")?
                .value;
            if current != platform_payout {
                tracing::info!(
                    "Margin: platform payout {current:?} -> {platform_payout:?}"
                );
                pool.methods()
                    .set_platform_payout(platform_payout)
                    .call()
                    .await?;
            }
        }
        if let Some(liquidator) = liquidator {
            let current = pool
                .methods()
                .liquidator()
                .simulate(Execution::state_read_only())
                .await
                .context("read the pool's liquidator")?
                .value;
            if current != liquidator {
                tracing::info!("Margin: liquidator {current:?} -> {liquidator:?}");
                pool.methods().set_liquidator(liquidator).call().await?;
            }
        }

        // -- the discount managers -----------------------------------------
        // The feed's publisher roster, part for part: granted and revoked
        // only where the pool disagrees with the config, so a settled
        // roster sends nothing at all.
        //
        // An identity in BOTH lists would be granted and then revoked in
        // the same run, silently, decided by iteration order. Refuse the
        // ambiguity.
        for entry in &margin.discount_managers {
            anyhow::ensure!(
                !margin.remove_discount_managers.contains(entry),
                "discount manager {entry} is listed in both \
                 `discount_managers` and `remove_discount_managers`"
            );
        }
        for (entry, should_hold) in margin
            .discount_managers
            .iter()
            .map(|entry| (entry, true))
            .chain(
                margin
                    .remove_discount_managers
                    .iter()
                    .map(|entry| (entry, false)),
            )
        {
            let manager = parse_margin_identity(entry)?;
            let holds = pool
                .methods()
                .has_role(DISCOUNT_MANAGER_ROLE, manager)
                .simulate(Execution::state_read_only())
                .await
                .context("read a discount manager's role")?
                .value;
            if holds == should_hold {
                continue;
            }
            if should_hold {
                tracing::info!("Margin: adding discount manager {manager:?}");
                pool.methods()
                    .grant_role(DISCOUNT_MANAGER_ROLE, manager)
                    .call()
                    .await
                    .context("grant a discount manager its role")?;
            } else {
                tracing::info!("Margin: removing discount manager {manager:?}");
                pool.methods()
                    .revoke_role(DISCOUNT_MANAGER_ROLE, manager)
                    .call()
                    .await
                    .context("revoke a discount manager's role")?;
            }
        }
    }

    // Tier-only mode resolves no oracle of its own - ask the live registry,
    // which is the same lookup the backend performs at boot.
    let margin_oracle_id = match margin_oracle_id {
        Some(oracle_id) => Some(oracle_id),
        None if cosigner.is_some() => {
            let registry = o2_tools::trade_account_registry::TradeAccountRegistry::new(
                trade_account_registry_id,
                wallet.clone(),
            );
            let oracle_id = registry
                .methods()
                .get_prop_oracle_id()
                .simulate(Execution::state_read_only())
                .await
                .context("read the registry's prop account oracle")?
                .value;
            (oracle_id != ContractId::zeroed()).then_some(oracle_id)
        }
        None => None,
    };

    // The cosigner lives on the ORACLE, not the pool, and only reaches
    // storage through INITIAL_COSIGNER on the very first initialize - so an
    // already-initialized oracle needs this explicit reconciliation, or
    // "set it if provided" would silently mean "only on a fresh deploy".
    if let (Some(cosigner), Some(oracle_id)) = (cosigner, margin_oracle_id)
        && wallet.try_provider()?.contract_exists(&oracle_id).await?
    {
        let oracle = PropAccountOracleContract::new(oracle_id, wallet.clone());
        let current = oracle
            .methods()
            .get_cosigner()
            .simulate(Execution::state_read_only())
            .await
            .context("read the prop account oracle's cosigner")?
            .value;
        if current != Some(cosigner) {
            tracing::info!("Margin: cosigner {current:?} -> {cosigner:?}");
            oracle.methods().set_cosigner(cosigner).call().await?;
        }
    }

    // -- who may publish --------------------------------------------------
    // Compare-first, like every other reconcile here: the role is granted or
    // revoked only when the feed disagrees with the config, so a settled
    // roster sends nothing at all.
    //
    // An identity in BOTH lists would be granted and then revoked in the same
    // run, silently, decided by iteration order. Refuse the ambiguity.
    for entry in &margin.price_feed.publishers {
        anyhow::ensure!(
            !margin.price_feed.remove_publishers.contains(entry),
            "price feed publisher {entry} is listed in both `publishers` and \
             `remove_publishers`"
        );
    }
    let price_feed = PriceFeedContract::new(price_feed_id, wallet.clone());
    for (entry, should_hold) in margin
        .price_feed
        .publishers
        .iter()
        .map(|entry| (entry, true))
        .chain(
            margin
                .price_feed
                .remove_publishers
                .iter()
                .map(|entry| (entry, false)),
        )
    {
        let publisher = parse_margin_identity(entry)?;
        let holds = price_feed
            .methods()
            .has_role(o2_tools::prop_deploy::PRICE_SUBMITTER_ROLE, publisher)
            .simulate(Execution::state_read_only())
            .await
            .context("read a price feed publisher's submitter role")?
            .value;
        if holds == should_hold {
            continue;
        }
        if should_hold {
            tracing::info!("Margin: adding price feed publisher {publisher:?}");
            price_feed
                .methods()
                .add_publisher(publisher)
                .call()
                .await
                .context("grant a price feed publisher the submitter role")?;
        } else {
            tracing::info!("Margin: removing price feed publisher {publisher:?}");
            price_feed
                .methods()
                .remove_publisher(publisher)
                .call()
                .await
                .context("revoke a price feed publisher's submitter role")?;
        }
    }
    // -- the feed's implementation ---------------------------------------
    // Same contract as the order books: under `--upgrade-bytecode`, rebuild
    // the configured blob and retarget the proxy only when it differs, so a
    // feed already on this bytecode costs no transaction.
    //
    // Never in tier-only mode: that mode reconciles configuration, never
    // bytecode. Rotating a publisher must not also swap the implementation
    // every margin valuation reads.
    if upgrade_bytecode && !tier_only {
        o2_tools::prop_deploy::upgrade_price_feed_implementation(
            wallet,
            price_feed_id,
            // The blob's owner configurable must match what the fresh deploy
            // derived, or the retarget would chase a different blob id.
            prop_config
                .owner
                .unwrap_or(Identity::Address(wallet.address())),
            &prop_config,
        )
        .await
        .context("upgrade the price feed implementation")?;
    }

    // -- the feed's submission-age bound ----------------------------------
    // Also reconciled here, not just through the system deploy, so tier-only
    // mode honours it. Compare-first, so the settled case sends nothing and
    // the double-apply on a full deploy is free.
    if let Some(seconds) = margin.price_feed.max_offchain_age_seconds {
        let current = price_feed
            .methods()
            .get_max_offchain_age()
            .simulate(Execution::state_read_only())
            .await
            .context("read the price feed's submission-age bound")?
            .value;
        if current != seconds {
            tracing::info!("Margin: submission-age bound {current} -> {seconds}");
            price_feed
                .methods()
                .set_max_offchain_age(seconds)
                .call()
                .await
                .context("set the price feed's submission-age bound")?;
        }
    }

    // -- the feed's supported assets -------------------------------------
    // Registering decimals is what makes an asset known to the feed, and it
    // is independent of ever having a price: a tier catalogue publishes
    // against a feed configured this way even when no quote has ever been
    // seeded.
    for supported in &margin.price_feed.supported_assets {
        let current = price_feed
            .methods()
            .get_asset_decimals(supported.asset)
            .simulate(Execution::state_read_only())
            .await
            .context("read the price feed's asset decimals")?
            .value;
        match current {
            Some(decimals) if decimals == supported.decimals => continue,
            // Refused, not overwritten: the pool pins an asset's oracle
            // decimals on first use and reverts on a later change, so an
            // asset already live at other decimals would be stranded.
            Some(decimals) => anyhow::bail!(
                "price feed already knows {} at {decimals} decimals, config says \
                 {} - refusing to move it, since the pool pins decimals on first \
                 use and rejects a change",
                supported.asset,
                supported.decimals,
            ),
            None => {
                tracing::info!(
                    "Margin: registering {} at {} decimals on the feed",
                    supported.asset,
                    supported.decimals,
                );
                price_feed
                    .methods()
                    .set_asset_decimals(supported.asset, supported.decimals)
                    .call()
                    .await
                    .context("register a supported asset on the price feed")?;
            }
        }
    }

    let pool = PropMarginPoolContract::new(margin_pool_id, wallet.clone());
    let pool_reachable = wallet
        .try_provider()?
        .contract_exists(&margin_pool_id)
        .await?;

    // -- the feed the POOL values against ---------------------------------
    // `INITIAL_PRICE_FEED` only reaches storage through the pool's one-time
    // `initialize`, so a pool that is already live keeps its old feed no
    // matter what the config says. Reconcile it explicitly, or "point the
    // pool at this feed" would silently mean "only on a fresh deploy".
    //
    // Runs AFTER the supported-assets step on purpose: `set_price_feed`
    // validates that the replacement already knows every admitted asset at
    // the pinned decimals, which is exactly what that step registers.
    if pool_reachable {
        let live_feed = pool
            .methods()
            .price_feed()
            .simulate(Execution::state_read_only())
            .await
            .context("read the pool's price feed")?
            .value;
        if live_feed != price_feed_id {
            tracing::info!("Margin: pool price feed {live_feed} -> {price_feed_id}");
            pool.methods()
                .set_price_feed(price_feed_id)
                // `validate_replacement_feed` calls INTO the new feed once per
                // admitted asset, so it must ride as an input.
                .with_contract_ids(&[price_feed_id])
                .call()
                .await
                .context(
                    "point the pool at the configured price feed - the \
                     replacement must already know every admitted asset at the \
                     decimals the pool pinned",
                )?;
        }
    }

    // -- the tier catalogue ---------------------------------------------
    // The pool is unreachable only when the system deploy did not run, which
    // means tier-only mode against a pool the config NAMES but the chain does
    // not have. The guard above only checks that a pool is named, so refuse
    // here rather than skip: a run that publishes no tiers and reports
    // success is the failure an operator cannot see.
    anyhow::ensure!(
        pool_reachable || margin.tiers.is_empty(),
        "margin pool {margin_pool_id} is not on chain, so its {} configured \
         tier(s) cannot be reconciled",
        margin.tiers.len()
    );
    if pool_reachable {
        reconcile_margin_tiers(
            &pool,
            price_feed_id,
            pairs,
            &margin.tiers,
            prop_config.collateral_decimals,
        )
        .await?;
    }

    Ok(MarginIds {
        price_feed_id,
        margin_pool_id,
        margin_oracle_id,
    })
}

/// The tier engine: reconcile the DECLARED catalogue against the LIVE
/// pool, idempotently.
///
/// - no live version              -> publish version 1;
/// - params differ from the live  -> publish a NEW version;
/// - params equal, books grew     -> `add_books` with the missing books;
/// - params equal, books covered  -> untouched (books are append-only:
///   a SHRUNK declared list cannot be enacted and is reported).
async fn reconcile_margin_tiers<W>(
    pool: &o2_tools::prop::PropMarginPoolContract<W>,
    price_feed_id: ContractId,
    pairs: &[OrderBookConfig],
    tiers: &[MarginTierConfig],
    collateral_decimals: u8,
) -> anyhow::Result<()>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    for tier in tiers {
        let books = tier
            .markets
            .iter()
            .map(|market| resolve_tier_market(market, pairs))
            .collect::<anyhow::Result<Vec<_>>>()?;
        let params = tier_params(tier, collateral_decimals)?;
        let current_version = pool
            .methods()
            .current_tier_version(tier.tier_id)
            .simulate(Execution::state_read_only())
            .await?
            .value;

        let mut contract_ids = vec![price_feed_id];
        contract_ids.extend(books.iter().copied());

        let Some(version) = current_version else {
            let version = pool
                .methods()
                .publish_tier_version(tier.tier_id, params, books)
                .with_contract_ids(&contract_ids)
                .call()
                .await?
                .value;
            tracing::info!("Margin: tier {} published version {version}", tier.tier_id);
            continue;
        };

        let live = pool
            .methods()
            .get_tier(tier.tier_id, version)
            .simulate(Execution::state_read_only())
            .await?
            .value
            .with_context(|| {
                format!("tier {} version {version} vanished mid-read", tier.tier_id)
            })?;
        if live != params {
            let new_version = pool
                .methods()
                .publish_tier_version(tier.tier_id, params, books)
                .with_contract_ids(&contract_ids)
                .call()
                .await?
                .value;
            tracing::info!(
                "Margin: tier {} republished as version {new_version}",
                tier.tier_id
            );
            continue;
        }

        let live_books = pool
            .methods()
            .tier_books(tier.tier_id, version)
            .simulate(Execution::state_read_only())
            .await?
            .value;
        let missing: Vec<ContractId> = books
            .iter()
            .copied()
            .filter(|book| !live_books.contains(book))
            .collect();
        let shrunk = live_books
            .iter()
            .filter(|book| !books.contains(book))
            .count();
        if shrunk > 0 {
            tracing::warn!(
                "Margin: tier {} declares {shrunk} fewer book(s) than live version \
                 {version}; books are append-only — publish a new version to drop \
                 markets",
                tier.tier_id
            );
        }
        if missing.is_empty() {
            tracing::info!(
                "Margin: tier {} version {version} matches the declared catalogue — \
                 unchanged",
                tier.tier_id
            );
            continue;
        }
        let mut add_contract_ids = vec![price_feed_id];
        add_contract_ids.extend(missing.iter().copied());
        pool.methods()
            .add_books(tier.tier_id, missing.clone())
            .with_contract_ids(&add_contract_ids)
            .call()
            .await?;
        tracing::info!(
            "Margin: tier {} version {version} gained {} book(s)",
            tier.tier_id,
            missing.len()
        );
    }
    Ok(())
}

/// Whole collateral units (`"7.5"`) into base units, EXACTLY.
///
/// Never through `f64`: a binary float cannot hold most decimal fractions, so
/// `"7.1"` at 9 decimals would land on 7_099_999_999 - and this is money. The
/// integer is built from the digits instead.
///
/// More fractional digits than the asset has is an ERROR, not a rounding: a
/// figure the chain cannot represent is a figure the operator did not mean.
fn collateral_amount(value: &str, decimals: u8, field: &str) -> anyhow::Result<u64> {
    let raw = value.trim();
    anyhow::ensure!(!raw.is_empty(), "{field}: empty amount");
    anyhow::ensure!(
        !raw.starts_with('-'),
        "{field}: `{raw}` is negative; fees are unsigned"
    );
    let (whole, fraction) = match raw.split_once('.') {
        Some((whole, fraction)) => (whole, fraction),
        None => (raw, ""),
    };
    anyhow::ensure!(
        !fraction.contains('.'),
        "{field}: `{raw}` has more than one decimal point"
    );
    anyhow::ensure!(
        !whole.is_empty() && whole.bytes().all(|b| b.is_ascii_digit()),
        "{field}: `{raw}` is not a decimal amount"
    );
    anyhow::ensure!(
        fraction.bytes().all(|b| b.is_ascii_digit()),
        "{field}: `{raw}` is not a decimal amount"
    );
    let decimals = usize::from(decimals);
    anyhow::ensure!(
        fraction.len() <= decimals,
        "{field}: `{raw}` has {} decimal places, but the collateral asset has \
         only {decimals}; the chain cannot represent it",
        fraction.len()
    );
    let digits = format!("{whole}{fraction}{}", "0".repeat(decimals - fraction.len()));
    digits
        .parse::<u64>()
        .map_err(|e| anyhow::anyhow!("{field}: `{raw}` does not fit a u64: {e}"))
}

fn tier_params(
    tier: &MarginTierConfig,
    collateral_decimals: u8,
) -> anyhow::Result<o2_tools::prop::TierParams> {
    let fee = |value: &str, what: &str| {
        collateral_amount(
            value,
            collateral_decimals,
            &format!("tier {} {what}", tier.tier_id),
        )
    };
    Ok(o2_tools::prop::TierParams {
        line: tier.line,
        leverage: tier.leverage,
        duration: tier.duration,
        maintenance_bps: tier.maintenance_bps,
        open_buffer_bps: tier.open_buffer_bps,
        liq_price_factor: tier.liq_price_factor,
        prolong_fee: [
            fee(&tier.prolong_fee[0], "prolong_fee[0]")?,
            fee(&tier.prolong_fee[1], "prolong_fee[1]")?,
            fee(&tier.prolong_fee[2], "prolong_fee[2]")?,
            fee(&tier.prolong_fee[3], "prolong_fee[3]")?,
        ],
        max_credit_line_bps: tier.max_credit_line_bps,
        max_price_age: tier.max_price_age,
        open_fee: fee(&tier.open_fee, "open_fee")?,
        profit_share_bps: tier.profit_share_bps,
        price_band_bps: tier.price_band_bps,
    })
}

/// Resolve a tier `markets` entry — a "BASE/QUOTE" symbol pair or a hex
/// market id — to the deployed order book's contract id.
fn resolve_tier_market(
    market: &str,
    pairs: &[OrderBookConfig],
) -> anyhow::Result<ContractId> {
    let wanted = market.trim();
    let wanted_id = wanted
        .strip_prefix("0x")
        .unwrap_or(wanted)
        .to_ascii_lowercase();
    let pair = pairs
        .iter()
        .find(|pair| {
            let symbol = format!("{}/{}", pair.base.symbol, pair.quote.symbol);
            symbol.eq_ignore_ascii_case(wanted)
                || hex::encode(*pair.market_id) == wanted_id
        })
        .with_context(|| format!("margin tier references unknown market `{market}`"))?;
    pair.contract_id.with_context(|| {
        format!("margin tier market `{market}` has no deployed order book")
    })
}

/// `address:0x..` or `contract:0x..` into an `Identity`.
fn parse_margin_identity(s: &str) -> anyhow::Result<Identity> {
    if let Some(hex_part) = s.strip_prefix("address:") {
        Ok(Identity::Address(fuels::types::Address::new(
            parse_margin_bytes32(hex_part)?,
        )))
    } else if let Some(hex_part) = s.strip_prefix("contract:") {
        Ok(Identity::ContractId(ContractId::new(parse_margin_bytes32(
            hex_part,
        )?)))
    } else {
        anyhow::bail!("expected `address:0x..` or `contract:0x..`, got `{s}`")
    }
}

fn parse_margin_bytes32(s: &str) -> anyhow::Result<[u8; 32]> {
    let raw = s.trim().strip_prefix("0x").unwrap_or(s.trim());
    let bytes = hex::decode(raw)
        .map_err(|e| anyhow::anyhow!("expected 32 hex bytes, got `{s}`: {e}"))?;
    bytes
        .try_into()
        .map_err(|_| anyhow::anyhow!("expected 32 hex bytes, got `{s}`"))
}

// ---------------------------------------------------------------------------
// Ownership transfer
// ---------------------------------------------------------------------------

#[allow(clippy::too_many_arguments)]
async fn transfer_ownership<W>(
    wallet: &W,
    params: &DeployParams,
    order_book_registry: &OrderBookRegistryManager<W>,
    trade_account_registry: &TradeAccountRegistryManager<W>,
    trade_account_oracle_deploy: &TradeAccountDeploy<W>,
    trial_trade_account_oracle_id: ContractId,
    order_book_blacklist_id: Option<ContractId>,
    order_book_whitelist_id: Option<ContractId>,
) -> anyhow::Result<()>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    if let Some(new_proxy_owner) = params.new_proxy_owner {
        let new_identity = Identity::Address(new_proxy_owner);
        tracing::info!(
            "Transferring OrderBookRegistry proxy ownership to {}",
            new_proxy_owner
        );
        order_book_registry
            .registry_proxy
            .methods()
            .set_owner(new_identity)
            .call()
            .await?;
        tracing::info!(
            "Transferring TradeAccountRegistry proxy ownership to {}",
            new_proxy_owner
        );
        trade_account_registry
            .registry_proxy
            .methods()
            .set_owner(new_identity)
            .call()
            .await?;
    }

    if let Some(new_contract_owner) = params.new_contract_owner {
        let new_identity = Identity::Address(new_contract_owner);
        tracing::info!(
            "Transferring TradeAccountOracle ownership to {}",
            new_contract_owner
        );
        trade_account_oracle_deploy
            .oracle
            .methods()
            .transfer_ownership(new_identity)
            .call()
            .await?;
        tracing::info!(
            "Transferring TrialTradeAccountOracle ownership to {}",
            new_contract_owner
        );
        TrialTradingAccountOracle::new(trial_trade_account_oracle_id, wallet.clone())
            .methods()
            .transfer_ownership(new_identity)
            .call()
            .await?;
        tracing::info!(
            "Transferring TradeAccountRegistry ownership to {}",
            new_contract_owner
        );
        trade_account_registry
            .registry
            .methods()
            .transfer_ownership(new_identity)
            .call()
            .await?;
        tracing::info!(
            "Transferring OrderBookRegistry ownership to {}",
            new_contract_owner
        );
        order_book_registry
            .registry
            .methods()
            .transfer_ownership(new_identity)
            .call()
            .await?;
        if let Some(blacklist_id) = order_book_blacklist_id {
            tracing::info!(
                "Transferring OrderBookBlacklist ownership to {}",
                new_contract_owner
            );
            OrderBookBlacklist::new(blacklist_id, wallet.clone())
                .methods()
                .transfer_ownership(new_identity)
                .call()
                .await?;
        }
        if let Some(whitelist_id) = order_book_whitelist_id {
            tracing::info!(
                "Transferring OrderBookWhitelist ownership to {}",
                new_contract_owner
            );
            OrderBookWhitelist::new(whitelist_id, wallet.clone())
                .methods()
                .transfer_ownership(new_identity)
                .call()
                .await?;
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Internal deploy helpers
// ---------------------------------------------------------------------------

async fn deploy_order_book_blacklist<W>(
    deployer_wallet: W,
    deploy_blacklist: bool,
    order_book_blacklist_id: Option<ContractId>,
    salt: Salt,
) -> anyhow::Result<Option<ContractId>>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    match order_book_blacklist_id {
        Some(order_book_blacklist_id) => {
            tracing::info!(
                "Using existing OrderBookBlacklist: {}",
                order_book_blacklist_id
            );
            Ok(Some(order_book_blacklist_id))
        }
        None => {
            if !deploy_blacklist {
                return Ok(None);
            }
            tracing::info!("Deploying OrderBookBlacklist");
            let order_book_blacklist = OrderBookDeploy::deploy_order_book_blacklist(
                &deployer_wallet,
                &Identity::Address(ViewOnlyAccount::address(&deployer_wallet)),
                &OrderBookDeployConfig {
                    salt,
                    ..Default::default()
                },
            )
            .await?;
            tracing::info!("OrderBookBlacklist: {}", order_book_blacklist.contract_id());
            Ok(Some(order_book_blacklist.contract_id()))
        }
    }
}

async fn deploy_order_book_whitelist<W>(
    deployer_wallet: W,
    deploy_whitelist: bool,
    order_book_whitelist_id: Option<ContractId>,
    salt: Salt,
) -> anyhow::Result<Option<ContractId>>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    match (order_book_whitelist_id, deploy_whitelist) {
        (Some(order_book_whitelist_id), false)
        | (Some(order_book_whitelist_id), true) => {
            tracing::info!(
                "Using existing OrderBookWhitelist: {}",
                order_book_whitelist_id
            );
            Ok(Some(order_book_whitelist_id))
        }
        (None, false) => Ok(None),
        (None, true) => {
            tracing::info!("Deploying OrderBookWhitelist");
            let trade_account_whitelist = OrderBookDeploy::deploy_order_book_whitelist(
                &deployer_wallet,
                &Identity::Address(ViewOnlyAccount::address(&deployer_wallet)),
                &OrderBookDeployConfig {
                    salt,
                    ..Default::default()
                },
            )
            .await?;
            tracing::info!(
                "OrderBookWhitelist: {}",
                trade_account_whitelist.contract_id()
            );
            Ok(Some(trade_account_whitelist.contract_id()))
        }
    }
}

/// Load an existing oracle and recover from partial deployment if needed.
/// Unlike `TradeAccountDeploy::from_oracle_id`, this does not error when
/// the trade account implementation is missing — it deploys and sets it.
async fn load_or_recover_trade_account_oracle<W>(
    deployer_wallet: &W,
    oracle_id: ContractId,
) -> anyhow::Result<(TradeAccountDeploy<W>, ContractId)>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    let oracle = TradingAccountOracle::new(oracle_id, deployer_wallet.clone());
    let impl_id = oracle
        .methods()
        .get_trade_account_impl()
        .simulate(Execution::state_read_only())
        .await?
        .value;

    let blob_id = match impl_id {
        Some(id) => id,
        None => {
            tracing::info!(
                "Trade account implementation not set on oracle {}, deploying...",
                oracle_id
            );
            let blob = TradeAccountDeploy::trade_account_blob(
                deployer_wallet,
                &Default::default(),
            )
            .await?;
            TradeAccountDeploy::deploy_trade_account_blob(
                deployer_wallet,
                &DeployConfig::Latest(Default::default()),
            )
            .await?;
            oracle
                .methods()
                .set_trade_account_impl(ContractId::from(blob.id))
                .call()
                .await?;
            ContractId::from(blob.id)
        }
    };

    let deploy = TradeAccountDeploy {
        oracle,
        oracle_id,
        trade_account_blob_id: blob_id.into(),
        deployer_wallet: deployer_wallet.clone(),
        proxy: None,
        proxy_id: None,
    };
    Ok((deploy, blob_id))
}

async fn deploy_trade_account_oracle<W>(
    deployer_wallet: W,
    should_upgrade_bytecode: bool,
    trade_account_oracle_id: Option<ContractId>,
    salt: Salt,
) -> anyhow::Result<(TradeAccountDeploy<W>, ContractId)>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    let (trade_account_oracle_deploy, mut trade_account_blob_id) =
        match trade_account_oracle_id {
            Some(oracle_id) => {
                load_or_recover_trade_account_oracle(&deployer_wallet, oracle_id).await?
            }
            None => {
                let deploy = TradeAccountDeploy::deploy(
                    &deployer_wallet,
                    &DeployConfig::Latest(TradeAccountDeployConfig {
                        salt,
                        ..Default::default()
                    }),
                )
                .await?;
                let blob_id = deploy
                    .oracle
                    .methods()
                    .get_trade_account_impl()
                    .simulate(Execution::state_read_only())
                    .await?
                    .value
                    .context("Trade account impl should exist after fresh deploy")?;
                (deploy, blob_id)
            }
        };
    tracing::info!(
        "TradeAccountOracle: {}",
        trade_account_oracle_deploy.oracle_id
    );

    if should_upgrade_bytecode {
        let trade_account_blob =
            TradeAccountDeploy::trade_account_blob(&deployer_wallet, &Default::default())
                .await?;
        if ContractId::from(trade_account_blob.id) != trade_account_blob_id {
            tracing::info!(
                "Update TradeAccountImpl on Oracle from {:?} to new blob {:?}",
                trade_account_blob_id,
                ContractId::from(trade_account_blob.id)
            );
            TradeAccountDeploy::deploy_trade_account_blob(
                &deployer_wallet,
                &DeployConfig::Latest(Default::default()),
            )
            .await?;
            trade_account_oracle_deploy
                .oracle
                .methods()
                .set_trade_account_impl(ContractId::from(trade_account_blob.id))
                .call()
                .await?;
            trade_account_blob_id = ContractId::from(trade_account_blob.id);
        }
    }

    Ok((trade_account_oracle_deploy, trade_account_blob_id))
}

/// Deploy (or load) the dedicated trial trade account oracle and keep its
/// implementation current. The implementation follows the trade-account
/// implementation's lifecycle: seeded when the oracle has none, upgraded
/// under `should_upgrade_bytecode`. The cosigner is opt-in: providing one
/// also (re)deploys the implementation and configures the cosigner; without
/// one, the configured cosigner is left untouched. This runs before
/// ownership transfer since it writes to the oracle.
async fn deploy_trial_trade_account_oracle<W>(
    deployer_wallet: W,
    should_upgrade_bytecode: bool,
    trial_trade_account_oracle_id: Option<ContractId>,
    trial_cosigner: Option<fuels::types::Address>,
    salt: Salt,
) -> anyhow::Result<ContractId>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    let mut trial_deploy_config = TrialTradeAccountDeployConfig {
        salt,
        ..Default::default()
    };
    if let Some(cosigner) = trial_cosigner {
        trial_deploy_config = trial_deploy_config.with_cosigner(cosigner);
    }
    let deploy_config = TrialDeployConfig::Latest(trial_deploy_config);

    let oracle_id = match trial_trade_account_oracle_id {
        None => {
            let trial_deploy =
                TrialTradeAccountDeploy::deploy(&deployer_wallet, &deploy_config).await?;
            tracing::info!(
                "TrialTradeAccountOracle: {} (implementation {:?}, cosigner {:?})",
                trial_deploy.oracle_id,
                trial_deploy.trial_trade_account_blob_id,
                trial_cosigner,
            );
            trial_deploy.oracle_id
        }
        Some(oracle_id) => {
            let current_trial_impl =
                TrialTradingAccountOracle::new(oracle_id, deployer_wallet.clone())
                    .methods()
                    .get_trial_account_impl()
                    .simulate(Execution::state_read_only())
                    .await?
                    .value;
            if current_trial_impl.is_none()
                || should_upgrade_bytecode
                || trial_cosigner.is_some()
            {
                let trial_deploy = TrialTradeAccountDeploy::deploy_to_oracle(
                    &deployer_wallet,
                    oracle_id,
                    &deploy_config,
                )
                .await?;
                tracing::info!(
                    "Trial implementation {:?} deployed to oracle {} (cosigner {:?})",
                    trial_deploy.trial_trade_account_blob_id,
                    oracle_id,
                    trial_cosigner,
                );
            }
            oracle_id
        }
    };

    Ok(oracle_id)
}

async fn deploy_trade_account_registry<W>(
    deployer_wallet: W,
    should_upgrade_bytecode: bool,
    trade_account_deploy: TradeAccountDeploy<W>,
    trial_trade_account_oracle_id: ContractId,
    trade_account_registry_id: Option<ContractId>,
    salt: Salt,
) -> anyhow::Result<(TradeAccountRegistryManager<W>, ContractId)>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    let trade_account_oracle_id = trade_account_deploy.oracle_id;
    let trade_account_registry = match trade_account_registry_id {
        Some(trade_account_registry_contract_id) => TradeAccountRegistryManager::new(
            deployer_wallet.clone(),
            trade_account_registry_contract_id,
        ),
        None => {
            let trade_account_registry_deploy_config = TradeAccountRegistryDeployConfig {
                salt,
                ..Default::default()
            };
            TradeAccountRegistryManager::deploy(
                &deployer_wallet,
                trade_account_oracle_id,
                trial_trade_account_oracle_id,
                &trade_account_registry_deploy_config,
            )
            .await?
        }
    };
    tracing::info!(
        "TradeAccountRegistry: {}",
        trade_account_registry.contract_id
    );
    let mut trade_account_registry_blob_id = match trade_account_registry
        .registry_proxy
        .methods()
        .proxy_target()
        .simulate(Execution::state_read_only())
        .await?
        .value
    {
        Some(blob_id) => blob_id,
        None => {
            tracing::info!("TradeAccountRegistry proxy target not set, initializing...");
            // Call initialize_proxy() to write INITIAL_OWNER and INITIAL_TARGET
            // from configurables to storage (upgrade/set_proxy_target would fail
            // because the owner is not yet in storage)
            trade_account_registry
                .registry_proxy
                .methods()
                .initialize_proxy()
                .call()
                .await?;
            trade_account_registry
                .registry
                .methods()
                .initialize()
                .call()
                .await?;
            trade_account_registry
                .registry_proxy
                .methods()
                .proxy_target()
                .simulate(Execution::state_read_only())
                .await?
                .value
                .context("TradeAccountRegistry proxy target should be set after initialization")?
        }
    };

    if should_upgrade_bytecode {
        // The rebuilt blob carries whatever this config says and DEFAULTS
        // everything else — so the prop wiring has to be repeated here or
        // the upgrade silently zeroes it. See `live_prop_registry_config`.
        let trade_account_registry_deploy_config = TradeAccountRegistryDeployConfig {
            registry_config: trade_account_registry
                .live_prop_config(TradeAccountRegistryConfigurables::default())
                .await?,
            ..Default::default()
        };
        let trade_account_proxy_blob = TradeAccountRegistryManager::register_proxy_blob(
            &deployer_wallet,
            &trade_account_registry_deploy_config,
        )
        .await?;
        let trial_trade_account_proxy_blob =
            TradeAccountRegistryManager::register_trial_proxy_blob(
                &deployer_wallet,
                &trade_account_registry_deploy_config,
            )
            .await?;

        let trade_account_register_blob = TradeAccountRegistryManager::register_blob(
            &deployer_wallet,
            trade_account_oracle_id,
            trial_trade_account_oracle_id,
            trade_account_proxy_blob.id,
            trial_trade_account_proxy_blob.id,
            &trade_account_registry_deploy_config,
        )
        .await?;

        if trade_account_registry_blob_id
            != ContractId::from(trade_account_register_blob.id)
        {
            tracing::info!(
                "Upgrade TradeAccountRegistry blob from {:?} to {:?}",
                trade_account_registry.contract_id,
                ContractId::from(trade_account_register_blob.id)
            );
            // The SAME config the blob above was computed from: `upgrade`
            // rebuilds the blob internally, so passing a different one
            // would retarget the proxy at something we never compared.
            trade_account_registry
                .upgrade(
                    trade_account_oracle_id,
                    trial_trade_account_oracle_id,
                    &trade_account_registry_deploy_config,
                )
                .await?;
            trade_account_registry_blob_id = trade_account_register_blob.id.into();
        }
    }
    Ok((trade_account_registry, trade_account_registry_blob_id))
}

async fn deploy_order_book_registry<W>(
    deployer_wallet: W,
    should_upgrade_bytecode: bool,
    order_book_registry_id: Option<ContractId>,
    salt: Salt,
) -> anyhow::Result<(OrderBookRegistryManager<W>, ContractId)>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    let order_book_registry = match order_book_registry_id {
        Some(registry_contract_id) => {
            OrderBookRegistryManager::new(deployer_wallet.clone(), registry_contract_id)
        }
        None => {
            OrderBookRegistryManager::deploy(
                &deployer_wallet,
                &OrderBookRegistryDeployConfig {
                    salt,
                    ..Default::default()
                },
            )
            .await?
        }
    };
    tracing::info!("OrderBookRegistry: {}", order_book_registry.contract_id);
    let mut order_book_registry_blob_id = match order_book_registry
        .registry_proxy
        .methods()
        .proxy_target()
        .simulate(Execution::state_read_only())
        .await?
        .value
    {
        Some(blob_id) => blob_id,
        None => {
            tracing::info!("OrderBookRegistry proxy target not set, initializing...");
            // Call initialize_proxy() to write INITIAL_OWNER and INITIAL_TARGET
            // from configurables to storage (upgrade/set_proxy_target would fail
            // because the owner is not yet in storage)
            order_book_registry
                .registry_proxy
                .methods()
                .initialize_proxy()
                .call()
                .await?;
            order_book_registry
                .registry
                .methods()
                .initialize()
                .call()
                .await?;
            order_book_registry
                .registry_proxy
                .methods()
                .proxy_target()
                .simulate(Execution::state_read_only())
                .await?
                .value
                .context(
                    "OrderBookRegistry proxy target should be set after initialization",
                )?
        }
    };

    if should_upgrade_bytecode {
        let order_book_register_deploy_config = OrderBookRegistryDeployConfig::default();
        let order_book_register_blob = OrderBookRegistryManager::register_blob(
            &deployer_wallet,
            &order_book_register_deploy_config,
        )
        .await?;
        if order_book_registry_blob_id != order_book_register_blob.id.into() {
            tracing::info!(
                "Upgrade OrderBookRegistry blob from {:?} to {:?}",
                order_book_registry.contract_id,
                ContractId::from(order_book_register_blob.id)
            );
            order_book_registry
                .upgrade(&order_book_register_deploy_config)
                .await?;
            order_book_registry_blob_id = order_book_register_blob.id.into();
        }
    }

    Ok((order_book_registry, order_book_registry_blob_id))
}

async fn deploy_order_books<W>(
    deployer_wallet: W,
    should_upgrade_bytecode: bool,
    order_book_blacklist_id: Option<ContractId>,
    order_book_whitelist_id: Option<ContractId>,
    order_book_registry: OrderBookRegistryManager<W>,
    order_book_configs: &mut [OrderBookConfig],
    ownership_options: OwnershipTransferOptions,
) -> anyhow::Result<Vec<OrderBookConfig>>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    // Pre-flight every pair before deploying any of them. A precision budget
    // breach is a config mistake, and the loop below deploys and registers as it
    // goes — failing on pair N would otherwise leave 1..N-1 live on chain, with
    // an append-only registry that cannot take them back.
    audit_order_book_precision(order_book_configs)?;

    let mut pairs: Vec<OrderBookConfig> = Vec::with_capacity(order_book_configs.len());

    for order_book_config in order_book_configs.iter_mut() {
        let pair = deploy_single_order_book(
            &deployer_wallet,
            should_upgrade_bytecode,
            order_book_blacklist_id,
            order_book_whitelist_id,
            &order_book_registry,
            order_book_config,
            &ownership_options,
        )
        .await?;
        pairs.push(pair);
    }

    Ok(pairs)
}

async fn deploy_single_order_book<W>(
    deployer_wallet: &W,
    should_upgrade_bytecode: bool,
    order_book_blacklist_id: Option<ContractId>,
    order_book_whitelist_id: Option<ContractId>,
    order_book_registry: &OrderBookRegistryManager<W>,
    order_book_config: &mut OrderBookConfig,
    ownership_options: &OwnershipTransferOptions,
) -> anyhow::Result<OrderBookConfig>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    let market_symbol = format!(
        "{}/{}",
        order_book_config.base.symbol, order_book_config.quote.symbol
    );
    let market_id = MarketIdAssets {
        base_asset: order_book_config.base.asset,
        quote_asset: order_book_config.quote.asset,
    };
    let order_book_configurables = build_order_book_configurables(
        order_book_config,
        order_book_blacklist_id,
        order_book_whitelist_id,
        deployer_wallet,
    )?;

    let order_book = load_or_deploy_order_book(
        deployer_wallet,
        order_book_registry,
        &market_id,
        &market_symbol,
        &order_book_configurables,
        order_book_config,
    )
    .await?;

    tracing::info!(
        "[{}] OrderBook: {}",
        market_symbol,
        order_book.contract.contract_id()
    );

    let order_book_blob_id = maybe_upgrade_order_book(
        deployer_wallet,
        should_upgrade_bytecode,
        &order_book,
        order_book_config,
        order_book_configurables,
        &market_symbol,
    )
    .await?;

    // Set the maintainer while the deployer is still the owner, i.e. before any
    // ownership transfer below (`owner_grant_role`/`owner_revoke_role` are
    // `only_owner`).
    set_order_book_maintainer(&order_book, ownership_options, &market_symbol).await?;

    transfer_order_book_ownership(&order_book, ownership_options, &market_symbol).await?;

    order_book_config.contract_id = Some(order_book.contract.contract_id());
    order_book_config.blob_id = order_book_blob_id.into();

    Ok(order_book_config.clone())
}

/// Checks every pair against its precision budget, naming the first offender.
///
/// The deploy path calls this before it touches the chain; it is public so a
/// config can be audited without one — CI, a linter, or `o2-api`'s
/// `validate_markets_config` example — against the same rule the deploy
/// enforces rather than a re-derived copy of it. See
/// [`order_book_precision_exponents`] for what the budget is and why.
pub fn audit_order_book_precision(configs: &[OrderBookConfig]) -> anyhow::Result<()> {
    for config in configs {
        order_book_precision_exponents(config)?;
    }
    Ok(())
}

/// The exponents behind `PRICE_PRECISION` and `QUANTITY_PRECISION`, after
/// checking the pair fits its precision budget.
///
/// The book settles a fill as `quantity * price / BASE_DECIMALS`
/// (`quote_coins_from_quantity`). A price on a
/// `10^(quote.decimals - quote.max_precision)` grid and a quantity on a
/// `10^(base.decimals - base.max_precision)` grid therefore put the notional on
/// a grid of `10^(quote.decimals - quote.max_precision - base.max_precision)`
/// quote atoms — so the two `max_precision` values are spending one shared
/// budget of `quote.decimals` digits.
///
/// Overspend it and the notional is a fraction of an atom the quote asset
/// cannot hold. Under `ALLOW_FRACTIONAL_PRICE = false` `quote_would_truncate`
/// turns that into a `FractionalPrice` revert on *every* order the book ever
/// receives; with fractional prices allowed it silently truncates instead.
///
/// Nothing downstream catches this: an over-budget book deploys, registers and
/// serves from `/v1/markets` looking healthy, and only fails when someone tries
/// to trade it.
fn order_book_precision_exponents(config: &OrderBookConfig) -> anyhow::Result<(u8, u8)> {
    let price_precision = config
        .quote
        .decimals
        .checked_sub(config.quote.max_precision)
        .ok_or_else(|| {
            anyhow::anyhow!(
                "quote max_precision ({}) exceeds decimals ({})",
                config.quote.max_precision,
                config.quote.decimals
            )
        })?;
    let quantity_precision = config
        .base
        .decimals
        .checked_sub(config.base.max_precision)
        .ok_or_else(|| {
            anyhow::anyhow!(
                "base max_precision ({}) exceeds decimals ({})",
                config.base.max_precision,
                config.base.decimals
            )
        })?;

    // Widen before summing: the checks above bound each side by its own
    // decimals, which still leaves room to wrap a u8.
    let spent = config.base.max_precision as u16 + config.quote.max_precision as u16;
    let budget = config.quote.decimals as u16;

    if config.allow_fractional_price {
        if spent > budget {
            tracing::warn!(
                "{}/{}: base max_precision ({}) + quote max_precision ({}) = {spent} \
                 exceeds the quote's {budget} decimals; ALLOW_FRACTIONAL_PRICE is set, \
                 so notionals will silently truncate rather than revert",
                config.base.symbol,
                config.quote.symbol,
                config.base.max_precision,
                config.quote.max_precision,
            );
        }
    } else {
        anyhow::ensure!(
            spent <= budget,
            "{}/{}: base max_precision ({}) + quote max_precision ({}) = {spent} \
             exceeds the quote's {budget} decimals, so every order would revert \
             with FractionalPrice. Lower one of the two until they sum to {budget} \
             or less.",
            config.base.symbol,
            config.quote.symbol,
            config.base.max_precision,
            config.quote.max_precision,
        );
    }

    Ok((price_precision, quantity_precision))
}

fn build_order_book_configurables<W: ViewOnlyAccount>(
    config: &OrderBookConfig,
    order_book_blacklist_id: Option<ContractId>,
    order_book_whitelist_id: Option<ContractId>,
    deployer_wallet: &W,
) -> anyhow::Result<OrderBookConfigurables> {
    let (price_precision, quantity_precision) = order_book_precision_exponents(config)?;

    Ok(OrderBookConfigurables::default()
        .with_MIN_ORDER(config.min_order)?
        .with_ALLOW_FRACTIONAL_PRICE(config.allow_fractional_price)?
        .with_TAKER_FEE(config.taker_fee.into())?
        .with_MAKER_FEE(config.maker_fee.into())?
        .with_DUST(config.dust)?
        .with_PRICE_WINDOW(config.price_window as u64)?
        .with_BASE_DECIMALS(10u64.pow(config.base.decimals as u32))?
        .with_QUOTE_DECIMALS(10u64.pow(config.quote.decimals as u32))?
        .with_BASE_SYMBOL(SizedAsciiString::new_with_right_whitespace_padding(
            config.base.symbol.clone(),
        )?)?
        .with_QUOTE_SYMBOL(SizedAsciiString::new_with_right_whitespace_padding(
            config.quote.symbol.clone(),
        )?)?
        .with_PRICE_PRECISION(10u64.pow(price_precision as u32))?
        .with_QUANTITY_PRECISION(10u64.pow(quantity_precision as u32))?
        .with_INITIAL_OWNER(o2_tools::order_book_deploy::State::Initialized(
            Identity::Address(ViewOnlyAccount::address(deployer_wallet)),
        ))?
        .with_WHITE_LIST_CONTRACT(order_book_whitelist_id)?
        .with_BLACK_LIST_CONTRACT(order_book_blacklist_id)?)
}

async fn load_or_deploy_order_book<W>(
    deployer_wallet: &W,
    order_book_registry: &OrderBookRegistryManager<W>,
    market_id: &MarketIdAssets,
    market_symbol: &str,
    order_book_configurables: &OrderBookConfigurables,
    order_book_config: &OrderBookConfig,
) -> anyhow::Result<OrderBookManager<W>>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    let register_contract_id = order_book_registry
        .registry
        .methods()
        .get_order_book(to_registry_market_id(market_id))
        .simulate(Execution::state_read_only())
        .await?
        .value;

    match register_contract_id {
        Some(contract_id) => {
            let order_book_deploy = OrderBookDeploy::new(
                deployer_wallet.clone(),
                contract_id,
                market_id.base_asset,
                market_id.quote_asset,
            );
            // Handle partially deployed contracts (e.g. previous deploy failed
            // after registering but before initializing the proxy)
            let proxy_target = order_book_deploy
                .order_book_proxy
                .methods()
                .proxy_target()
                .simulate(Execution::state_read_only())
                .await?
                .value;
            if proxy_target.is_none() {
                tracing::info!(
                    "[{}] Proxy target not set, initializing...",
                    market_symbol
                );
                order_book_deploy.initialize().await?;
            }
            Ok(OrderBookManager::new(
                deployer_wallet,
                10u64.pow(order_book_config.base.decimals as u32),
                10u64.pow(order_book_config.quote.decimals as u32),
                &order_book_deploy,
            ))
        }
        None => {
            let (order_book_deployment, initialization_required) =
                OrderBookDeploy::deploy_without_initialization(
                    deployer_wallet,
                    market_id.base_asset,
                    market_id.quote_asset,
                    &OrderBookDeployConfig {
                        order_book_configurables: order_book_configurables.clone(),
                        salt: Salt::from(*order_book_registry.contract_id),
                        ..Default::default()
                    },
                )
                .await?;

            order_book_registry
                .register_order_book(
                    to_registry_market_id(market_id),
                    order_book_deployment.contract_id,
                )
                .await?;

            if initialization_required {
                order_book_deployment.initialize().await?;
            }
            Ok(OrderBookManager::new(
                deployer_wallet,
                10u64.pow(order_book_config.base.decimals as u32),
                10u64.pow(order_book_config.quote.decimals as u32),
                &order_book_deployment,
            ))
        }
    }
}

async fn maybe_upgrade_order_book<W>(
    deployer_wallet: &W,
    should_upgrade_bytecode: bool,
    order_book: &OrderBookManager<W>,
    order_book_config: &OrderBookConfig,
    order_book_configurables: OrderBookConfigurables,
    market_symbol: &str,
) -> anyhow::Result<ContractId>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    let mut order_book_blob_id = order_book
        .proxy
        .methods()
        .proxy_target()
        .simulate(Execution::state_read_only())
        .await?
        .value
        .context("Order book proxy target should be set after initialization")?;

    if should_upgrade_bytecode {
        let order_book_deploy_config = OrderBookDeployConfig {
            order_book_configurables,
            ..Default::default()
        };
        let order_book_deploy = OrderBookDeploy::new(
            deployer_wallet.clone(),
            order_book.contract.contract_id(),
            order_book_config.base.asset,
            order_book_config.quote.asset,
        );
        let order_book_manager = OrderBookManager::new(
            deployer_wallet,
            10u64.pow(order_book_config.base.decimals as u32),
            10u64.pow(order_book_config.quote.decimals as u32),
            &order_book_deploy,
        );
        let order_book_blob = OrderBookDeploy::order_book_blob(
            deployer_wallet,
            order_book_config.base.asset,
            order_book_config.quote.asset,
            &order_book_deploy_config,
        )
        .await?;

        if order_book_blob_id != order_book_blob.id.into() {
            tracing::info!(
                "[{}] Upgrade OrderBook blob from {:?} to {:?}",
                market_symbol,
                order_book_blob_id,
                ContractId::from(order_book_blob.id)
            );
            order_book_manager
                .upgrade(&order_book_deploy_config)
                .await?;
            tracing::info!(
                "[{}] Emit new configuration event for {}",
                market_symbol,
                order_book.contract.contract_id()
            );
            order_book_manager.emit_config().await?;
            order_book_blob_id = order_book_blob.id.into();
        }
    }

    Ok(order_book_blob_id)
}

async fn set_order_book_maintainer<W>(
    order_book: &OrderBookManager<W>,
    ownership_options: &OwnershipTransferOptions,
    market_symbol: &str,
) -> anyhow::Result<()>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    // Revoke the maintainer role from the previous holders first, so the role is
    // rotated rather than accumulating holders across upgrades. Revoking an
    // account that does not hold the role is a no-op on-chain.
    for account in &ownership_options.revoke_orderbook_maintainers {
        tracing::info!(
            "[{}] Revoking ORDERBOOK_MAINTAINER_ROLE from {}",
            market_symbol,
            account
        );
        order_book
            .contract
            .methods()
            .owner_revoke_role(ORDERBOOK_MAINTAINER_ROLE, Identity::Address(*account))
            .call()
            .await?;
    }

    for account in &ownership_options.new_orderbook_maintainers {
        tracing::info!(
            "[{}] Granting ORDERBOOK_MAINTAINER_ROLE to {}",
            market_symbol,
            account
        );
        order_book
            .contract
            .methods()
            .owner_grant_role(ORDERBOOK_MAINTAINER_ROLE, Identity::Address(*account))
            .call()
            .await?;
    }

    Ok(())
}

async fn transfer_order_book_ownership<W>(
    order_book: &OrderBookManager<W>,
    ownership_options: &OwnershipTransferOptions,
    market_symbol: &str,
) -> anyhow::Result<()>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    if let Some(new_owner) = ownership_options.new_proxy_owner {
        let new_identity = Identity::Address(new_owner);
        tracing::info!(
            "[{}] Transferring OrderBook proxy ownership to {}",
            market_symbol,
            new_owner
        );
        order_book
            .proxy
            .methods()
            .set_owner(new_identity)
            .call()
            .await?;
    }

    if let Some(new_owner) = ownership_options.new_contract_owner {
        let new_identity = Identity::Address(new_owner);
        tracing::info!(
            "[{}] Transferring OrderBook contract ownership to {}",
            market_symbol,
            new_owner
        );
        order_book
            .contract
            .methods()
            .transfer_ownership(new_identity)
            .call()
            .await?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn load_config_empty_path_returns_default() {
        let result: MarketsConfigPartial = load_config_from_file("").unwrap();
        assert!(result.pairs.is_empty());
    }

    #[test]
    fn load_config_missing_file_errors() {
        let result: Result<MarketsConfigPartial, _> =
            load_config_from_file("nonexistent_file_12345.json");
        assert!(result.is_err());
    }

    #[test]
    fn checked_sub_catches_overflow() {
        // Validates that our checked_sub pattern works correctly
        let decimals: u32 = 6;
        let max_precision: u32 = 8; // greater than decimals

        let result = decimals.checked_sub(max_precision);
        assert!(
            result.is_none(),
            "should return None when max_precision > decimals"
        );

        // Normal case
        let result = 9u32.checked_sub(6);
        assert_eq!(result, Some(3));
    }

    #[test]
    fn markets_config_partial_default_has_empty_pairs() {
        let config = MarketsConfigPartial::default();
        assert!(config.pairs.is_empty());
    }
}

#[cfg(test)]
mod precision_budget_tests {
    use super::*;

    /// A pair shaped like every listed o2 market: `decimals: 9` on both sides,
    /// fractional prices off.
    fn pair(base_max: u8, quote_max: u8) -> OrderBookConfig {
        let asset = |symbol: &str, max_precision: u8| AssetConfig {
            symbol: symbol.to_string(),
            asset: Default::default(),
            decimals: 9,
            min_precision: 0,
            max_precision,
        };
        OrderBookConfig {
            contract_id: None,
            blob_id: None,
            market_id: Default::default(),
            taker_fee: 100,
            maker_fee: 0,
            min_order: 1_000_000_000,
            dust: 1_000,
            price_window: 0,
            allow_fractional_price: false,
            base: asset("TKN", base_max),
            quote: asset("USDC", quote_max),
        }
    }

    #[test]
    fn a_pair_that_spends_its_whole_budget_yields_the_contract_exponents() {
        // ENA/USDC: base 2 + quote 7 == 9, right on the limit.
        let (price, quantity) = order_book_precision_exponents(&pair(2, 7)).unwrap();
        assert_eq!(price, 2, "PRICE_PRECISION = 10^(9-7)");
        assert_eq!(quantity, 7, "QUANTITY_PRECISION = 10^(9-2)");
    }

    #[test]
    fn one_digit_over_budget_is_refused() {
        // The USDT/USDC trap: base 4 leaves room for 5 price digits, not 6.
        let err = order_book_precision_exponents(&pair(4, 6))
            .unwrap_err()
            .to_string();
        assert!(err.contains("FractionalPrice"), "{err}");
        assert!(err.contains("TKN/USDC"), "{err}");
        assert!(err.contains("= 10"), "{err}");
    }

    #[test]
    fn fractional_prices_downgrade_the_breach_to_a_warning() {
        // ALLOW_FRACTIONAL_PRICE truncates the notional rather than reverting,
        // so overspending is a smell there, not a hard failure.
        let mut config = pair(4, 6);
        config.allow_fractional_price = true;
        assert!(order_book_precision_exponents(&config).is_ok());
    }

    #[test]
    fn max_precision_beyond_the_asset_decimals_is_still_refused() {
        let err = order_book_precision_exponents(&pair(0, 10))
            .unwrap_err()
            .to_string();
        assert!(err.contains("exceeds decimals"), "{err}");
    }

    #[test]
    fn the_budget_tracks_the_quote_decimals_not_a_hardcoded_nine() {
        let mut config = pair(4, 2);
        config.quote.decimals = 6;
        assert!(
            order_book_precision_exponents(&config).is_ok(),
            "4 + 2 fits a 6-decimal quote"
        );

        config.quote.max_precision = 3;
        assert!(
            order_book_precision_exponents(&config).is_err(),
            "4 + 3 does not"
        );
    }
}

#[cfg(test)]
mod fee_amount_tests {
    use super::collateral_amount;

    fn at9(value: &str) -> anyhow::Result<u64> {
        collateral_amount(value, 9, "tier 1 open_fee")
    }

    #[test]
    fn whole_and_fractional_units_scale_by_the_asset_decimals() {
        assert_eq!(at9("7.5").unwrap(), 7_500_000_000);
        assert_eq!(at9("7").unwrap(), 7_000_000_000);
        assert_eq!(at9("0").unwrap(), 0);
        assert_eq!(at9("0.000000001").unwrap(), 1);
        assert_eq!(at9("13.5").unwrap(), 13_500_000_000);
        // The case a binary float gets wrong: `7.1 * 1e9` is 7099999999.99…
        assert_eq!(at9("7.1").unwrap(), 7_100_000_000);
    }

    #[test]
    fn a_figure_the_asset_cannot_represent_is_refused_not_rounded() {
        let err = at9("7.0000000001").unwrap_err().to_string();
        assert!(err.contains("10 decimal places"), "{err}");
        assert!(err.contains("tier 1 open_fee"), "{err}");
    }

    #[test]
    fn junk_is_refused() {
        for bad in ["", "   ", "-1", "1.2.3", "abc", "1e9", ".5", "1_000"] {
            assert!(at9(bad).is_err(), "`{bad}` should not parse");
        }
    }

    #[test]
    fn an_amount_past_u64_is_refused_rather_than_wrapping() {
        assert!(at9("18446744074").is_err());
        assert_eq!(at9("18446744073.709551615").unwrap(), u64::MAX);
    }

    #[test]
    fn other_decimal_scales_are_honoured() {
        assert_eq!(collateral_amount("7.5", 6, "f").unwrap(), 7_500_000);
        assert_eq!(collateral_amount("7.5", 1, "f").unwrap(), 75);
        assert!(collateral_amount("7.5", 0, "f").is_err());
        assert_eq!(collateral_amount("7", 0, "f").unwrap(), 7);
    }
}