o2-tools 0.3.21-rc

Reusable tooling for trade account and order book contract interactions on Fuel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
//! Deployment helpers for the independent prop-account contract family.
//!
//! Prop accounts consult a stable account-oracle proxy at runtime. The oracle,
//! registry and margin pool each retain independent SRC-14 upgrade authority.

/// Test-only: the entry term every fixture session opens on.
#[cfg(test)]
use crate::prop::ProlongPeriod;
use crate::{
    blob_loader,
    prop::{
        PRICE_FEED_BYTECODE,
        PRICE_FEED_PROXY_BYTECODE,
        PRICE_FEED_PROXY_STORAGE,
        PRICE_FEED_STORAGE,
        PROP_ACCOUNT_BYTECODE,
        PROP_ACCOUNT_ORACLE_BYTECODE,
        PROP_ACCOUNT_ORACLE_PROXY_BYTECODE,
        PROP_ACCOUNT_ORACLE_PROXY_STORAGE,
        PROP_ACCOUNT_ORACLE_STORAGE,
        PROP_ACCOUNT_PROXY_BYTECODE,
        PROP_ACCOUNT_PROXY_STORAGE,
        PROP_ACCOUNT_STORAGE,
        PROP_MARGIN_POOL_BYTECODE,
        PROP_MARGIN_POOL_PROXY_BYTECODE,
        PROP_MARGIN_POOL_PROXY_STORAGE,
        PROP_MARGIN_POOL_STORAGE,
        PriceFeedContract,
        PriceFeedContractConfigurables,
        PriceFeedProxyContract,
        PriceFeedProxyContractConfigurables,
        PropAccountContract,
        PropAccountOracleContract,
        PropAccountOracleContractConfigurables,
        PropAccountOracleProxyContract,
        PropAccountOracleProxyContractConfigurables,
        PropAccountProxyContract,
        PropAccountProxyContractConfigurables,
        PropMarginPoolContract,
        PropMarginPoolContractConfigurables,
        PropMarginPoolProxyContract,
        PropMarginPoolProxyContractConfigurables,
        State,
    },
    trade_account_registry::{
        State as TradeAccountRegistryState,
        TRADE_ACCOUNT_REGISTER_BYTECODE,
        TRADE_ACCOUNT_REGISTER_PROXY_BYTECODE,
        TRADE_ACCOUNT_REGISTER_PROXY_STORAGE,
        TRADE_ACCOUNT_REGISTER_STORAGE,
        TradeAccountRegistry,
        TradeAccountRegistryConfigurables,
        TradeAccountRegistryDeployConfig,
        TradeAccountRegistryManager,
        TradeAccountRegistryProxy,
        TradeAccountRegistryProxyConfigurables,
    },
};
use anyhow::{
    Context,
    Result,
    ensure,
};
use fuels::{
    core::{
        Configurable,
        Configurables,
    },
    prelude::*,
    programs::contract::Regular,
    tx::StorageSlot,
    types::{
        Address,
        AssetId,
        ContractId,
        Identity,
        transaction_builders::Blob,
    },
};

/// An already-deployed shared trade-account registry to reuse for
/// prop-account registration instead of deploying a dedicated one. The
/// registry's implementation is UPGRADED in place (new blob, same proxy) to
/// carry the prop configurables, so the oracle ids it was deployed with must
/// be repeated — the fresh implementation blob embeds them again.
#[derive(Clone, Debug)]
pub struct ExistingRegistry {
    /// The registry proxy id every account resolution goes through.
    pub registry_id: ContractId,
    /// The trade-account oracle the registry validates against.
    pub trade_account_oracle_id: ContractId,
    /// The trial-trade-account oracle the registry validates against.
    pub trial_trade_account_oracle_id: ContractId,
}

/// Deployment-time settings for the prop-account system.
#[derive(Clone, Debug)]
pub struct PropDeployConfig {
    /// Asset used for collateral and quote accounting by the pool.
    pub collateral_asset: AssetId,
    /// Decimal precision of `collateral_asset`.
    pub collateral_decimals: u8,
    /// Maximum number of order books in one tier version.
    pub max_tier_books: u64,
    /// Fee charged by `repay_base_from_collateral`, in parts per million of the
    /// quote value of the debt closed. Same scale as the order book's taker fee,
    /// so `100` is one basis point.
    pub base_repay_fee_ppm: u64,
    /// Owner of the oracle implementation, feed, registry implementation and pool.
    /// Defaults to the deployer.
    pub owner: Option<Identity>,
    /// Owner of the oracle, registry and pool SRC-14 proxies. Defaults to the deployer.
    pub proxy_owner: Option<Identity>,
    /// Cosigner exposed by every prop account. Defaults to the deployer.
    pub cosigner: Option<Address>,
    /// Recipient of the platform share. Defaults to the deployer.
    pub platform_payout: Option<Identity>,
    /// Recipient of assets retained during forced settlement. Defaults to the deployer.
    pub liquidator: Option<Identity>,
    /// Deterministic salt used for all contracts in this deployment.
    pub salt: Salt,
    /// Maximum implementation words placed into each loader data blob.
    pub max_words_per_blob: usize,
    /// Reuse (and upgrade) an existing shared trade-account registry
    /// instead of deploying a dedicated one.
    pub existing_registry: Option<ExistingRegistry>,
    /// Reuse an already-deployed price feed instead of deploying one. When
    /// `None` the PRODUCTION price feed is deployed behind its own SRC-14
    /// proxy.
    pub existing_price_feed: Option<ContractId>,
    /// Submission-age bound written to the feed, in seconds. `None` leaves
    /// the contract's own default in place; a value is reconciled
    /// compare-first, so a feed already on it costs no transaction.
    pub max_offchain_age_seconds: Option<u64>,
    /// Reuse an already-deployed margin pool instead of deriving its
    /// address. The derivation depends on the pool BYTECODE (through the
    /// bootstrap blob the proxy is seeded with), so a release that changes
    /// the pool derives a new address and forks the pool. Anyone who
    /// already knows their pool must pin it here to get an upgrade rather
    /// than a fork.
    pub existing_pool: Option<ContractId>,
}

impl PropDeployConfig {
    pub fn new(collateral_asset: AssetId) -> Self {
        Self {
            collateral_asset,
            collateral_decimals: 6,
            max_tier_books: 80,
            base_repay_fee_ppm: 100,
            owner: None,
            proxy_owner: None,
            cosigner: None,
            platform_payout: None,
            liquidator: None,
            salt: Salt::default(),
            max_words_per_blob: 10_000,
            existing_registry: None,
            existing_price_feed: None,
            max_offchain_age_seconds: None,
            existing_pool: None,
        }
    }
}

/// Handles and implementation blob IDs produced by a complete deployment.
#[derive(Clone)]
pub struct PropDeployment<W> {
    /// Oracle implementation ABI bound to its stable SRC-14 proxy.
    pub oracle: PropAccountOracleContract<W>,
    pub oracle_proxy: PropAccountOracleProxyContract<W>,
    pub oracle_id: ContractId,
    pub oracle_blob_id: BlobId,
    /// The price feed the pool values against, bound through its proxy.
    pub price_feed: PriceFeedContract<W>,
    pub price_feed_id: ContractId,
    /// Shared trade-account registry implementation ABI bound to its SRC-14 proxy.
    pub registry: TradeAccountRegistry<W>,
    pub registry_proxy: TradeAccountRegistryProxy<W>,
    pub registry_id: ContractId,
    pub registry_blob_id: BlobId,
    /// Margin-pool implementation ABI bound to its SRC-14 proxy.
    pub pool: PropMarginPoolContract<W>,
    pub pool_proxy: PropMarginPoolProxyContract<W>,
    pub pool_id: ContractId,
    pub pool_blob_id: BlobId,
    /// Runtime account implementation selected through the oracle proxy.
    pub account_blob_id: BlobId,
    /// Raw configurable account-proxy bytecode consumed by the registry.
    pub account_proxy_blob_id: BlobId,
    /// Fixed salt used with parent/index configurables for deterministic children.
    pub account_salt: Salt,
    pub deployer_wallet: W,
}

