-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotocol-cli.rs
More file actions
executable file
·1280 lines (1138 loc) · 56.4 KB
/
protocol-cli.rs
File metadata and controls
executable file
·1280 lines (1138 loc) · 56.4 KB
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
#!/usr/bin/env rust-script
//! ```cargo
//! [package]
//! name = "protocol-cli"
//! version = "0.1.0"
//! edition = "2021"
//! description = "Protocol development and deployment tools including contract deployment, action whitelisting, and directory comparison"
//!
//! [dependencies]
//! anyhow = "1.0"
//! clap = { version = "4.5", features = ["derive"] }
//! serde = { version = "1.0", features = ["derive"] }
//! serde_json = "1.0"
//! serde_yaml = "0.9"
//! tokio = { version = "1.46", features = ["full"] }
//! regex = "1.11"
//! indexmap = { version = "2.10", features = ["serde"] }
//! colored = "3.0"
//! tempfile = "3.8"
//! merkle_hash = "3.8"
//! camino = "1.0"
//! alloy-primitives = "1.4"
//! alloy-sol-types = "1.4"
//! ```
use anyhow::{anyhow, Context, Result, bail};
use clap::{Parser, Subcommand};
use colored::*;
use merkle_hash::{MerkleTree, Encodable};
use serde_json::json;
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::Path;
use alloy_primitives::{Address, U256, hex};
use alloy_sol_types::SolValue;
#[derive(Parser)]
#[command(name = "protocol-cli")]
#[command(about = "Protocol development and deployment tools")]
#[command(long_about = "Protocol CLI for multi-chain contract deployment and management.")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Validate contract addresses match expected addresses
ValidateContracts {
/// Configuration file with lists of chains and contracts to manage
#[arg(short, long)]
config_file: String,
/// Directory containing network/chain environment variable configs
#[arg(long)]
env_dir: String,
/// Update the environment file with newly calculated addresses
#[arg(short, long)]
update: bool,
},
/// Deploy contracts to configured chains
DeployContracts {
/// Configuration file with lists of chains and contracts to manage
#[arg(short, long)]
config_file: String,
/// Directory containing network/chain environment variable configs
#[arg(long)]
env_dir: Option<String>,
/// Private key for deployment (if not provided, uses AWS KMS)
#[arg(short, long)]
private_key: Option<String>,
},
/// Whitelist actions within an action manager
WhitelistActions {
/// Configuration file with lists of chains and contracts to manage
#[arg(short, long)]
config_file: String,
/// JSON file containing deployed contract addresses to whitelist
#[arg(short, long)]
addresses_file: String,
/// Directory containing network/chain environment variable configs
#[arg(long)]
env_dir: Option<String>,
/// Optional private key for whitelisting (if not provided, uses AWS KMS)
#[arg(short, long)]
private_key: Option<String>,
},
/// Update chain configuration with deployed contract addresses
UpdateChainConfig {
/// Configuration file with lists of chains and contracts to manage
#[arg(short, long)]
config_file: String,
/// JSON file containing contract addresses (e.g., deployed-addresses.json from deploys)
#[arg(short, long)]
addresses_file: String,
/// Chain config file to update
#[arg(long)]
chain_config_file: String,
},
/// Compare directory contents using Merkle trees
CompareDirectories {
/// First directory to compare
dir1: String,
/// Second directory to compare
dir2: String,
/// Pattern to ignore during comparison
#[arg(long)]
ignore: Option<String>,
/// Show detailed differences when directories don't match
#[arg(long)]
show_diff: bool,
},
/// Verify deployed contracts on block explorers
VerifyContracts {
/// Configuration file containing deployment details
#[arg(short, long, default_value = ".github/scripts/deployment-config.yaml")]
config_file: String,
/// Networks directory containing common and chain-specific environment configuration
#[arg(short, long, default_value = ".github/networks/")]
env_dir: String,
/// Protocol repository root path
#[arg(short, long, default_value = ".")]
protocol_root: String,
/// Etherscan API key for contract verification
#[arg(short = 'k', long)]
etherscan_api_key: Option<String>,
/// Verifier service to use (etherscan, sourcify)
#[arg(short, long, default_value = "etherscan", value_parser = ["etherscan", "sourcify"])]
verifier: String,
},
}
#[derive(Debug, serde::Deserialize)]
struct DeploymentConfig {
contracts: Vec<String>,
chains: Option<Vec<String>>,
}
#[derive(Debug, Clone)]
struct ChainInfo {
chain_id: u64,
network: &'static str,
}
#[derive(Debug, Clone)]
#[allow(dead_code)]
enum ConstructorType {
None, // No constructor args
Owner, // Single owner address
Action, // (feeTokenRegistry, treasury, gasConstant)
Core, // Deployed by OtimDelegate, not directly verifiable
}
#[derive(Debug, Clone)]
struct ContractDetails {
script: Option<String>,
expected_addr_envvar: Option<&'static str>,
chain_config_key: Option<String>,
source_path: &'static str,
constructor_type: ConstructorType,
}
#[derive(Debug, Clone)]
struct TierConfig {
script: Option<String>, // For core tier group deployment
contracts: HashMap<String, ContractDetails>,
}
/// Gets chain information including chain ID and network
fn get_chain_info(chain: &str) -> Option<ChainInfo> {
Some(match chain {
"anvil" => ChainInfo { chain_id: 31337, network: "devnet" },
"base-sepolia" => ChainInfo { chain_id: 84532, network: "testnet" },
"base" => ChainInfo { chain_id: 8453, network: "mainnet" },
"optimism-sepolia" => ChainInfo { chain_id: 11155420, network: "testnet" },
"optimism" => ChainInfo { chain_id: 10, network: "mainnet" },
"arbitrum-sepolia" => ChainInfo { chain_id: 421614, network: "testnet" },
"arbitrum" => ChainInfo { chain_id: 42161, network: "mainnet" },
"ethereum-sepolia" => ChainInfo { chain_id: 11155111, network: "testnet" },
"ethereum" => ChainInfo { chain_id: 1, network: "mainnet" },
"polygon-amoy" => ChainInfo { chain_id: 80002, network: "testnet" },
"polygon" => ChainInfo { chain_id: 137, network: "mainnet" },
"bnb-testnet" => ChainInfo { chain_id: 97, network: "testnet" },
"bnb" => ChainInfo { chain_id: 56, network: "mainnet" },
"unichain-sepolia" => ChainInfo { chain_id: 1301, network: "testnet" },
"unichain" => ChainInfo { chain_id: 130, network: "mainnet" },
"pecorino-signet" => ChainInfo { chain_id: 14174, network: "testnet" },
"pecorino-host" => ChainInfo { chain_id: 3151908, network: "testnet" },
_ => return None,
})
}
/// Returns the tier-based contract mapping configuration
fn get_contract_mapping() -> HashMap<String, TierConfig> {
use std::collections::HashMap;
HashMap::from([
("core".to_string(), TierConfig {
script: Some("DeployCore".to_string()),
contracts: HashMap::from([
("OtimDelegate".to_string(), ContractDetails {
script: None,
expected_addr_envvar: Some("EXPECTED_OTIM_DELEGATE_ADDRESS"),
chain_config_key: Some("otim_delegate_addr".to_string()),
source_path: "src/OtimDelegate.sol:OtimDelegate",
constructor_type: ConstructorType::Owner,
}),
("Gateway".to_string(), ContractDetails {
script: None,
expected_addr_envvar: Some("EXPECTED_GATEWAY_ADDRESS"),
chain_config_key: Some("gateway_addr".to_string()),
source_path: "src/core/Gateway.sol:Gateway",
constructor_type: ConstructorType::Core,
}),
("InstructionStorage".to_string(), ContractDetails {
script: None,
expected_addr_envvar: Some("EXPECTED_INSTRUCTION_STORAGE_ADDRESS"),
chain_config_key: Some("instruction_storage_addr".to_string()),
source_path: "src/core/InstructionStorage.sol:InstructionStorage",
constructor_type: ConstructorType::Core,
}),
("ActionManager".to_string(), ContractDetails {
script: None,
expected_addr_envvar: Some("ACTION_MANAGER_ADDRESS"),
chain_config_key: Some("action_manager_addr".to_string()),
source_path: "src/core/ActionManager.sol:ActionManager",
constructor_type: ConstructorType::Core,
}),
]),
}),
("infrastructure".to_string(), TierConfig {
script: None,
contracts: HashMap::from([
("FeeTokenRegistry".to_string(), ContractDetails {
script: Some("DeployFeeTokenRegistry".to_string()),
expected_addr_envvar: Some("EXPECTED_FEE_TOKEN_REGISTRY_ADDRESS"),
chain_config_key: Some("fee_token_registry_addr".to_string()),
source_path: "src/infrastructure/FeeTokenRegistry.sol:FeeTokenRegistry",
constructor_type: ConstructorType::Owner,
}),
("Treasury".to_string(), ContractDetails {
script: Some("DeployTreasury".to_string()),
expected_addr_envvar: Some("EXPECTED_TREASURY_ADDRESS"),
chain_config_key: Some("treasury_addr".to_string()),
source_path: "src/infrastructure/Treasury.sol:Treasury",
constructor_type: ConstructorType::Owner,
}),
]),
}),
("actions".to_string(), TierConfig {
script: None,
contracts: HashMap::from([
("TransferAction".to_string(), ContractDetails {
script: Some("DeployTransferAction".to_string()),
expected_addr_envvar: Some("EXPECTED_TRANSFER_ACTION_ADDRESS"),
chain_config_key: Some("actions.Transfer".to_string()),
source_path: "src/actions/TransferAction.sol:TransferAction",
constructor_type: ConstructorType::Action,
}),
("TransferERC20Action".to_string(), ContractDetails {
script: Some("DeployTransferERC20Action".to_string()),
expected_addr_envvar: Some("EXPECTED_TRANSFER_ERC20_ACTION_ADDRESS"),
chain_config_key: Some("actions.TransferERC20".to_string()),
source_path: "src/actions/TransferERC20Action.sol:TransferERC20Action",
constructor_type: ConstructorType::Action,
}),
("RefuelAction".to_string(), ContractDetails {
script: Some("DeployRefuelAction".to_string()),
expected_addr_envvar: Some("EXPECTED_REFUEL_ACTION_ADDRESS"),
chain_config_key: Some("actions.Refuel".to_string()),
source_path: "src/actions/RefuelAction.sol:RefuelAction",
constructor_type: ConstructorType::Action,
}),
("RefuelERC20Action".to_string(), ContractDetails {
script: Some("DeployRefuelERC20Action".to_string()),
expected_addr_envvar: Some("EXPECTED_REFUEL_ERC20_ACTION_ADDRESS"),
chain_config_key: Some("actions.RefuelERC20".to_string()),
source_path: "src/actions/RefuelERC20Action.sol:RefuelERC20Action",
constructor_type: ConstructorType::Action,
}),
("UniswapV3ExactInputAction".to_string(), ContractDetails {
script: Some("DeployUniswapV3ExactInputAction".to_string()),
expected_addr_envvar: Some("EXPECTED_UNISWAP_V3_EXACT_INPUT_ACTION_ADDRESS"),
chain_config_key: Some("actions.UniswapV3ExactInput".to_string()),
source_path: "src/actions/UniswapV3ExactInputAction.sol:UniswapV3ExactInputAction",
constructor_type: ConstructorType::Action,
}),
("DeactivateInstructionAction".to_string(), ContractDetails {
script: Some("DeployDeactivateInstructionAction".to_string()),
expected_addr_envvar: Some("EXPECTED_DEACTIVATE_INSTRUCTION_ACTION_ADDRESS"),
chain_config_key: Some("actions.DeactivateInstruction".to_string()),
source_path: "src/actions/DeactivateInstructionAction.sol:DeactivateInstructionAction",
constructor_type: ConstructorType::Action,
}),
("SweepAction".to_string(), ContractDetails {
script: Some("DeploySweepAction".to_string()),
expected_addr_envvar: Some("EXPECTED_SWEEP_ACTION_ADDRESS"),
chain_config_key: Some("actions.Sweep".to_string()),
source_path: "src/actions/SweepAction.sol:SweepAction",
constructor_type: ConstructorType::Action,
}),
("SweepERC20Action".to_string(), ContractDetails {
script: Some("DeploySweepERC20Action".to_string()),
expected_addr_envvar: Some("EXPECTED_SWEEP_ERC20_ACTION_ADDRESS"),
chain_config_key: Some("actions.SweepERC20".to_string()),
source_path: "src/actions/SweepERC20Action.sol:SweepERC20Action",
constructor_type: ConstructorType::Action,
}),
("SweepCCTPAction".to_string(), ContractDetails {
script: Some("DeploySweepCCTPAction".to_string()),
expected_addr_envvar: Some("EXPECTED_SWEEP_CCTP_ACTION_ADDRESS"),
chain_config_key: Some("actions.SweepCCTP".to_string()),
source_path: "src/actions/SweepCCTPAction.sol:SweepCCTPAction",
constructor_type: ConstructorType::Action,
}),
("TransferCCTPAction".to_string(), ContractDetails {
script: Some("DeployTransferCCTPAction".to_string()),
expected_addr_envvar: Some("EXPECTED_TRANSFER_CCTP_ACTION_ADDRESS"),
chain_config_key: Some("actions.TransferCCTP".to_string()),
source_path: "src/actions/TransferCCTPAction.sol:TransferCCTPAction",
constructor_type: ConstructorType::Action,
}),
("SweepUniswapV3Action".to_string(), ContractDetails {
script: Some("DeploySweepUniswapV3Action".to_string()),
expected_addr_envvar: Some("EXPECTED_SWEEP_UNISWAP_V3_ACTION_ADDRESS"),
chain_config_key: Some("actions.SweepUniswapV3".to_string()),
source_path: "src/actions/SweepUniswapV3Action.sol:SweepUniswapV3Action",
constructor_type: ConstructorType::Action,
}),
("DepositERC4626Action".to_string(), ContractDetails {
script: Some("DeployDepositERC4626Action".to_string()),
expected_addr_envvar: Some("EXPECTED_DEPOSIT_ERC4626_ACTION_ADDRESS"),
chain_config_key: Some("actions.DepositERC4626".to_string()),
source_path: "src/actions/DepositERC4626Action.sol:DepositERC4626Action",
constructor_type: ConstructorType::Action,
}),
("SweepDepositERC4626Action".to_string(), ContractDetails {
script: Some("DeploySweepDepositERC4626Action".to_string()),
expected_addr_envvar: Some("EXPECTED_SWEEP_DEPOSIT_ERC4626_ACTION_ADDRESS"),
chain_config_key: Some("actions.SweepDepositERC4626".to_string()),
source_path: "src/actions/SweepDepositERC4626Action.sol:SweepDepositERC4626Action",
constructor_type: ConstructorType::Action,
}),
("WithdrawERC4626Action".to_string(), ContractDetails {
script: Some("DeployWithdrawERC4626Action".to_string()),
expected_addr_envvar: Some("EXPECTED_WITHDRAW_ERC4626_ACTION_ADDRESS"),
chain_config_key: Some("actions.WithdrawERC4626".to_string()),
source_path: "src/actions/WithdrawERC4626Action.sol:WithdrawERC4626Action",
constructor_type: ConstructorType::Action,
}),
("SweepWithdrawERC4626Action".to_string(), ContractDetails {
script: Some("DeploySweepWithdrawERC4626Action".to_string()),
expected_addr_envvar: Some("EXPECTED_SWEEP_WITHDRAW_ERC4626_ACTION_ADDRESS"),
chain_config_key: Some("actions.SweepWithdrawERC4626".to_string()),
source_path: "src/actions/SweepWithdrawERC4626Action.sol:SweepWithdrawERC4626Action",
constructor_type: ConstructorType::Action,
}),
("CallOnceAction".to_string(), ContractDetails {
script: Some("DeployCallOnceAction".to_string()),
expected_addr_envvar: Some("EXPECTED_CALL_ONCE_ACTION_ADDRESS"),
chain_config_key: Some("actions.CallOnce".to_string()),
source_path: "src/actions/CallOnceAction.sol:CallOnceAction",
constructor_type: ConstructorType::Action,
}),
("RequestDepositERC7540Action".to_string(), ContractDetails {
script: Some("DeployRequestDepositERC7540Action".to_string()),
expected_addr_envvar: Some("EXPECTED_REQUEST_DEPOSIT_ERC7540_ACTION_ADDRESS"),
chain_config_key: Some("actions.RequestDepositERC7540".to_string()),
source_path: "src/actions/RequestDepositERC7540Action.sol:RequestDepositERC7540Action",
constructor_type: ConstructorType::Action,
}),
("SweepRequestDepositERC7540Action".to_string(), ContractDetails {
script: Some("DeploySweepRequestDepositERC7540Action".to_string()),
expected_addr_envvar: Some("EXPECTED_SWEEP_REQUEST_DEPOSIT_ERC7540_ACTION_ADDRESS"),
chain_config_key: Some("actions.SweepRequestDepositERC7540".to_string()),
source_path: "src/actions/SweepRequestDepositERC7540Action.sol:SweepRequestDepositERC7540Action",
constructor_type: ConstructorType::Action,
}),
]),
}),
])
}
// =============================================================================
// UTILITIES
// =============================================================================
/// Prints log messages with colored formatting
fn info(msg: &str) {
println!("{} {}", "[INFO]".green().bold(), msg);
}
fn warn(msg: &str) {
println!("{} {}", "[WARN]".yellow().bold(), msg);
}
/// Converts camelCase to SNAKE_CASE
fn to_snake_case(s: &str) -> String {
s.chars()
.enumerate()
.flat_map(|(i, c)| {
if i > 0 && c.is_uppercase() && !s.chars().nth(i - 1).unwrap().is_uppercase() {
vec!['_', c]
} else {
vec![c]
}
})
.collect::<String>()
.to_uppercase()
}
/// Loads and parses the deployment configuration from YAML file
fn load_deploy_config(config_path: &str) -> Result<DeploymentConfig> {
let content = fs::read_to_string(config_path)
.with_context(|| format!("Failed to read config file: {}", config_path))?;
serde_yaml::from_str(&content)
.with_context(|| "Failed to parse deployment config")
}
/// Gets contracts for a specific tier from the config list
fn get_tier_contracts(config: &DeploymentConfig, tier: &str) -> Vec<String> {
let mapping = get_contract_mapping();
if let Some(tier_config) = mapping.get(tier) {
config.contracts.iter()
.filter(|contract| {
// Handle "Core" as a special case that maps to all core contracts
if *contract == "Core" && tier == "core" {
true
} else {
tier_config.contracts.contains_key(*contract)
}
})
.cloned()
.collect()
} else {
Vec::new()
}
}
/// Finds contract details by name from the tier-based mapping
fn find_contract_details(contract: &str) -> Option<ContractDetails> {
let mapping = get_contract_mapping();
for (_, tier_config) in mapping.iter() {
if let Some(details) = tier_config.contracts.get(contract) {
return Some(details.clone());
}
}
None
}
/// Loads environment variables from file and sets them in the current process
fn load_env_file(path: &str) -> Result<HashMap<String, String>> {
let mut expected_addr_envvars = HashMap::new();
if !Path::new(path).exists() {
warn(&format!("Environment file not found: {}, will create it", path));
return Ok(expected_addr_envvars);
}
let content = fs::read_to_string(path)?;
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue; // Skip empty lines and comments
}
if let Some((key, value)) = line.split_once('=') {
let key = key.trim();
let value = value.trim();
expected_addr_envvars.insert(key.to_string(), value.to_string());
env::set_var(key, value);
}
}
Ok(expected_addr_envvars)
}
/// Loads environment files for a chain (auto-detects network from chain name)
fn load_chain_env_files(env_dir: &str, chain: &str, network: &str) -> Result<HashMap<String, String>> {
[(format!("{}/.env-gas-constants", env_dir), "gas constants"),
(format!("{}/{}/.env-otim-{}", env_dir, network, network), "shared"),
(format!("{}/{}/.env-{}", env_dir, network, chain), "chain")]
.iter()
.try_fold(HashMap::new(), |mut env_vars, (path, env_type)| {
info(&format!("Loading {} env: {}", env_type, path));
env_vars.extend(load_env_file(path)?);
Ok(env_vars)
})
}
/// Updates environment file with new key-value pairs, preserving comments and structure
fn update_env_file(path: &str, updates: &HashMap<String, String>) -> Result<()> {
let content = if Path::new(path).exists() {
fs::read_to_string(path)
.with_context(|| format!("Failed to read environment file: {}", path))?
} else {
String::new()
};
let mut updated_content = content;
for (key, new_value) in updates {
// Replace the value for the specific key
let pattern = format!(r"(?m)^{}=.*$", regex::escape(key));
let replacement = format!("{}={}", key, new_value);
if let Ok(re) = regex::Regex::new(&pattern) {
if re.is_match(&updated_content) {
updated_content = re.replace_all(&updated_content, replacement.as_str()).to_string();
} else {
// If key doesn't exist, append it
if !updated_content.ends_with('\n') {
updated_content.push('\n');
}
updated_content.push_str(&replacement);
updated_content.push('\n');
}
}
}
fs::write(path, updated_content)
.with_context(|| format!("Failed to write environment file: {}", path))
}
/// Executes any command with retry logic
async fn run_command(command: &str, args: &[&str], max_retries: u32, retry_errors: &[&str]) -> Result<String> {
let mut last_error = None;
for attempt in 1..=max_retries {
info(&format!("Executing: {} {}", command, args.join(" ")));
let output = tokio::process::Command::new(command)
.args(args)
.env_clear()
.envs(env::vars())
.output()
.await?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let error = anyhow!("Command failed: {} {}\nError: {}", command, args.join(" "), stderr);
let error_msg = error.to_string();
// Check if error matches any retry patterns (case-insensitive)
let error_msg_lower = error_msg.to_lowercase();
let should_retry = retry_errors.iter().any(|pattern| error_msg_lower.contains(&pattern.to_lowercase()));
if should_retry && attempt < max_retries {
warn(&format!("Attempt {}/{} failed ({}), retrying...", attempt, max_retries, error_msg.lines().next().unwrap_or("unknown error")));
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
last_error = Some(error);
continue;
}
return Err(error);
}
return Ok(String::from_utf8_lossy(&output.stdout).to_string());
}
Err(last_error.unwrap_or_else(|| anyhow!("Max retries exceeded")))
}
/// Extracts contract address from forge deployment output using regex pattern matching
fn extract_address(output: &str, contract: &str) -> Result<String> {
use regex::Regex;
let re = Regex::new(&format!(r"{} deployed at: (0x[a-fA-F0-9]{{40}})", contract))?;
re.captures(output)
.and_then(|caps| caps.get(1))
.map(|m| m.as_str().to_string())
.ok_or_else(|| anyhow!("Address not found for {}", contract))
}
// =============================================================================
// VALIDATE CONTRACTS
// =============================================================================
/// Calculates contract addresses for a specific deployment tier using dry-run
async fn calculate_addresses_by_tier(config: &DeploymentConfig, tier: &str) -> Result<HashMap<String, String>> {
let contracts = get_tier_contracts(config, tier);
let mut addresses = HashMap::new();
let tier_mapping = get_contract_mapping();
if let Some(tier_config) = tier_mapping.get(tier) {
// Group contracts by script
let mut script_groups: HashMap<String, Vec<String>> = HashMap::new();
for contract in contracts {
if contract == "Core" && tier == "core" {
// Handle Core as a special case - deploy all core contracts together
if let Some(core_script) = &tier_config.script {
let core_contracts: Vec<String> = tier_config.contracts.keys().cloned().collect();
script_groups.entry(core_script.clone()).or_default().extend(core_contracts);
}
} else if let Some(details) = tier_config.contracts.get(&contract) {
// Skip contracts without expected_addr_envvar property
if details.expected_addr_envvar.is_none() {
info(&format!("Skipping {} - no expected_addr_envvar configured", contract));
continue;
}
// For core tier, use the tier-level script; for others, use individual contract script
let script_to_use = if tier == "core" {
tier_config.script.clone().unwrap_or_else(|| details.script.clone().unwrap_or_default())
} else {
details.script.clone().unwrap_or_default()
};
script_groups.entry(script_to_use).or_default().push(contract);
} else {
warn(&format!("Contract {} not found in {} tier mapping, skipping", contract, tier));
}
}
// Execute each script and extract addresses for all contracts in that script
for (script, script_contracts) in script_groups {
let args = vec!["script", script.as_str(), "--json"];
let output = run_command("forge", &args, 1, &[]).await?;
for contract in script_contracts {
if let Ok(address) = extract_address(&output, &contract) {
addresses.insert(contract, address);
} else {
warn(&format!("Could not extract address for {} from script {}", contract, script));
}
}
}
}
Ok(addresses)
}
/// Validates calculated contract addresses against environment file values
async fn validate_addresses(config: &DeploymentConfig, network_env_file: &str, chain_env_file: &str, update: bool) -> Result<()> {
let network_env = load_env_file(network_env_file)?;
let chain_env = load_env_file(chain_env_file)?;
let mut calculated_addresses = HashMap::new();
let mut network_updates = HashMap::new();
let mut chain_updates = HashMap::new();
// Calculate addresses for all tiers
for tier in ["core", "infrastructure", "actions"] {
info(&format!("Calculating {} addresses...", tier));
let addresses = calculate_addresses_by_tier(config, tier).await?;
// Update environment for next tier dependencies
for (contract, address) in &addresses {
if let Some(details) = find_contract_details(contract) {
if let Some(env_var) = &details.expected_addr_envvar {
env::set_var(env_var, address);
}
}
}
calculated_addresses.extend(addresses);
}
// Compare addresses and collect updates (route to chain or network env file)
for (contract, calculated_address) in &calculated_addresses {
if let Some(details) = find_contract_details(contract) {
if let Some(env_var) = &details.expected_addr_envvar {
let is_non_create2 = matches!(*env_var,
"EXPECTED_UNISWAP_V3_EXACT_INPUT_ACTION_ADDRESS" | "EXPECTED_SWEEP_CCTP_ACTION_ADDRESS" |
"EXPECTED_TRANSFER_CCTP_ACTION_ADDRESS" | "EXPECTED_SWEEP_UNISWAP_V3_ACTION_ADDRESS"
);
let (env, updates_map) = if is_non_create2 {
(&chain_env, &mut chain_updates)
} else {
(&network_env, &mut network_updates)
};
let env_file_path = if is_non_create2 { chain_env_file } else { network_env_file };
let current_address = env.get(*env_var).map(|s| s.as_str()).unwrap_or("NOT_SET");
if current_address != calculated_address {
warn(&format!("{}: {} → {} ({})", contract, current_address, calculated_address, env_file_path));
updates_map.insert(env_var.to_string(), calculated_address.clone());
} else {
info(&format!("{}: {} ✓", contract, calculated_address));
}
} else {
info(&format!("{}: {} (skipped)", contract, calculated_address));
}
} else {
info(&format!("{}: {} (skipped)", contract, calculated_address));
}
}
// Apply updates and/or report differences
let has_updates = !network_updates.is_empty() || !chain_updates.is_empty();
if has_updates {
if update {
if !network_updates.is_empty() {
update_env_file(network_env_file, &network_updates)?;
info(&format!("Updated {}", network_env_file));
}
if !chain_updates.is_empty() {
update_env_file(chain_env_file, &chain_updates)?;
info(&format!("Updated {}", chain_env_file));
}
} else {
info("Address differences detected. Use --update to apply changes.");
}
std::process::exit(2);
} else {
info("All addresses match");
}
Ok(())
}
// =============================================================================
// DEPLOY CONTRACTS
// =============================================================================
/// Checks if an error is a known/expected error that should not be retried
fn is_known_error(error: &str) -> bool {
error.contains("CreateCollision") ||
error.contains("AlreadyAdded") ||
error.contains("empty revert data")
}
/// Executes a forge deployment command with retry logic
async fn run_forge_deploy(script: &str, private_key: Option<&str>) -> Result<String> {
let rpc_url = env::var("RPC_URL").context("RPC_URL not found")?;
let use_legacy = env::var("FORGE_LEGACY")
.map(|v| v.eq_ignore_ascii_case("true") || v == "1")
.unwrap_or(false);
let mut args: Vec<&str> = vec![
"script", script,
"--broadcast",
"--rpc-url", rpc_url.as_str(),
"--timeout", "30", // 30 second timeout
];
if use_legacy {
args.push("--legacy");
}
if let Some(pk) = private_key {
args.extend_from_slice(&["--private-key", pk]);
} else {
args.push("--aws");
}
args.push("--json");
let retry_errors = &["failed to get block", "timed out", "dispatch failure", "connection", "reset by peer"];
run_command("forge", &args, 3, retry_errors).await
}
/// Deploys all contracts in tier order
async fn deploy_contracts(config: &DeploymentConfig, private_key: Option<&str>) -> Result<HashMap<String, String>> {
info("Deploying contracts...");
let mut all_addresses = HashMap::new();
let tier_mapping = get_contract_mapping();
for tier in ["core", "infrastructure", "actions"] {
info(&format!("Deploying {} contracts...", tier));
let contracts = get_tier_contracts(config, tier);
let tier_config = tier_mapping.get(tier).unwrap();
// Deploy each contract
for contract in &contracts {
if contract == "Core" && tier == "core" {
// Deploy all core contracts together
if let Some(script) = &tier_config.script {
match run_forge_deploy(script, private_key).await {
Ok(output) => {
for (core_contract, details) in &tier_config.contracts {
if let Ok(addr) = extract_address(&output, core_contract) {
info(&format!("✓ Deployed {}: {}", core_contract, addr));
all_addresses.insert(core_contract.clone(), addr.clone());
if let Some(env_var) = &details.expected_addr_envvar {
env::set_var(env_var, &addr);
}
}
}
}
Err(e) if is_known_error(&e.to_string()) => {
info("Core already deployed, collecting existing addresses");
for (core_contract, details) in &tier_config.contracts {
if let Some(env_var) = &details.expected_addr_envvar {
let existing_addr = env::var(env_var)
.with_context(|| format!("No existing address found for {} ({})", core_contract, env_var))?;
info(&format!("- Using existing {}: {}", core_contract, existing_addr));
all_addresses.insert(core_contract.clone(), existing_addr);
}
}
}
Err(e) => bail!("Core deployment failed with unknown error: {}", e),
}
}
} else if let Some(details) = tier_config.contracts.get(contract) {
// Deploy individual contract
let script = details.script.clone().unwrap_or_else(|| format!("Deploy{}", contract));
match run_forge_deploy(&script, private_key).await {
Ok(output) => {
if let Ok(addr) = extract_address(&output, contract) {
info(&format!("✓ Deployed {}: {}", contract, addr));
all_addresses.insert(contract.clone(), addr.clone());
if let Some(env_var) = &details.expected_addr_envvar {
env::set_var(env_var, &addr);
}
}
}
Err(e) if is_known_error(&e.to_string()) => {
info(&format!("Contract {} already deployed", contract));
if let Some(env_var) = &details.expected_addr_envvar {
let existing_addr = env::var(env_var)
.with_context(|| format!("No existing address found for {} ({})", contract, env_var))?;
info(&format!("- Using existing {}: {}", contract, existing_addr));
all_addresses.insert(contract.clone(), existing_addr);
}
}
Err(e) => bail!("Contract {} deployment failed with unknown error: {}", contract, e),
}
}
// Add delay between deployments to prevent nonce conflicts
if let Some(last_contract) = contracts.last() {
if contract != last_contract {
tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
}
}
}
// Update environment for next tier dependencies
for (contract, address) in &all_addresses {
if let Some(details) = find_contract_details(contract) {
if let Some(env_var) = &details.expected_addr_envvar {
env::set_var(env_var, address);
}
}
}
}
info(&format!("Deployment completed! Collected {} addresses", all_addresses.len()));
Ok(all_addresses)
}
// =============================================================================
// WHITELIST ACTIONS
// =============================================================================
/// Whitelists all action contracts in the action manager for a specific chain
async fn whitelist_actions_for_chain(chain: &str, addresses: &HashMap<String, String>, private_key: Option<&str>) -> Result<()> {
let action_contracts: Vec<_> = addresses.iter()
.filter(|(name, _)| name.ends_with("Action"))
.collect();
if action_contracts.is_empty() {
info(&format!("No action contracts found for {}", chain));
return Ok(());
}
let rpc_url = env::var("RPC_URL")?;
let use_legacy = env::var("FORGE_LEGACY")
.map(|v| v.eq_ignore_ascii_case("true") || v == "1")
.unwrap_or(false);
for (contract_name, action_address) in &action_contracts {
info(&format!("Whitelisting {} at {}...", contract_name, action_address));
let mut args = vec![
"script", "AddAction", "--sig", "run(address)", "--broadcast",
"--rpc-url", &rpc_url
];
if use_legacy {
args.push("--legacy");
}
if let Some(pk) = private_key {
args.extend_from_slice(&["--private-key", pk]);
} else {
args.push("--aws");
}
args.push(action_address);
let retry_errors = &["failed to get block", "timed out", "dispatch failure", "connection", "reset by peer"];
match run_command("forge", &args, 3, retry_errors).await {
Ok(_) => {
info(&format!("✓ {} whitelisted", contract_name));
}
Err(e) => {
let error_str = e.to_string();
if is_known_error(&error_str) {
info(&format!("- {} already whitelisted", contract_name));
} else {
bail!("Failed to whitelist {}: {}", contract_name, e);
}
}
}
// Add delay between whitelisting operations to prevent nonce conflicts
if let Some((last_contract_name, _)) = action_contracts.last() {
if *contract_name != *last_contract_name {
tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
}
}
}
info(&format!("✓ Completed whitelisting {} contracts for {}", action_contracts.len(), chain));
Ok(())
}
// =============================================================================
// UPDATE CHAIN CONFIG
// =============================================================================
/// Update chain configuration with deployed contract addresses
async fn update_chain_config(config: &DeploymentConfig, addresses_file: &str, chain_config_file: &str) -> Result<()> {
let addresses_by_chain: HashMap<String, HashMap<String, String>> =
serde_json::from_str(&fs::read_to_string(addresses_file)?)?;
let mut chain_config: serde_json::Value = serde_json::from_str(&fs::read_to_string(chain_config_file)?)?;
let chains = config.chains.as_ref().filter(|c| !c.is_empty())
.ok_or_else(|| anyhow!("No chains in config"))?;
let tier_mapping = get_contract_mapping();
let mut has_changes = false;
for chain in chains {
let chain_id = get_chain_info(chain).ok_or_else(|| anyhow!("Unknown chain: {}", chain))?.chain_id;
let addresses = addresses_by_chain.get(chain)
.ok_or_else(|| anyhow!("No addresses found for '{}'", chain))?;
let target_key = chain_config.as_object()
.and_then(|obj| obj.iter().find(|(k, _)| k.parse::<u64>().ok() == Some(chain_id)))
.map(|(k, _)| k.clone())
.ok_or_else(|| anyhow!("Chain '{}' (chain_id: {}) not found in config", chain, chain_id))?;
let target = chain_config[&target_key].as_object_mut().ok_or_else(|| anyhow!("Invalid chain block"))?;
let mut updated = false;
for (contract_name, address) in addresses {
if let Some(key) = tier_mapping.values().find_map(|t| t.contracts.get(contract_name)?.chain_config_key.as_ref()) {
if let Some(action_name) = key.strip_prefix("actions.") {
let actions = target.entry("actions").or_insert_with(|| json!({})).as_object_mut().unwrap();
if actions.get(address).and_then(|v| v.as_str()) != Some(action_name) {
actions.insert(address.clone(), json!(action_name));
updated = true;
}
} else if target.get(key).and_then(|v| v.as_str()) != Some(address) {
target.insert(key.clone(), json!(address));
updated = true;
}
}
}
info(&format!("{} {}", if updated { "✓" } else { "-" }, chain));
has_changes |= updated;
}
if has_changes {
fs::write(chain_config_file, serde_json::to_string_pretty(&chain_config)?)?;
info(&format!("✓ Updated {} chains", chains.len()));
std::process::exit(2);
}
info("No changes needed");
std::process::exit(0);
}
// =============================================================================
// VERIFY CONTRACTS
// =============================================================================
/// Encodes constructor arguments based on contract type and specific action patterns
fn encode_constructor_args(constructor_type: &ConstructorType, contract_name: &str, env_vars: &HashMap<String, String>) -> Result<String> {
let get_envvar = |key: &str| -> Result<Address> {
env_vars.get(key).ok_or_else(|| anyhow!("{} not found", key))?
.parse().with_context(|| format!("Failed to parse address: {}", key))
};
match constructor_type {
ConstructorType::None | ConstructorType::Core => Ok(String::new()),
ConstructorType::Owner => Ok(hex::encode_prefixed(get_envvar("OWNER_ADDRESS")?.abi_encode())),
ConstructorType::Action => {
let (fee, treasury) = (get_envvar("EXPECTED_FEE_TOKEN_REGISTRY_ADDRESS")?, get_envvar("EXPECTED_TREASURY_ADDRESS")?);
let gas_key = match contract_name {
"SweepCCTPAction" => "SWEEP_CCTP_ACTION".to_string(),
"TransferCCTPAction" => "TRANSFER_CCTP_ACTION".to_string(),
"SweepUniswapV3Action" => "SWEEP_UNISWAP_V3_ACTION".to_string(),
"UniswapV3ExactInputAction" => "UNISWAP_V3_EXACT_INPUT_ACTION".to_string(),
_ => to_snake_case(contract_name),
};
let gas = env_vars.get(&format!("{}_GAS_CONSTANT", gas_key))
.ok_or_else(|| anyhow!("Gas constant not found for {}", contract_name))?
.parse::<u64>().map(U256::from)
.with_context(|| format!("Failed to parse gas constant for {}", contract_name))?;
Ok(hex::encode_prefixed(match contract_name {
"CallOnceAction" | "DeactivateInstructionAction" =>