o2-deploy 0.1.20-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
//! 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,
    },
};
use serde_with::serde_as;
use std::ops::{
    Deref,
    DerefMut,
};

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 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>,
    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,
    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,
            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 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>,
}

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

#[derive(Debug, Clone, Copy, Default)]
pub struct OwnershipTransferOptions {
    pub new_proxy_owner: Option<fuels::types::Address>,
    pub new_contract_owner: Option<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>,
}

// ---------------------------------------------------------------------------
// 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 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?;
    let (trade_account_registry, trade_account_registry_blob_id) =
        deploy_trade_account_registry(
            wallet.clone(),
            params.upgrade_bytecode,
            trade_account_oracle_deploy.clone(),
            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,
        },
    )
    .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")?;

    transfer_ownership(
        &wallet,
        &params,
        &order_book_registry,
        &trade_account_registry,
        &trade_account_oracle_deploy,
        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,
        order_book_whitelist_id,
        order_book_blacklist_id,
        order_book_registry_id,
        order_book_registry_blob_id,
        pairs,
        fast_bridge_asset_registry_proxy_id,
    };

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

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

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>,
    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 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))
}

async fn deploy_trade_account_registry<W>(
    deployer_wallet: W,
    should_upgrade_bytecode: bool,
    trade_account_deploy: TradeAccountDeploy<W>,
    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,
                &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 trade_account_register_blob = TradeAccountRegistryManager::register_blob(
            &deployer_wallet,
            trade_account_oracle_id,
            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,
                    &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?;

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