impl<W> PropDeployment<W>
where
    W: Account + Clone,
{
    /// Deploy the full system in dependency order.
    ///
    /// The registry is deployed before the pool so its ID can be embedded in
    /// the pool implementation configurables. The pool ID is then stored in
    /// the account oracle through its stable proxy.
    pub async fn deploy(deployer_wallet: &W, config: &PropDeployConfig) -> Result<Self> {
        ensure!(
            config.collateral_asset != AssetId::zeroed(),
            "prop collateral asset cannot be zero"
        );
        ensure!(
            config.collateral_decimals <= 18,
            "prop collateral decimals cannot exceed 18"
        );
        ensure!(
            config.max_tier_books != 0,
            "prop max tier books cannot be zero"
        );
        ensure!(
            config.max_words_per_blob != 0,
            "prop loader blob size cannot be zero"
        );

        let deployer = Identity::Address(deployer_wallet.address());
        let owner = config.owner.unwrap_or(deployer);
        let proxy_owner = config.proxy_owner.unwrap_or(deployer);
        // `initialize` refuses a zero cosigner or liquidator, so the blob this
        // run uploads has to name SOMETHING - the deployer is the only sensible
        // bootstrap. In production both arrive as explicit deploy parameters.
        //
        // The seed is only ever CONSUMED by `initialize`, which is guarded by
        // the initialization flag, so on an already-deployed pool or oracle it
        // is inert: storage keeps the live value and the reconciliation in
        // `o2-deploy` is what changes it, on request. That is why the warnings
        // are not raised here - the fallback is not news, USING it is. Warning
        // at the fallback made an ordinary upgrade announce that the deploy key
        // had become the residue payee, which was never true and is exactly the
        // sort of false alarm that gets real ones ignored.
        let cosigner_defaulted = config.cosigner.is_none();
        let cosigner = config.cosigner.unwrap_or_else(|| deployer_wallet.address());
        let platform_payout = config.platform_payout.unwrap_or(deployer);
        let liquidator_defaulted = config.liquidator.is_none();
        let liquidator = config.liquidator.unwrap_or(deployer);

        let account_blob_id = upload_implementation(
            deployer_wallet,
            PROP_ACCOUNT_BYTECODE,
            PROP_ACCOUNT_STORAGE,
            Configurables::default(),
            config,
        )
        .await
        .context("deploy prop-account implementation blob")?;

        // This must remain raw bytecode: the registry BLDd-loads it and patches
        // the account-specific configurables before checking the child root.
        let account_proxy_blob_id = blob_loader::upload_loader_blobs(
            deployer_wallet,
            vec![],
            Blob::new(PROP_ACCOUNT_PROXY_BYTECODE.to_vec()),
        )
        .await
        .context("deploy raw prop-account proxy blob")?;

        // The final oracle implementation embeds the pool ID, while the pool
        // transitively embeds the stable oracle proxy ID. Point the proxy at a
        // default-config bootstrap blob first to break that deployment cycle.
        let oracle_bootstrap_blob_id = upload_implementation(
            deployer_wallet,
            PROP_ACCOUNT_ORACLE_BYTECODE,
            PROP_ACCOUNT_ORACLE_STORAGE,
            Configurables::default(),
            config,
        )
        .await
        .context("deploy prop-account oracle implementation blob")?;
        let oracle_proxy_configurables =
            PropAccountOracleProxyContractConfigurables::default()
                .with_INITIAL_OWNER(State::Initialized(proxy_owner))?
                .with_INITIAL_TARGET(ContractId::from(oracle_bootstrap_blob_id))?;
        let oracle_proxy_contract = regular_contract_with_implementation_storage(
            PROP_ACCOUNT_ORACLE_PROXY_BYTECODE,
            PROP_ACCOUNT_ORACLE_PROXY_STORAGE,
            PROP_ACCOUNT_ORACLE_STORAGE,
            config.salt,
        )?
        .with_configurables(oracle_proxy_configurables);
        let (oracle_id, _) = deploy_regular(deployer_wallet, oracle_proxy_contract)
            .await
            .context("deploy prop-account oracle proxy")?;
        let oracle_proxy =
            PropAccountOracleProxyContract::new(oracle_id, deployer_wallet.clone());
        let oracle = PropAccountOracleContract::new(oracle_id, deployer_wallet.clone());
        // State-checked rather than is-new-gated: a run that crashed between
        // the Create and this call resumes here instead of stranding an
        // uninitialized proxy forever.
        let oracle_proxy_target = oracle_proxy
            .methods()
            .proxy_target()
            .simulate(Execution::state_read_only())
            .await
            .context("read prop-account oracle proxy target")?
            .value;
        if oracle_proxy_target.is_none() {
            oracle_proxy
                .methods()
                .initialize_proxy()
                .call()
                .await
                .context("initialize prop-account oracle proxy")?;
        }

        // The PRODUCTION price feed, behind its own SRC-14 proxy — not the
        // test mock, which has neither role administration nor a pause
        // switch and has no business backing a real pool.
        let (price_feed, price_feed_id) = match config.existing_price_feed {
            Some(price_feed_id) => (
                PriceFeedContract::new(price_feed_id, deployer_wallet.clone()),
                price_feed_id,
            ),
            None => {
                // Same bootstrap trick the pool and the oracle use: the
                // proxy's ADDRESS must not depend on the implementation's
                // configurables, or naming a different owner would derive a
                // different proxy and fork the feed instead of upgrading it.
                let feed_bootstrap_blob_id = upload_implementation(
                    deployer_wallet,
                    PRICE_FEED_BYTECODE,
                    PRICE_FEED_STORAGE,
                    Configurables::default(),
                    config,
                )
                .await
                .context("deploy price-feed bootstrap implementation blob")?;
                let feed_proxy_configurables =
                    PriceFeedProxyContractConfigurables::default()
                        .with_INITIAL_OWNER(State::Initialized(proxy_owner))?
                        .with_INITIAL_TARGET(ContractId::from(feed_bootstrap_blob_id))?;
                let feed_proxy_contract = regular_contract_with_implementation_storage(
                    PRICE_FEED_PROXY_BYTECODE,
                    PRICE_FEED_PROXY_STORAGE,
                    PRICE_FEED_STORAGE,
                    config.salt,
                )?
                .with_configurables(feed_proxy_configurables);
                let (price_feed_id, _) =
                    deploy_regular(deployer_wallet, feed_proxy_contract)
                        .await
                        .context("deploy price-feed proxy")?;
                let feed_proxy =
                    PriceFeedProxyContract::new(price_feed_id, deployer_wallet.clone());
                let feed_proxy_target = feed_proxy
                    .methods()
                    .proxy_target()
                    .simulate(Execution::state_read_only())
                    .await
                    .context("read price-feed proxy target")?
                    .value;
                if feed_proxy_target.is_none() {
                    feed_proxy
                        .methods()
                        .initialize_proxy()
                        .call()
                        .await
                        .context("initialize price-feed proxy")?;
                }
                upgrade_price_feed_implementation(
                    deployer_wallet,
                    price_feed_id,
                    owner,
                    config,
                )
                .await?;
                let price_feed =
                    PriceFeedContract::new(price_feed_id, deployer_wallet.clone());
                let feed_is_uninitialized = price_feed
                    .methods()
                    .owner()
                    .simulate(Execution::state_read_only())
                    .await
                    .context("read price-feed initialization state")?
                    .value
                    == State::Uninitialized;
                if feed_is_uninitialized {
                    price_feed
                        .methods()
                        .initialize()
                        .call()
                        .await
                        .context("initialize price-feed")?;
                }
                // `initialize` grants the owner the ADMIN role only —
                // publishing needs the submitter role named explicitly, and
                // the deploy seeds its prices as the owner. No widening: the
                // owner may grant it to itself at will, so withholding it
                // would only mean the first publish reverts.
                let owner_can_publish = price_feed
                    .methods()
                    .has_role(PRICE_SUBMITTER_ROLE, owner)
                    .simulate(Execution::state_read_only())
                    .await
                    .context("read the price feed's submitter role")?
                    .value;
                if !owner_can_publish {
                    price_feed
                        .methods()
                        .add_publisher(owner)
                        .call()
                        .await
                        .context("grant the price feed's owner the submitter role")?;
                }
                (price_feed, price_feed_id)
            }
        };

        // The submission-age bound, reconciled compare-first against
        // whatever the feed currently enforces. Opt-in: with nothing
        // configured the contract's own default stands, so a feed this
        // deploy does not own is never written to.
        if let Some(seconds) = config.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 {
                price_feed
                    .methods()
                    .set_max_offchain_age(seconds)
                    .call()
                    .await
                    .context("set the price feed's submission-age bound")?;
            }
        }

        let [oracle_offset, parent_offset, index_offset] = prop_account_proxy_offsets()?;
        let prop_registry_configurables = |base: TradeAccountRegistryConfigurables| {
            Ok::<_, anyhow::Error>(
                base.with_PROP_ACCOUNT_ORACLE_CONTRACT_ID(oracle_id)?
                    .with_DEFAULT_PROP_ACCOUNT_PROXY(ContractId::from(
                        account_proxy_blob_id,
                    ))?
                    .with_PROP_ORACLE_CONFIG_OFFSET(oracle_offset)?
                    .with_PROP_PARENT_CONFIG_OFFSET(parent_offset)?
                    .with_PROP_INDEX_CONFIG_OFFSET(index_offset)?,
            )
        };
        let (registry_id, registry_blob_id) = match &config.existing_registry {
            Some(existing) => {
                // Upgrade the shared registry's implementation in place:
                // same proxy, a fresh blob repeating the oracle ids it was
                // deployed with plus the prop configurables above. Storage
                // (registered accounts, ownership) rides through untouched.
                let manager = TradeAccountRegistryManager::new(
                    deployer_wallet.clone(),
                    existing.registry_id,
                );
                let deploy_config = TradeAccountRegistryDeployConfig {
                    registry_config: prop_registry_configurables(
                        TradeAccountRegistryConfigurables::default(),
                    )?,
                    ..Default::default()
                };
                // Blob uploads are exists-checked; the retarget only fires
                // when the proxy does not already point at the upgraded
                // implementation, so a re-run is a no-op.
                let registry_blob_id = TradeAccountRegistryManager::deploy_register_blob(
                    deployer_wallet,
                    existing.trade_account_oracle_id,
                    existing.trial_trade_account_oracle_id,
                    &deploy_config,
                )
                .await
                .context("build upgraded shared trade-account registry blob")?;
                let current_target = manager
                    .registry_proxy
                    .methods()
                    .proxy_target()
                    .simulate(Execution::state_read_only())
                    .await
                    .context("read shared trade-account registry proxy target")?
                    .value;
                if current_target != Some(ContractId::from(registry_blob_id)) {
                    manager
                        .registry_proxy
                        .methods()
                        .set_proxy_target(ContractId::from(registry_blob_id))
                        .call()
                        .await
                        .context("upgrade shared trade-account registry for prop")?;
                }
                (existing.registry_id, registry_blob_id)
            }
            None => {
                let registry_configurables = prop_registry_configurables(
                    TradeAccountRegistryConfigurables::default()
                        .with_INITIAL_OWNER(TradeAccountRegistryState::Initialized(
                            owner,
                        ))?
                        .with_INITIAL_TRIAL_TRADE_ACCOUNT_CREATOR(owner)?,
                )?;
                let registry_blob_id = upload_implementation(
                    deployer_wallet,
                    TRADE_ACCOUNT_REGISTER_BYTECODE,
                    TRADE_ACCOUNT_REGISTER_STORAGE,
                    registry_configurables,
                    config,
                )
                .await
                .context("deploy shared trade-account registry implementation blob")?;

                let registry_proxy_configurables =
                    TradeAccountRegistryProxyConfigurables::default()
                        .with_INITIAL_OWNER(TradeAccountRegistryState::Initialized(
                            proxy_owner,
                        ))?
                        .with_INITIAL_TARGET(ContractId::from(registry_blob_id))?;
                let registry_proxy_contract = regular_contract(
                    TRADE_ACCOUNT_REGISTER_PROXY_BYTECODE,
                    TRADE_ACCOUNT_REGISTER_PROXY_STORAGE,
                    config.salt,
                )?
                .with_configurables(registry_proxy_configurables);
                let (registry_id, registry_proxy_is_new) =
                    deploy_regular(deployer_wallet, registry_proxy_contract)
                        .await
                        .context("deploy shared trade-account registry proxy")?;
                let registry_proxy =
                    TradeAccountRegistryProxy::new(registry_id, deployer_wallet.clone());
                let registry =
                    TradeAccountRegistry::new(registry_id, deployer_wallet.clone());
                if registry_proxy_is_new {
                    registry_proxy
                        .methods()
                        .initialize_proxy()
                        .call()
                        .await
                        .context("initialize shared trade-account registry proxy")?;
                    registry
                        .methods()
                        .initialize()
                        .call()
                        .await
                        .context("initialize shared trade-account registry")?;
                }
                (registry_id, registry_blob_id)
            }
        };
        let registry_proxy =
            TradeAccountRegistryProxy::new(registry_id, deployer_wallet.clone());
        let registry = TradeAccountRegistry::new(registry_id, deployer_wallet.clone());

        let pool_configurables = PropMarginPoolContractConfigurables::default()
            .with_INITIAL_ADMIN(owner)?
            .with_INITIAL_REGISTRY(registry_id)?
            .with_INITIAL_PRICE_FEED(price_feed_id)?
            .with_INITIAL_PLATFORM_PAYOUT(platform_payout)?
            .with_INITIAL_LIQUIDATOR(liquidator)?
            .with_COLLATERAL_ASSET(config.collateral_asset)?
            .with_COLLATERAL_DECIMALS(config.collateral_decimals)?
            .with_MAX_TIER_BOOKS(config.max_tier_books)?
            .with_BASE_REPAY_FEE_PPM(config.base_repay_fee_ppm)?;
        let pool_blob_id = upload_implementation(
            deployer_wallet,
            PROP_MARGIN_POOL_BYTECODE,
            PROP_MARGIN_POOL_STORAGE,
            pool_configurables,
            config,
        )
        .await
        .context("deploy prop margin-pool implementation blob")?;

        // The proxy's ADDRESS must not depend on the implementation's
        // configurables, or changing a runtime value - the liquidator, the
        // payout party, the feed - would derive a DIFFERENT proxy and fork the
        // pool instead of upgrading it. Point it at a default-config bootstrap
        // blob (the same trick the oracle below uses to break its own cycle),
        // then retarget to the configured implementation.
        // ...but that only covers CONFIGURABLE changes. The bootstrap blob
        // id is a hash of the pool BYTECODE, so any release that touches
        // the pool derives a different `INITIAL_TARGET`, a different proxy
        // address, and forks the pool instead of upgrading it — silently,
        // leaving the funded one orphaned. A caller that already knows its
        // pool pins the id, and derivation is only for the first deploy.
        let pool_id = match config.existing_pool {
            Some(pool_id) => pool_id,
            None => {
                let pool_bootstrap_blob_id = upload_implementation(
                    deployer_wallet,
                    PROP_MARGIN_POOL_BYTECODE,
                    PROP_MARGIN_POOL_STORAGE,
                    Configurables::default(),
                    config,
                )
                .await
                .context("deploy prop margin-pool bootstrap implementation blob")?;
                let pool_proxy_configurables =
                    PropMarginPoolProxyContractConfigurables::default()
                        .with_INITIAL_OWNER(State::Initialized(proxy_owner))?
                        .with_INITIAL_TARGET(ContractId::from(pool_bootstrap_blob_id))?;
                let pool_proxy_contract = regular_contract_with_implementation_storage(
                    PROP_MARGIN_POOL_PROXY_BYTECODE,
                    PROP_MARGIN_POOL_PROXY_STORAGE,
                    PROP_MARGIN_POOL_STORAGE,
                    config.salt,
                )?
                .with_configurables(pool_proxy_configurables);
                let (pool_id, _) = deploy_regular(deployer_wallet, pool_proxy_contract)
                    .await
                    .context("deploy prop margin-pool proxy")?;
                pool_id
            }
        };
        let pool_proxy =
            PropMarginPoolProxyContract::new(pool_id, deployer_wallet.clone());
        let pool = PropMarginPoolContract::new(pool_id, deployer_wallet.clone());
        let pool_proxy_target = pool_proxy
            .methods()
            .proxy_target()
            .simulate(Execution::state_read_only())
            .await
            .context("read prop margin-pool proxy target")?
            .value;
        if pool_proxy_target.is_none() {
            pool_proxy
                .methods()
                .initialize_proxy()
                .call()
                .await
                .context("initialize prop margin-pool proxy")?;
        }
        // The upgrade itself: new configurables mean a new blob, and the
        // stable proxy is pointed at it. A run that changes nothing computes
        // the same blob id and retargets nothing.
        let pool_target = pool_proxy
            .methods()
            .proxy_target()
            .simulate(Execution::state_read_only())
            .await
            .context("read configured prop margin-pool proxy target")?
            .value;
        if pool_target != Some(ContractId::from(pool_blob_id)) {
            pool_proxy
                .methods()
                .set_proxy_target(ContractId::from(pool_blob_id))
                .call()
                .await
                .context("activate configured prop margin-pool implementation")?;
        }

        let oracle_configurables = PropAccountOracleContractConfigurables::default()
            .with_INITIAL_OWNER(owner)?
            .with_INITIAL_PROP_ACCOUNT_IMPL(ContractId::from(account_blob_id))?
            .with_INITIAL_COSIGNER(cosigner)?
            .with_INITIAL_PROP_MARGIN_POOL(pool_id)?;
        let oracle_blob_id = upload_implementation(
            deployer_wallet,
            PROP_ACCOUNT_ORACLE_BYTECODE,
            PROP_ACCOUNT_ORACLE_STORAGE,
            oracle_configurables,
            config,
        )
        .await
        .context("deploy configured prop-account oracle implementation blob")?;
        let oracle_target = oracle_proxy
            .methods()
            .proxy_target()
            .simulate(Execution::state_read_only())
            .await
            .context("read prop-account oracle proxy target")?
            .value;
        if oracle_target != Some(ContractId::from(oracle_blob_id)) {
            oracle_proxy
                .methods()
                .set_proxy_target(ContractId::from(oracle_blob_id))
                .call()
                .await
                .context("activate configured prop-account oracle implementation")?;
        }

        let oracle_is_uninitialized = oracle
            .methods()
            .owner()
            .simulate(Execution::state_read_only())
            .await
            .context("read prop-account oracle initialization state")?
            .value
            == State::Uninitialized;
        if oracle_is_uninitialized {
            // NOW the seed becomes the live cosigner, so now it is worth
            // saying. An oracle that was already initialized keeps whatever
            // its storage holds and never reaches this branch.
            if cosigner_defaulted {
                tracing::warn!(
                    "prop deploy: no cosigner given and this oracle is being \
                     initialized - the deployer becomes the cosigner. The \
                     backend must run MARGIN_COSIGNER_KEY for this address or \
                     margin stays inert."
                );
            }
            oracle
                .methods()
                .initialize()
                .call()
                .await
                .context("initialize prop-account oracle")?;
        }

        // The account implementation EVERY margin account resolves through,
        // reconciled explicitly — the same defect the cosigner already had,
        // and the price feed had on the pool.
        //
        // `INITIAL_PROP_ACCOUNT_IMPL` reaches storage only through the
        // one-time `initialize` above. On an already-initialized oracle that
        // branch is skipped, so baking a fresh `account_blob_id` into the
        // oracle's configurables and retargeting its proxy — both of which
        // this run does, and both of which succeed — still leaves
        // `get_prop_account_impl` answering with the PREVIOUS blob. Every
        // account keeps running the old bytecode while the deploy reports a
        // clean upgrade, which is the worst shape a bug can take.
        //
        // Compare-first, like every other reconcile here: an oracle already
        // on this implementation costs one read and no transaction.
        let stored_impl = oracle
            .methods()
            .get_prop_account_impl()
            .simulate(Execution::state_read_only())
            .await
            .context("read the prop-account oracle's account implementation")?
            .value;
        let account_impl = ContractId::from(account_blob_id);
        if stored_impl != Some(account_impl) {
            tracing::info!(
                "Prop: account implementation {stored_impl:?} -> {account_impl:?}"
            );
            oracle
                .methods()
                .set_prop_account_impl(account_impl)
                .call()
                .await
                .context("activate the prop-account implementation on the oracle")?;
        }

        // The account implementation EVERY margin account resolves through,
        // reconciled explicitly — the same defect the cosigner already had,
        // and the price feed had on the pool.
        //
        // `INITIAL_PROP_ACCOUNT_IMPL` reaches storage only through the
        // one-time `initialize` above. On an already-initialized oracle that
        // branch is skipped, so baking a fresh `account_blob_id` into the
        // oracle's configurables and retargeting its proxy — both of which
        // this run does, and both of which succeed — still leaves
        // `get_prop_account_impl` answering with the PREVIOUS blob. Every
        // account keeps running the old bytecode while the deploy reports a
        // clean upgrade, which is the worst shape a bug can take.
        //
        // Compare-first, like every other reconcile here: an oracle already
        // on this implementation costs one read and no transaction.

        // State-checked: a resumed run initializes iff the pool has not
        // been initialized yet, whether or not this run created the proxy.
        let deployed_collateral = pool
            .methods()
            .collateral_asset()
            .simulate(Execution::state_read_only())
            .await
            .context("read deployed prop margin-pool collateral")?
            .value;
        ensure!(
            deployed_collateral == config.collateral_asset,
            "prop margin-pool collateral configurable mismatch"
        );
        ensure!(
            pool.methods()
                .collateral_decimals()
                .simulate(Execution::state_read_only())
                .await
                .context("read deployed prop margin-pool collateral decimals")?
                .value
                == config.collateral_decimals,
            "prop margin-pool decimals configurable mismatch"
        );
        ensure!(
            pool.methods()
                .max_tier_books()
                .simulate(Execution::state_read_only())
                .await
                .context("read deployed prop margin-pool book limit")?
                .value
                == config.max_tier_books,
            "prop margin-pool book-limit configurable mismatch"
        );
        let pool_is_initialized = pool
            .methods()
            .is_initialized()
            .simulate(Execution::state_read_only())
            .await
            .context("read deployed prop margin-pool initialization state")?
            .value;
        if !pool_is_initialized {
            // Same rule as the oracle's cosigner above: the seed only becomes
            // the payee here, on a pool that has never been initialized.
            if liquidator_defaulted {
                tracing::warn!(
                    "prop deploy: no liquidator given and this pool is being \
                     initialized - the deployer becomes the liquidator, and \
                     will receive the residue of every forced exit."
                );
            }
            pool.methods()
                .initialize()
                .call()
                .await
                .context("initialize prop margin pool")?;
        }

        Ok(Self {
            oracle,
            oracle_proxy,
            oracle_id,
            oracle_blob_id,
            price_feed,
            price_feed_id,
            registry,
            registry_proxy,
            registry_id,
            registry_blob_id,
            pool,
            pool_proxy,
            pool_id,
            pool_blob_id,
            account_blob_id,
            account_proxy_blob_id,
            account_salt: config.salt,
            deployer_wallet: deployer_wallet.clone(),
        })
    }

    /// Deploy and register one deterministic prop-account child.
    ///
    /// `parent_caller` submits the registration transaction and must resolve
    /// to `parent`; the registry enforces this relationship on chain.
    pub async fn deploy_account(
        &self,
        parent_caller: &W,
        parent: Identity,
        index: u64,
    ) -> Result<PropAccountProxyContract<W>> {
        ensure!(
            parent != Identity::Address(Address::zeroed()),
            "prop-account parent cannot be zero"
        );

        let configurables = PropAccountProxyContractConfigurables::default()
            .with_ORACLE_CONTRACT_ID(self.oracle_id)?
            .with_PARENT(parent)?
            .with_INDEX(index)?;
        let child_contract = regular_contract(
            PROP_ACCOUNT_PROXY_BYTECODE,
            PROP_ACCOUNT_PROXY_STORAGE,
            self.account_salt,
        )?
        .with_configurables(configurables);
        let (child_id, _) = deploy_regular(&self.deployer_wallet, child_contract)
            .await
            .context("deploy prop-account child")?;

        let child = PropAccountProxyContract::new(child_id, self.deployer_wallet.clone());
        if !self
            .registry
            .methods()
            .prop_is_valid(child_id)
            .simulate(Execution::state_read_only())
            .await?
            .value
        {
            TradeAccountRegistry::new(self.registry_id, parent_caller.clone())
                .methods()
                .prop_register_contract(child_id, parent, index)
                .with_contract_ids(&[self.oracle_id, child_id, self.pool_id])
                .call()
                .await
                .context("register prop-account child")?;
        }

        Ok(child)
    }

    /// Bind the implementation ABI to a deployed child proxy.
    pub fn account(&self, account_id: ContractId) -> PropAccountContract<W> {
        PropAccountContract::new(account_id, self.deployer_wallet.clone())
    }
}

