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