o2-deploy 0.3.12-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
//! 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::{
        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;

/// 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)?;
        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,
    pub prolong_fee_bps: [u64; 4],
    pub max_credit_line_bps: u64,
    pub max_price_age: u64,
    pub open_fee_bps: u64,
    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 initial price to publish on the feed before tiers are published
/// (`publish_tier_version` prices every non-collateral tier asset).
/// `bid`/`ask` are u128 decimal strings scaled 1e18 per whole unit.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MarginInitialPrice {
    pub asset: fuels::types::AssetId,
    pub bid: String,
    pub ask: String,
    pub asset_decimals: u8,
}

/// 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 {
    /// DRY-RUN: report what exists on the live chain versus what a real
    /// run would deploy/upgrade — per contract and per tier — and send NO
    /// transaction.
    #[serde(default)]
    pub dry_run: bool,
    /// Reuse an existing price feed instead of deploying the mock feed
    /// (production passes its proxied feed; the mock fits test/dev only).
    pub price_feed_id: Option<ContractId>,
    /// TIER-ONLY mode: run no system deploy, only reconcile the tier
    /// catalogue (and prices/publishers 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>,
    /// Price feed publishers to add (`address:0x..` — the feed grants the
    /// submitter role to addresses). When empty, nothing is granted; the
    /// deployer must already be a publisher for `initial_prices` to land.
    #[serde(default)]
    pub publishers: 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>,
    /// Prices published (by the deployer) before tiers, so tier assets
    /// are priced on the feed. Already-priced assets are skipped.
    #[serde(default)]
    pub initial_prices: Vec<MarginInitialPrice>,
    /// 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>,
    /// 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,
                trade_account_registry_id,
                trade_account_oracle_id,
                trial_trade_account_oracle_id,
                &pairs,
                params.margin_cosigner,
                params.margin_liquidator,
            )
            .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), false) = (margin_ids, margin.dry_run) {
                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
/// `margin.dry_run` everything is reported and nothing is sent; with
/// `margin.margin_pool_id` the system deploy is skipped and only the
/// feed/price/tier reconciliation runs against the given pool.
#[allow(clippy::too_many_arguments)]
async fn deploy_margin<W>(
    wallet: &W,
    margin: &MarginConfig,
    salt: fuels::types::Salt,
    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>,
) -> anyhow::Result<MarginIds>
where
    W: Account + ViewOnlyAccount + Clone + 'static,
{
    use o2_tools::prop::{
        PropAccountOracleContract,
        PropMarginPoolContract,
        PropPriceFeedMockContract,
    };

    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.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.existing_registry = Some(ExistingRegistry {
        registry_id: trade_account_registry_id,
        trade_account_oracle_id,
        trial_trade_account_oracle_id,
    });

    // Resolve the system: tier-only mode / dry run / real deploy-or-resume.
    let (price_feed_id, margin_pool_id, margin_oracle_id, mutate) = if let Some(
        margin_pool_id,
    ) =
        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
            }
        };
        (price_feed_id, margin_pool_id, None, !margin.dry_run)
    } else if margin.dry_run {
        let report = PropDeployment::verify(wallet, &prop_config).await?;
        tracing::info!(
            "Margin DRY-RUN: system {} (oracle {}, pool {}, feed {}, registry {})",
            if report.up_to_date {
                "up to date — a real run would send no system transaction"
            } else {
                "NOT up to date — see the [prop verify] lines above"
            },
            report.oracle_id,
            report.pool_id,
            report.price_feed_id,
            report.registry_id,
        );
        (
            report.price_feed_id,
            report.pool_id,
            Some(report.oracle_id),
            false,
        )
    } 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),
            true,
        )
    };

    // -- 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 {
                if mutate {
                    tracing::info!(
                        "Margin: platform payout {current:?} -> {platform_payout:?}"
                    );
                    pool.methods()
                        .set_platform_payout(platform_payout)
                        .call()
                        .await?;
                } else {
                    tracing::info!(
                        "Margin DRY-RUN: would set platform payout \
                         {current:?} -> {platform_payout:?}"
                    );
                }
            }
        }
        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 {
                if mutate {
                    tracing::info!("Margin: liquidator {current:?} -> {liquidator:?}");
                    pool.methods().set_liquidator(liquidator).call().await?;
                } else {
                    tracing::info!(
                        "Margin DRY-RUN: would set liquidator \
                         {current:?} -> {liquidator:?}"
                    );
                }
            }
        }
    }

    // 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) {
            if mutate {
                tracing::info!("Margin: cosigner {current:?} -> {cosigner:?}");
                oracle.methods().set_cosigner(cosigner).call().await?;
            } else {
                tracing::info!(
                    "Margin DRY-RUN: would set cosigner \
                     {current:?} -> {cosigner:?}"
                );
            }
        }
    }

    // -- publishers + initial prices ------------------------------------
    let price_feed = PropPriceFeedMockContract::new(price_feed_id, wallet.clone());
    if mutate {
        for publisher in &margin.publishers {
            let publisher = parse_margin_identity(publisher)?;
            tracing::info!("Margin: adding price feed publisher {publisher:?}");
            price_feed.methods().add_publisher(publisher).call().await?;
        }
    } else if !margin.publishers.is_empty() {
        tracing::info!(
            "Margin DRY-RUN: would add {} price feed publisher(s)",
            margin.publishers.len()
        );
    }
    for initial_price in &margin.initial_prices {
        let has_price = price_feed
            .methods()
            .has_price(initial_price.asset)
            .simulate(Execution::state_read_only())
            .await?
            .value;
        if has_price {
            continue;
        }
        if !mutate {
            tracing::info!(
                "Margin DRY-RUN: would publish an initial price for {}",
                initial_price.asset
            );
            continue;
        }
        let decimals = price_feed
            .methods()
            .get_asset_decimals(initial_price.asset)
            .simulate(Execution::state_read_only())
            .await?
            .value;
        if decimals.is_none() {
            price_feed
                .methods()
                .set_asset_decimals(initial_price.asset, initial_price.asset_decimals)
                .call()
                .await?;
        }
        let bid: u128 = initial_price
            .bid
            .parse()
            .map_err(|e| anyhow::anyhow!("invalid initial price bid: {e}"))?;
        let ask: u128 = initial_price
            .ask
            .parse()
            .map_err(|e| anyhow::anyhow!("invalid initial price ask: {e}"))?;
        tracing::info!(
            "Margin: publishing initial price for {}",
            initial_price.asset
        );
        price_feed
            .methods()
            .publish_prices(vec![o2_tools::prop::PriceInput {
                asset: initial_price.asset,
                bid,
                ask,
                timestamp: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)?
                    .as_secs(),
            }])
            .call()
            .await?;
    }

    // -- the tier catalogue ---------------------------------------------
    let pool = PropMarginPoolContract::new(margin_pool_id, wallet.clone());
    let pool_reachable = wallet
        .try_provider()?
        .contract_exists(&margin_pool_id)
        .await?;
    if pool_reachable {
        reconcile_margin_tiers(&pool, price_feed_id, pairs, &margin.tiers, !mutate)
            .await?;
    } else if !margin.tiers.is_empty() {
        tracing::info!(
            "Margin DRY-RUN: pool not deployed yet — all {} tier(s) would publish \
             their first version",
            margin.tiers.len()
        );
    }

    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],
    dry_run: bool,
) -> 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);
        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 {
            if dry_run {
                tracing::info!(
                    "Margin DRY-RUN: tier {} — would publish its FIRST version \
                     ({} book(s))",
                    tier.tier_id,
                    books.len()
                );
                continue;
            }
            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 {
            if dry_run {
                tracing::info!(
                    "Margin DRY-RUN: tier {} — params differ from live version \
                     {version}; would publish a NEW version",
                    tier.tier_id
                );
                continue;
            }
            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;
        }
        if dry_run {
            tracing::info!(
                "Margin DRY-RUN: tier {} — would add {} book(s) to version {version}",
                tier.tier_id,
                missing.len()
            );
            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(())
}

fn tier_params(tier: &MarginTierConfig) -> o2_tools::prop::TierParams {
    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_bps: tier.prolong_fee_bps,
        max_credit_line_bps: tier.max_credit_line_bps,
        max_price_age: tier.max_price_age,
        open_fee_bps: tier.open_fee_bps,
        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 {
        let trade_account_registry_deploy_config =
            TradeAccountRegistryDeployConfig::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)
            );
            trade_account_registry
                .upgrade(
                    trade_account_oracle_id,
                    trial_trade_account_oracle_id,
                    &TradeAccountRegistryDeployConfig::default(),
                )
                .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,
{
    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())
}

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 = 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
            )
        })?;

    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());
    }
}