/// Byte offsets of the margin-account proxy's `ORACLE_CONTRACT_ID`,
/// `PARENT` and `INDEX` configurables, in that order.
///
/// A build-time property of the bundled artifact — nothing touches the
/// chain. Public because the PLAIN registry upgrade has to repeat these
/// values verbatim or it resets them to zero; see
/// `live_prop_registry_config` in `o2-deploy`.
pub fn prop_account_proxy_offsets() -> Result<[u64; 3]> {
    fn only_offset(configurables: Configurables, name: &str) -> Result<u64> {
        let offsets: Vec<Configurable> = configurables.offsets_with_data;
        ensure!(
            offsets.len() == 1,
            "expected one {name} configurable, got {}",
            offsets.len()
        );
        Ok(offsets[0].offset)
    }

    let oracle: Configurables = PropAccountProxyContractConfigurables::default()
        .with_ORACLE_CONTRACT_ID(ContractId::zeroed())?
        .into();
    let parent: Configurables = PropAccountProxyContractConfigurables::default()
        .with_PARENT(Identity::Address(Address::zeroed()))?
        .into();
    let index: Configurables = PropAccountProxyContractConfigurables::default()
        .with_INDEX(0)?
        .into();

    Ok([
        only_offset(oracle, "oracle")?,
        only_offset(parent, "parent")?,
        only_offset(index, "index")?,
    ])
}

