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