1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::path::PathBuf;
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct BackupConfig {
8 pub path: PathBuf,
9 #[serde(skip_serializing_if = "Option::is_none")]
10 pub auto_backup: Option<bool>,
11 #[serde(skip_serializing_if = "Option::is_none")]
12 pub max_backups: Option<u32>,
13}
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct Config {
18 pub vault_path: PathBuf,
19 #[serde(default)]
20 pub rpc: HashMap<String, String>,
21 #[serde(default)]
22 pub plugins: HashMap<String, serde_json::Value>,
23 #[serde(skip_serializing_if = "Option::is_none")]
24 pub backup: Option<BackupConfig>,
25}
26
27impl Config {
28 pub fn default_rpc() -> HashMap<String, String> {
30 let mut rpc = HashMap::new();
31 rpc.insert("eip155:1".into(), "https://eth.llamarpc.com".into());
32 rpc.insert("eip155:137".into(), "https://polygon-rpc.com".into());
33 rpc.insert("eip155:42161".into(), "https://arb1.arbitrum.io/rpc".into());
34 rpc.insert("eip155:10".into(), "https://mainnet.optimism.io".into());
35 rpc.insert("eip155:8453".into(), "https://mainnet.base.org".into());
36 rpc.insert("eip155:9745".into(), "https://rpc.plasma.to".into());
37 rpc.insert(
38 "eip155:56".into(),
39 "https://bsc-dataseed.binance.org".into(),
40 );
41 rpc.insert(
42 "eip155:43114".into(),
43 "https://api.avax.network/ext/bc/C/rpc".into(),
44 );
45 rpc.insert(
46 "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp".into(),
47 "https://api.mainnet-beta.solana.com".into(),
48 );
49 rpc.insert(
50 "bip122:000000000019d6689c085ae165831e93".into(),
51 "https://mempool.space/api".into(),
52 );
53 rpc.insert(
54 "cosmos:cosmoshub-4".into(),
55 "https://cosmos-rest.publicnode.com".into(),
56 );
57 rpc.insert("tron:mainnet".into(), "https://api.trongrid.io".into());
58 rpc.insert("ton:mainnet".into(), "https://toncenter.com/api/v2".into());
59 rpc.insert(
60 "fil:mainnet".into(),
61 "https://api.node.glif.io/rpc/v1".into(),
62 );
63 rpc.insert(
64 "sui:mainnet".into(),
65 "https://fullnode.mainnet.sui.io:443".into(),
66 );
67 rpc
68 }
69}
70
71impl Default for Config {
72 fn default() -> Self {
73 let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
74 Config {
75 vault_path: PathBuf::from(home).join(".ows"),
76 rpc: Self::default_rpc(),
77 plugins: HashMap::new(),
78 backup: None,
79 }
80 }
81}
82
83impl Config {
84 pub fn rpc_url(&self, chain: &str) -> Option<&str> {
86 self.rpc.get(chain).map(|s| s.as_str())
87 }
88
89 pub fn load(path: &std::path::Path) -> Result<Self, crate::error::OwsError> {
91 if !path.exists() {
92 return Ok(Config::default());
93 }
94 let contents =
95 std::fs::read_to_string(path).map_err(|e| crate::error::OwsError::InvalidInput {
96 message: format!("failed to read config: {}", e),
97 })?;
98 serde_json::from_str(&contents).map_err(|e| crate::error::OwsError::InvalidInput {
99 message: format!("failed to parse config: {}", e),
100 })
101 }
102
103 pub fn load_or_default() -> Self {
106 let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
107 let config_path = PathBuf::from(home).join(".ows/config.json");
108 Self::load_or_default_from(&config_path)
109 }
110
111 pub fn load_or_default_from(path: &std::path::Path) -> Self {
113 let mut config = Config::default();
114 if path.exists() {
115 if let Ok(contents) = std::fs::read_to_string(path) {
116 if let Ok(user_config) = serde_json::from_str::<Config>(&contents) {
117 for (k, v) in user_config.rpc {
119 config.rpc.insert(k, v);
120 }
121 config.plugins = user_config.plugins;
122 config.backup = user_config.backup;
123 if user_config.vault_path.as_path() != std::path::Path::new("/tmp/.ows")
124 && user_config.vault_path.to_string_lossy() != ""
125 {
126 config.vault_path = user_config.vault_path;
127 }
128 }
129 }
130 }
131 config
132 }
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 #[test]
140 fn test_default_vault_path() {
141 let config = Config::default();
142 let path_str = config.vault_path.to_string_lossy();
143 assert!(path_str.ends_with(".ows"));
144 }
145
146 #[test]
147 fn test_serde_roundtrip() {
148 let mut rpc = HashMap::new();
149 rpc.insert(
150 "eip155:1".to_string(),
151 "https://eth.rpc.example".to_string(),
152 );
153
154 let config = Config {
155 vault_path: PathBuf::from("/home/test/.ows"),
156 rpc,
157 plugins: HashMap::new(),
158 backup: None,
159 };
160 let json = serde_json::to_string(&config).unwrap();
161 let config2: Config = serde_json::from_str(&json).unwrap();
162 assert_eq!(config.vault_path, config2.vault_path);
163 assert_eq!(config.rpc, config2.rpc);
164 }
165
166 #[test]
167 fn test_rpc_lookup_hit() {
168 let mut config = Config::default();
169 config.rpc.insert(
170 "eip155:1".to_string(),
171 "https://eth.rpc.example".to_string(),
172 );
173 assert_eq!(config.rpc_url("eip155:1"), Some("https://eth.rpc.example"));
174 }
175
176 #[test]
177 fn test_default_rpc_endpoints() {
178 let config = Config::default();
179 assert_eq!(config.rpc_url("eip155:1"), Some("https://eth.llamarpc.com"));
180 assert_eq!(
181 config.rpc_url("eip155:137"),
182 Some("https://polygon-rpc.com")
183 );
184 assert_eq!(config.rpc_url("eip155:9745"), Some("https://rpc.plasma.to"));
185 assert_eq!(
186 config.rpc_url("solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"),
187 Some("https://api.mainnet-beta.solana.com")
188 );
189 assert_eq!(
190 config.rpc_url("bip122:000000000019d6689c085ae165831e93"),
191 Some("https://mempool.space/api")
192 );
193 assert_eq!(
194 config.rpc_url("cosmos:cosmoshub-4"),
195 Some("https://cosmos-rest.publicnode.com")
196 );
197 assert_eq!(
198 config.rpc_url("tron:mainnet"),
199 Some("https://api.trongrid.io")
200 );
201 assert_eq!(
202 config.rpc_url("ton:mainnet"),
203 Some("https://toncenter.com/api/v2")
204 );
205 }
206
207 #[test]
208 fn test_rpc_lookup_miss() {
209 let config = Config::default();
210 assert_eq!(config.rpc_url("eip155:999"), None);
211 }
212
213 #[test]
214 fn test_optional_backup() {
215 let config = Config::default();
216 let json = serde_json::to_value(&config).unwrap();
217 assert!(json.get("backup").is_none());
218 }
219
220 #[test]
221 fn test_backup_config_serde() {
222 let config = Config {
223 vault_path: PathBuf::from("/tmp/.ows"),
224 rpc: HashMap::new(),
225 plugins: HashMap::new(),
226 backup: Some(BackupConfig {
227 path: PathBuf::from("/tmp/backup"),
228 auto_backup: Some(true),
229 max_backups: Some(5),
230 }),
231 };
232 let json = serde_json::to_value(&config).unwrap();
233 assert!(json.get("backup").is_some());
234 assert_eq!(json["backup"]["auto_backup"], true);
235 }
236
237 #[test]
238 fn test_load_nonexistent_returns_default() {
239 let config = Config::load(std::path::Path::new("/nonexistent/path/config.json")).unwrap();
240 assert!(config.vault_path.to_string_lossy().ends_with(".ows"));
241 }
242
243 #[test]
244 fn test_load_or_default_nonexistent() {
245 let config = Config::load_or_default_from(std::path::Path::new("/nonexistent/config.json"));
246 assert_eq!(config.rpc.len(), 15);
248 assert_eq!(config.rpc_url("eip155:1"), Some("https://eth.llamarpc.com"));
249 }
250
251 #[test]
252 fn test_load_or_default_merges_overrides() {
253 let dir = tempfile::tempdir().unwrap();
254 let config_path = dir.path().join("config.json");
255 let user_config = serde_json::json!({
256 "vault_path": "/tmp/custom-vault",
257 "rpc": {
258 "eip155:1": "https://custom-eth.rpc",
259 "eip155:11155111": "https://sepolia.rpc"
260 }
261 });
262 std::fs::write(&config_path, serde_json::to_string(&user_config).unwrap()).unwrap();
263
264 let config = Config::load_or_default_from(&config_path);
265 assert_eq!(config.rpc_url("eip155:1"), Some("https://custom-eth.rpc"));
267 assert_eq!(
269 config.rpc_url("eip155:11155111"),
270 Some("https://sepolia.rpc")
271 );
272 assert_eq!(
274 config.rpc_url("eip155:137"),
275 Some("https://polygon-rpc.com")
276 );
277 assert_eq!(config.vault_path, PathBuf::from("/tmp/custom-vault"));
279 }
280}