fn storage_slots(bytes: &[u8]) -> Result<Vec<StorageSlot>> {
    serde_json::from_slice(bytes).context("decode contract storage slots")
}

fn regular_contract(
    bytecode: &[u8],
    storage: &[u8],
    salt: Salt,
) -> Result<Contract<Regular>> {
    Ok(Contract::regular(
        bytecode.to_vec(),
        salt,
        storage_slots(storage)?,
    ))
}

fn regular_contract_with_implementation_storage(
    bytecode: &[u8],
    proxy_storage: &[u8],
    implementation_storage: &[u8],
    salt: Salt,
) -> Result<Contract<Regular>> {
    let mut slots = storage_slots(proxy_storage)?;
    for implementation_slot in storage_slots(implementation_storage)? {
        ensure!(
            !slots
                .iter()
                .any(|proxy_slot| proxy_slot.key() == implementation_slot.key()),
            "proxy and implementation storage slots collide"
        );
        slots.push(implementation_slot);
    }
    Ok(Contract::regular(bytecode.to_vec(), salt, slots))
}

/// Points a price-feed PROXY at the implementation this build carries,
/// exactly as the order books are upgraded: read the live target, rebuild
/// the configured blob, and retarget only when the two differ. A feed
/// already on this bytecode costs no transaction.
///
/// Returns the active implementation id.
///
/// `set_proxy_target` is owner-only, so this works on a feed this deployer
/// owns; a feed owned elsewhere must be upgraded by its own owner.
pub async fn upgrade_price_feed_implementation<W>(
    deployer_wallet: &W,
    price_feed_id: ContractId,
    owner: Identity,
    config: &PropDeployConfig,
) -> Result<ContractId>
where
    W: Account + Clone,
{
    let feed_proxy = PriceFeedProxyContract::new(price_feed_id, deployer_wallet.clone());
    let current = feed_proxy
        .methods()
        .proxy_target()
        .simulate(Execution::state_read_only())
        .await
        .context(
            "read the price feed's proxy target - an unproxied feed cannot be \
             upgraded in place",
        )?
        .value;
    let feed_blob_id = upload_implementation(
        deployer_wallet,
        PRICE_FEED_BYTECODE,
        PRICE_FEED_STORAGE,
        PriceFeedContractConfigurables::default()
            .with_INITIAL_OWNER(State::Initialized(owner))?,
        config,
    )
    .await
    .context("deploy configured price-feed implementation blob")?;
    let feed_blob_id = ContractId::from(feed_blob_id);
    if current != Some(feed_blob_id) {
        tracing::info!(
            "Upgrade price feed implementation from {current:?} to {feed_blob_id:?}"
        );
        feed_proxy
            .methods()
            .set_proxy_target(feed_blob_id)
            .call()
            .await
            .context("activate configured price-feed implementation")?;
    }
    Ok(feed_blob_id)
}

