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