/// `PRICE_SUBMITTER_ROLE` on the price feed — the role `add_publisher`
/// grants and `publish_prices` demands. Mirrors the contract's constant.
pub const PRICE_SUBMITTER_ROLE: u64 = 2;

async fn upload_implementation<W>(
    deployer_wallet: &W,
    bytecode: &[u8],
    storage: &[u8],
    configurables: impl Into<Configurables>,
    config: &PropDeployConfig,
) -> Result<BlobId>
where
    W: Account,
{
    let (data_blobs, loader_blob) = blob_loader::build_loader_blobs(
        bytecode.to_vec(),
        config.salt,
        storage_slots(storage)?,
        configurables,
        config.max_words_per_blob,
    )?;
    blob_loader::upload_loader_blobs(deployer_wallet, data_blobs, loader_blob).await
}

async fn deploy_regular<W>(
    deployer_wallet: &W,
    contract: Contract<Regular>,
) -> Result<(ContractId, bool)>
where
    W: Account,
{
    let contract_id = contract.contract_id();
    let is_new = !deployer_wallet
        .try_provider()?
        .contract_exists(&contract_id)
        .await?;
    if is_new {
        contract
            .deploy(deployer_wallet, TxPolicies::default())
            .await?;
    }
    Ok((contract_id, is_new))
}

#[cfg(test)]
static PROP_DEPLOY_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        order_book_deploy::{
            OrderArgs,
            OrderBookConfigurables,
            OrderBookDeploy,
            OrderBookDeployConfig,
            OrderType,
        },
        prop::{
            MarginPoolPauseChanged,
            MarginPoolPlatformPayoutChanged,
            MarginPoolPriceFeedChanged,
            MarginPoolRegistryChanged,
            MarginTradeAccountWithdrawn,
            PriceInput,
            PropOrderBookCleanup,
            SessionClosed,
            SessionSeized,
            SettlementReason,
            TierParams,
        },
    };
    use fuels::test_helpers::{
        AssetConfig,
        WalletsConfig,
        launch_custom_provider_and_get_wallets,
    };
    use std::time::{
        SystemTime,
        UNIX_EPOCH,
    };

    fn assert_recent_timestamp(timestamp: u64) {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time predates the Unix epoch")
            .as_secs();
        assert!(
            timestamp.abs_diff(now) <= 1,
            "event timestamp {timestamp} is not close to {now}"
        );
    }

    #[tokio::test]
    async fn deploys_independent_prop_system_and_registers_child() {
        let _test_guard = PROP_DEPLOY_TEST_LOCK.lock().await;
        let collateral_asset = AssetId::new([1; 32]);
        let base_asset = AssetId::new([2; 32]);
        let initial_balance = 10_000_000_000u64;
        let mut wallets = launch_custom_provider_and_get_wallets(
            WalletsConfig::new_multiple_assets(
                2,
                vec![
                    AssetConfig {
                        id: AssetId::default(),
                        num_coins: 2,
                        coin_amount: initial_balance,
                    },
                    AssetConfig {
                        id: collateral_asset,
                        num_coins: 2,
                        coin_amount: initial_balance,
                    },
                    AssetConfig {
                        id: base_asset,
                        num_coins: 2,
                        coin_amount: initial_balance,
                    },
                ],
            ),
            None,
            Some(::fuels::test_helpers::ChainConfig::local_testnet()),
        )
        .await
        .unwrap();
        let user = wallets.pop().unwrap();
        let deployer = wallets.pop().unwrap();

        let deployment = PropDeployment::deploy(&deployer, &{
            // The production feed bounds a submission's age against the
            // block clock; this test publishes at a fixed timestamp.
            let mut config = PropDeployConfig::new(collateral_asset);
            config.max_offchain_age_seconds = Some(10_000_000_000);
            config
        })
        .await
        .unwrap();

        let oracle_target = deployment
            .oracle
            .methods()
            .get_prop_account_impl()
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value;
        assert_eq!(
            oracle_target,
            Some(ContractId::from(deployment.account_blob_id))
        );
        assert_eq!(
            deployment
                .oracle
                .methods()
                .get_prop_margin_pool()
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            Some(deployment.pool_id)
        );
        assert_eq!(
            deployment
                .registry
                .methods()
                .get_prop_oracle_id()
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            deployment.oracle_id
        );
        assert_eq!(
            deployment
                .registry
                .methods()
                .get_prop_pool_id()
                .with_contract_ids(&[deployment.oracle_id])
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            deployment.pool_id
        );
        assert_eq!(
            deployment
                .pool
                .methods()
                .registry()
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            deployment.registry_id
        );
        assert_eq!(
            deployment
                .pool
                .methods()
                .price_feed()
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            deployment.price_feed_id
        );
        let deployer_identity = Identity::Address(deployer.address());

        // The float is simply what the pool holds: outside money arrives as a
        // plain transfer, with no pool entry point to call.
        let inventory_amount = 1_234;
        deployer
            .force_transfer_to_contract(
                deployment.pool.contract_id(),
                inventory_amount,
                collateral_asset,
                TxPolicies::default(),
            )
            .await
            .unwrap();
        assert_eq!(
            deployment
                .pool
                .get_balances()
                .await
                .unwrap()
                .get(&collateral_asset)
                .copied()
                .unwrap_or_default(),
            inventory_amount,
        );

        let registry_update = deployment
            .pool
            .methods()
            .set_registry(deployment.oracle_id)
            .call()
            .await
            .unwrap();
        let registry_events = registry_update
            .decode_logs_with_type::<MarginPoolRegistryChanged>()
            .unwrap();
        assert_recent_timestamp(registry_events[0].timestamp.unix);
        assert_eq!(
            registry_events,
            vec![MarginPoolRegistryChanged {
                old_registry: deployment.registry_id,
                new_registry: deployment.oracle_id,
                timestamp: registry_events[0].timestamp.clone(),
            }]
        );
        assert_eq!(
            deployment
                .pool
                .methods()
                .registry()
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            deployment.oracle_id
        );
        deployment
            .pool
            .methods()
            .set_registry(deployment.registry_id)
            .call()
            .await
            .unwrap();

        let price_feed_update = deployment
            .pool
            .methods()
            .set_price_feed(deployment.oracle_id)
            .call()
            .await
            .unwrap();
        let price_feed_events = price_feed_update
            .decode_logs_with_type::<MarginPoolPriceFeedChanged>()
            .unwrap();
        assert_recent_timestamp(price_feed_events[0].timestamp.unix);
        assert_eq!(
            price_feed_events,
            vec![MarginPoolPriceFeedChanged {
                old_price_feed: deployment.price_feed_id,
                new_price_feed: deployment.oracle_id,
                timestamp: price_feed_events[0].timestamp.clone(),
            }]
        );
        assert_eq!(
            deployment
                .pool
                .methods()
                .price_feed()
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            deployment.oracle_id
        );
        deployment
            .pool
            .methods()
            .set_price_feed(deployment.price_feed_id)
            .call()
            .await
            .unwrap();

        let platform_payout = Identity::Address(user.address());
        let payout_update = deployment
            .pool
            .methods()
            .set_platform_payout(platform_payout)
            .call()
            .await
            .unwrap();
        let payout_events = payout_update
            .decode_logs_with_type::<MarginPoolPlatformPayoutChanged>()
            .unwrap();
        assert_recent_timestamp(payout_events[0].timestamp.unix);
        assert_eq!(
            payout_events,
            vec![MarginPoolPlatformPayoutChanged {
                old_platform_payout: deployer_identity,
                new_platform_payout: platform_payout,
                timestamp: payout_events[0].timestamp.clone(),
            }]
        );
        deployment
            .pool
            .methods()
            .set_platform_payout(deployer_identity)
            .call()
            .await
            .unwrap();

        let pause_response = deployment.pool.methods().pause().call().await.unwrap();
        let pause_events = pause_response
            .decode_logs_with_type::<MarginPoolPauseChanged>()
            .unwrap();
        assert_recent_timestamp(pause_events[0].timestamp.unix);
        assert_eq!(pause_events.len(), 1);
        assert!(pause_events[0].paused);

        let unpause_response = deployment.pool.methods().unpause().call().await.unwrap();
        let unpause_events = unpause_response
            .decode_logs_with_type::<MarginPoolPauseChanged>()
            .unwrap();
        assert_recent_timestamp(unpause_events[0].timestamp.unix);
        assert_eq!(unpause_events.len(), 1);
        assert!(!unpause_events[0].paused);

        let user_pool = PropMarginPoolContract::new(deployment.pool_id, user.clone());
        assert!(
            user_pool
                .methods()
                .set_registry(deployment.oracle_id)
                .call()
                .await
                .is_err()
        );

        assert!(
            deployment
                .pool
                .methods()
                .has_role(0, deployer_identity)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value
        );
        let order_book_configurables = OrderBookConfigurables::default()
            .with_MAKER_FEE(0u64.into())
            .unwrap()
            .with_TAKER_FEE(0u64.into())
            .unwrap()
            .with_MIN_ORDER(1)
            .unwrap()
            .with_DUST(0)
            .unwrap();
        let order_book_config =
            OrderBookDeployConfig::with_configurables(order_book_configurables);
        let order_book = OrderBookDeploy::deploy(
            &deployer,
            base_asset,
            collateral_asset,
            &order_book_config,
        )
        .await
        .unwrap();
        let mut second_order_book_config = order_book_config.clone();
        second_order_book_config.salt = Salt::from([1u8; 32]);
        let second_order_book = OrderBookDeploy::deploy(
            &deployer,
            base_asset,
            collateral_asset,
            &second_order_book_config,
        )
        .await
        .unwrap();

        deployment
            .price_feed
            .methods()
            .set_asset_decimals(collateral_asset, 6)
            .call()
            .await
            .unwrap();
        deployment
            .price_feed
            .methods()
            .set_asset_decimals(base_asset, 9)
            .call()
            .await
            .unwrap();
        deployment
            .price_feed
            .methods()
            .publish_prices(vec![
                PriceInput {
                    asset: collateral_asset,
                    bid: 1_000_000_000_000_000_000u64.into(),
                    ask: 1_000_000_000_000_000_000u64.into(),
                    // Strictly above the replay floor of 0, and in the past.
                    timestamp: 1,
                },
                PriceInput {
                    asset: base_asset,
                    bid: 2_000_000_000_000_000_000u64.into(),
                    ask: 2_000_000_000_000_000_000u64.into(),
                    timestamp: 1,
                },
            ])
            .call()
            .await
            .unwrap();
        assert!(
            deployment
                .price_feed
                .methods()
                .has_price(collateral_asset)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value
        );

        let tier_params = TierParams {
            line: 10_000_000,
            leverage: 5,
            duration: 86_400,
            maintenance_bps: 250,
            open_buffer_bps: 375,
            liq_price_factor: 9_900,
            // The amounts the old bps rates derived from this line: 6, 21,
            // 76 and 738 bps of 10_000_000.
            prolong_fee: [0, 21_000, 76_000, 738_000],
            max_credit_line_bps: 20_000,
            max_price_age: 60,
            open_fee: 0,
            profit_share_bps: 1_000,
            price_band_bps: 1_000,
        };
        assert!(
            deployment
                .pool
                .methods()
                .publish_tier_version(
                    1,
                    TierParams {
                        leverage: 0,
                        ..tier_params.clone()
                    },
                    vec![order_book.contract_id],
                )
                .call()
                .await
                .is_err()
        );
        deployment
            .pool
            .methods()
            .publish_tier_version(
                1,
                tier_params,
                vec![order_book.contract_id, second_order_book.contract_id],
            )
            .with_contract_ids(&[
                order_book.contract_id,
                second_order_book.contract_id,
                deployment.price_feed_id,
            ])
            .call()
            .await
            .unwrap();

        let tier = deployment
            .pool
            .methods()
            .get_tier(1, 1)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .expect("published tier version");
        assert_eq!(tier.line, 10_000_000);
        assert_eq!(
            deployment
                .pool
                .methods()
                .current_tier_version(1)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            Some(1)
        );
        assert_eq!(
            deployment
                .pool
                .methods()
                .tier_books(1, 1)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            vec![order_book.contract_id, second_order_book.contract_id]
        );
        let tier_assets = deployment
            .pool
            .methods()
            .tier_assets(1, 1)
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value;
        assert_eq!(tier_assets.len(), 2);
        assert!(tier_assets.contains(&base_asset));
        assert!(tier_assets.contains(&collateral_asset));
        assert!(
            deployment
                .pool
                .methods()
                .get_tier(1, 2)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value
                .is_none()
        );
        assert!(
            deployment
                .pool
                .methods()
                .tier_books(1, 2)
                .simulate(Execution::state_read_only())
                .await
                .is_err()
        );
        assert!(
            deployment
                .pool
                .methods()
                .tier_assets(1, 2)
                .simulate(Execution::state_read_only())
                .await
                .is_err()
        );

        deployment
            .price_feed
            .methods()
            .set_asset_decimals(base_asset, 8)
            .call()
            .await
            .unwrap();
        deployment
            .price_feed
            .methods()
            .publish_prices(vec![PriceInput {
                // Above this asset's replay floor, which the publish above
                // already moved to 1.
                asset: base_asset,
                bid: 2_000_000_000_000_000_000u64.into(),
                ask: 2_000_000_000_000_000_000u64.into(),
                timestamp: 2,
            }])
            .call()
            .await
            .unwrap();
        assert!(
            deployment
                .pool
                .methods()
                .set_price_feed(deployment.price_feed_id)
                .with_contracts(&[&deployment.price_feed])
                .call()
                .await
                .is_err()
        );
        deployment
            .price_feed
            .methods()
            .set_asset_decimals(base_asset, 9)
            .call()
            .await
            .unwrap();
        deployment
            .price_feed
            .methods()
            .publish_prices(vec![PriceInput {
                asset: base_asset,
                bid: 2_000_000_000_000_000_000u64.into(),
                ask: 2_000_000_000_000_000_000u64.into(),
                timestamp: 3,
            }])
            .call()
            .await
            .unwrap();

        let parent = Identity::Address(user.address());
        let registration_error = deployment
            .deploy_account(&deployer, parent, 7)
            .await
            .expect_err("a caller other than the configured parent must be rejected");
        assert!(
            format!("{registration_error:?}").contains("NotParent"),
            "unexpected registration error: {registration_error:?}"
        );
        let child = deployment.deploy_account(&user, parent, 7).await.unwrap();
        assert!(
            deployment
                .registry
                .methods()
                .prop_is_valid(child.contract_id())
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value
        );
        assert_eq!(
            child
                .methods()
                .parent()
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            parent
        );
        assert_eq!(
            child
                .methods()
                .index()
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            7
        );
        assert_eq!(
            child
                .methods()
                .pool()
                .with_contract_ids(&[deployment.oracle_id])
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            deployment.pool_id
        );
        assert_eq!(
            child
                .methods()
                .oracle()
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            deployment.oracle_id
        );

        let collateral = 2_000_000;
        let account = PropAccountContract::new(child.contract_id(), user.clone());
        let missing_payment_error = account
            .methods()
            .start_session(1, collateral, ProlongPeriod::SixHours)
            .with_contract_ids(&[
                deployment.oracle_id,
                deployment.pool_id,
                deployment.registry_id,
            ])
            .call()
            .await
            .unwrap_err();
        assert!(
            missing_payment_error
                .to_string()
                .contains("PaymentAmountMismatch"),
            "unexpected missing-payment error: {missing_payment_error:#}"
        );
        let mismatched_payment_error = account
            .methods()
            .start_session(1, collateral, ProlongPeriod::SixHours)
            .call_params(CallParameters::new(
                collateral - 1,
                collateral_asset,
                u64::MAX,
            ))
            .unwrap()
            .with_contract_ids(&[
                deployment.oracle_id,
                deployment.pool_id,
                deployment.registry_id,
            ])
            .call()
            .await
            .unwrap_err();
        assert!(
            mismatched_payment_error
                .to_string()
                .contains("PaymentAmountMismatch"),
            "unexpected mismatched-payment error: {mismatched_payment_error:#}"
        );
        let wrong_asset_error = account
            .methods()
            .start_session(1, collateral, ProlongPeriod::SixHours)
            .call_params(CallParameters::new(collateral, base_asset, u64::MAX))
            .unwrap()
            .with_contract_ids(&[
                deployment.oracle_id,
                deployment.pool_id,
                deployment.registry_id,
            ])
            .call()
            .await
            .unwrap_err();
        assert!(
            wrong_asset_error.to_string().contains("WrongAsset"),
            "unexpected wrong-asset error: {wrong_asset_error:#}"
        );

        let collateral_dust = 17;
        let base_dust = 23;
        user.force_transfer_to_contract(
            child.contract_id(),
            collateral_dust,
            collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
        user.force_transfer_to_contract(
            child.contract_id(),
            base_dust,
            base_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
        account
            .methods()
            .start_session(1, collateral, ProlongPeriod::SixHours)
            .call_params(CallParameters::new(collateral, collateral_asset, u64::MAX))
            .unwrap()
            .with_contract_ids(&[
                deployment.oracle_id,
                deployment.pool_id,
                deployment.registry_id,
            ])
            .with_variable_output_policy(VariableOutputPolicy::Exactly(2))
            .call()
            .await
            .unwrap();
        let provider = user.provider();
        assert_eq!(
            provider
                .get_contract_asset_balance(&child.contract_id(), &collateral_asset)
                .await
                .unwrap(),
            0
        );
        assert_eq!(
            provider
                .get_contract_asset_balance(&child.contract_id(), &base_asset)
                .await
                .unwrap(),
            0
        );

        assert!(
            deployment
                .pool
                .methods()
                .is_call_allowed(child.contract_id(), order_book.contract_id)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value
        );
        assert!(
            deployment
                .pool
                .methods()
                .is_call_allowed(child.contract_id(), second_order_book.contract_id)
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value
        );
        assert!(
            !deployment
                .pool
                .methods()
                .is_call_allowed(child.contract_id(), ContractId::new([0x99; 32]))
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value
        );

        let session = deployment
            .pool
            .methods()
            .get_session(child.contract_id())
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .expect("prop session opened");
        assert_eq!(session.session_id, 1);
        assert_eq!(session.credit_line, 10_000_000);
        assert_eq!(session.collateral, collateral);

        assert!(
            deployment
                .pool
                .methods()
                .min_sellable(child.contract_id(), base_asset)
                .with_contracts(&[&order_book.order_book, &second_order_book.order_book,])
                .simulate(Execution::state_read_only())
                .await
                .is_err()
        );

        let best_bid = 2_000_000;
        let bid_quantity = 1_000_000_000;
        order_book
            .order_book
            .methods()
            .create_order(OrderArgs {
                price: best_bid,
                quantity: bid_quantity,
                order_type: OrderType::Spot,
            })
            .call_params(CallParameters::new(
                bid_quantity * best_bid / 1_000_000_000,
                collateral_asset,
                u64::MAX,
            ))
            .unwrap()
            .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
            .call()
            .await
            .unwrap();
        assert_eq!(
            order_book
                .order_book
                .methods()
                .get_base_decimals()
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            1_000_000_000
        );
        assert_eq!(
            deployment
                .pool
                .methods()
                .min_sellable(child.contract_id(), base_asset)
                .with_contracts(&[&order_book.order_book, &second_order_book.order_book,])
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value,
            Some(500)
        );

        let close = account
            .methods()
            .close_session(Vec::<PropOrderBookCleanup>::new())
            .with_contracts(&[
                &deployment.oracle,
                &deployment.pool,
                &order_book.order_book,
                &second_order_book.order_book,
            ])
            .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
            .call()
            .await
            .unwrap();
        let close_events = close.decode_logs_with_type::<SessionClosed>().unwrap();
        assert!(
            close
                .decode_logs_with_type::<SessionSeized>()
                .unwrap()
                .is_empty()
        );
        assert_recent_timestamp(close_events[0].timestamp.unix);
        assert_eq!(
            close_events,
            vec![SessionClosed {
                account: child.contract_id(),
                session_id: 1,
                reason: SettlementReason::UserClose,
                v: 10_000_000,
                v_is_negative: false,
                v_liq: 10_000_000,
                v_liq_is_negative: false,
                profit_abs: 0,
                profit_is_negative: false,
                fees_accrued: 0,
                platform_total: 0,
                user_net: collateral,
                bad_debt: 0,
                cancelled_debt: vec![],
                payout_parent: vec![(collateral_asset, collateral)],
                payout_platform: vec![],
                timestamp: close_events[0].timestamp.clone(),
            }]
        );
        assert!(
            !deployment
                .pool
                .methods()
                .has_session(child.contract_id())
                .simulate(Execution::state_read_only())
                .await
                .unwrap()
                .value
        );

        let excess_collateral = 25_000_000;
        account
            .methods()
            .start_session(1, excess_collateral, ProlongPeriod::SixHours)
            .call_params(CallParameters::new(
                excess_collateral,
                collateral_asset,
                u64::MAX,
            ))
            .unwrap()
            .with_contract_ids(&[
                deployment.oracle_id,
                deployment.pool_id,
                deployment.registry_id,
            ])
            .call()
            .await
            .unwrap();
        let excess_session = deployment
            .pool
            .methods()
            .get_session(child.contract_id())
            .simulate(Execution::state_read_only())
            .await
            .unwrap()
            .value
            .expect("excess-collateral session opened");
        assert_eq!(excess_session.session_id, 2);
        assert_eq!(excess_session.collateral, excess_collateral);
        assert_eq!(excess_session.credit_line, 20_000_000);

        let excess_close = account
            .methods()
            .close_session(Vec::<PropOrderBookCleanup>::new())
            .with_contracts(&[
                &deployment.oracle,
                &deployment.pool,
                &order_book.order_book,
                &second_order_book.order_book,
            ])
            .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
            .call()
            .await
            .unwrap();
        let excess_close_events = excess_close
            .decode_logs_with_type::<SessionClosed>()
            .unwrap();
        assert_recent_timestamp(excess_close_events[0].timestamp.unix);
        assert_eq!(
            excess_close_events,
            vec![SessionClosed {
                account: child.contract_id(),
                session_id: 2,
                reason: SettlementReason::UserClose,
                v: 33_000_000,
                v_is_negative: false,
                v_liq: 33_000_000,
                v_liq_is_negative: false,
                profit_abs: 0,
                profit_is_negative: false,
                fees_accrued: 0,
                platform_total: 0,
                user_net: excess_collateral,
                bad_debt: 0,
                cancelled_debt: vec![],
                payout_parent: vec![(collateral_asset, excess_collateral)],
                payout_platform: vec![],
                timestamp: excess_close_events[0].timestamp.clone(),
            }]
        );

        let withdrawal = 1_000;
        user.force_transfer_to_contract(
            child.contract_id(),
            withdrawal,
            collateral_asset,
            TxPolicies::default(),
        )
        .await
        .unwrap();
        let balance_before = user.get_asset_balance(&collateral_asset).await.unwrap();
        let withdraw_response = account
            .methods()
            .withdraw(collateral_asset, withdrawal)
            .with_contract_ids(&[deployment.oracle_id, deployment.pool_id])
            .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
            .call()
            .await
            .unwrap();
        let withdraw_events = withdraw_response
            .decode_logs_with_type::<MarginTradeAccountWithdrawn>()
            .unwrap();
        assert_recent_timestamp(withdraw_events[0].timestamp.unix);
        assert_eq!(
            withdraw_events,
            vec![MarginTradeAccountWithdrawn {
                account: child.contract_id(),
                parent,
                asset_id: collateral_asset,
                amount: withdrawal,
                timestamp: withdraw_events[0].timestamp.clone(),
            }]
        );
        assert_eq!(
            user.get_asset_balance(&collateral_asset).await.unwrap(),
            balance_before + withdrawal as u128
        );
    }
}

#[cfg(test)]
#[path = "prop_deploy_tests.rs"]
mod integration_tests;