Skip to main content

ows_core/
config.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::path::PathBuf;
4
5/// Backup configuration.
6#[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/// Application configuration.
16#[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    /// Returns the built-in default RPC endpoints for well-known chains.
29    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.insert("nano:mainnet".into(), "https://rpc.nano.to".into());
77        rpc.insert("eip155:4217".into(), "https://rpc.tempo.xyz".into());
78        rpc.insert(
79            "eip155:999".into(),
80            "https://rpc.hyperliquid.xyz/evm".into(),
81        );
82        rpc
83    }
84}
85
86impl Default for Config {
87    fn default() -> Self {
88        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
89        Config {
90            vault_path: PathBuf::from(home).join(".ows"),
91            rpc: Self::default_rpc(),
92            plugins: HashMap::new(),
93            backup: None,
94        }
95    }
96}
97
98impl Config {
99    /// Look up an RPC URL by chain identifier.
100    pub fn rpc_url(&self, chain: &str) -> Option<&str> {
101        self.rpc.get(chain).map(|s| s.as_str())
102    }
103
104    /// Load config from a file path, or return defaults if file doesn't exist.
105    pub fn load(path: &std::path::Path) -> Result<Self, crate::error::OwsError> {
106        if !path.exists() {
107            return Ok(Config::default());
108        }
109        let contents =
110            std::fs::read_to_string(path).map_err(|e| crate::error::OwsError::InvalidInput {
111                message: format!("failed to read config: {}", e),
112            })?;
113        serde_json::from_str(&contents).map_err(|e| crate::error::OwsError::InvalidInput {
114            message: format!("failed to parse config: {}", e),
115        })
116    }
117
118    /// Load `~/.ows/config.json`, merging user overrides on top of defaults.
119    /// If the file doesn't exist, returns the built-in defaults.
120    pub fn load_or_default() -> Self {
121        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
122        let config_path = PathBuf::from(home).join(".ows/config.json");
123        Self::load_or_default_from(&config_path)
124    }
125
126    /// Load config from a specific path, merging user overrides on top of defaults.
127    pub fn load_or_default_from(path: &std::path::Path) -> Self {
128        let mut config = Config::default();
129        if path.exists() {
130            if let Ok(contents) = std::fs::read_to_string(path) {
131                if let Ok(user_config) = serde_json::from_str::<Config>(&contents) {
132                    // User overrides take priority
133                    for (k, v) in user_config.rpc {
134                        config.rpc.insert(k, v);
135                    }
136                    config.plugins = user_config.plugins;
137                    config.backup = user_config.backup;
138                    if user_config.vault_path.as_path() != std::path::Path::new("/tmp/.ows")
139                        && user_config.vault_path.to_string_lossy() != ""
140                    {
141                        config.vault_path = user_config.vault_path;
142                    }
143                }
144            }
145        }
146        config
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn test_default_vault_path() {
156        let config = Config::default();
157        let path_str = config.vault_path.to_string_lossy();
158        assert!(path_str.ends_with(".ows"));
159    }
160
161    #[test]
162    fn test_serde_roundtrip() {
163        let mut rpc = HashMap::new();
164        rpc.insert(
165            "eip155:1".to_string(),
166            "https://eth.rpc.example".to_string(),
167        );
168
169        let config = Config {
170            vault_path: PathBuf::from("/home/test/.ows"),
171            rpc,
172            plugins: HashMap::new(),
173            backup: None,
174        };
175        let json = serde_json::to_string(&config).unwrap();
176        let config2: Config = serde_json::from_str(&json).unwrap();
177        assert_eq!(config.vault_path, config2.vault_path);
178        assert_eq!(config.rpc, config2.rpc);
179    }
180
181    #[test]
182    fn test_rpc_lookup_hit() {
183        let mut config = Config::default();
184        config.rpc.insert(
185            "eip155:1".to_string(),
186            "https://eth.rpc.example".to_string(),
187        );
188        assert_eq!(config.rpc_url("eip155:1"), Some("https://eth.rpc.example"));
189    }
190
191    #[test]
192    fn test_default_rpc_endpoints() {
193        let config = Config::default();
194        assert_eq!(config.rpc_url("eip155:1"), Some("https://eth.llamarpc.com"));
195        assert_eq!(
196            config.rpc_url("eip155:137"),
197            Some("https://polygon-rpc.com")
198        );
199        assert_eq!(config.rpc_url("eip155:9745"), Some("https://rpc.plasma.to"));
200        assert_eq!(
201            config.rpc_url("solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"),
202            Some("https://api.mainnet-beta.solana.com")
203        );
204        assert_eq!(
205            config.rpc_url("bip122:000000000019d6689c085ae165831e93"),
206            Some("https://mempool.space/api")
207        );
208        assert_eq!(
209            config.rpc_url("cosmos:cosmoshub-4"),
210            Some("https://cosmos-rest.publicnode.com")
211        );
212        assert_eq!(
213            config.rpc_url("tron:mainnet"),
214            Some("https://api.trongrid.io")
215        );
216        assert_eq!(
217            config.rpc_url("ton:mainnet"),
218            Some("https://toncenter.com/api/v2")
219        );
220        assert_eq!(config.rpc_url("eip155:4217"), Some("https://rpc.tempo.xyz"));
221        assert_eq!(
222            config.rpc_url("eip155:999"),
223            Some("https://rpc.hyperliquid.xyz/evm")
224        );
225    }
226
227    #[test]
228    fn test_rpc_lookup_miss() {
229        let config = Config::default();
230        assert_eq!(config.rpc_url("eip155:99999"), None);
231    }
232
233    #[test]
234    fn test_optional_backup() {
235        let config = Config::default();
236        let json = serde_json::to_value(&config).unwrap();
237        assert!(json.get("backup").is_none());
238    }
239
240    #[test]
241    fn test_backup_config_serde() {
242        let config = Config {
243            vault_path: PathBuf::from("/tmp/.ows"),
244            rpc: HashMap::new(),
245            plugins: HashMap::new(),
246            backup: Some(BackupConfig {
247                path: PathBuf::from("/tmp/backup"),
248                auto_backup: Some(true),
249                max_backups: Some(5),
250            }),
251        };
252        let json = serde_json::to_value(&config).unwrap();
253        assert!(json.get("backup").is_some());
254        assert_eq!(json["backup"]["auto_backup"], true);
255    }
256
257    #[test]
258    fn test_load_nonexistent_returns_default() {
259        let config = Config::load(std::path::Path::new("/nonexistent/path/config.json")).unwrap();
260        assert!(config.vault_path.to_string_lossy().ends_with(".ows"));
261    }
262
263    #[test]
264    fn test_load_or_default_nonexistent() {
265        let config = Config::load_or_default_from(std::path::Path::new("/nonexistent/config.json"));
266        // Should have all default RPCs
267        assert_eq!(config.rpc.len(), 21);
268        assert_eq!(config.rpc_url("eip155:1"), Some("https://eth.llamarpc.com"));
269    }
270
271    #[test]
272    fn test_load_or_default_merges_overrides() {
273        let dir = tempfile::tempdir().unwrap();
274        let config_path = dir.path().join("config.json");
275        let user_config = serde_json::json!({
276            "vault_path": "/tmp/custom-vault",
277            "rpc": {
278                "eip155:1": "https://custom-eth.rpc",
279                "eip155:11155111": "https://sepolia.rpc"
280            }
281        });
282        std::fs::write(&config_path, serde_json::to_string(&user_config).unwrap()).unwrap();
283
284        let config = Config::load_or_default_from(&config_path);
285        // User override replaces default
286        assert_eq!(config.rpc_url("eip155:1"), Some("https://custom-eth.rpc"));
287        // User-added chain
288        assert_eq!(
289            config.rpc_url("eip155:11155111"),
290            Some("https://sepolia.rpc")
291        );
292        // Defaults preserved
293        assert_eq!(
294            config.rpc_url("eip155:137"),
295            Some("https://polygon-rpc.com")
296        );
297        // Custom vault path
298        assert_eq!(config.vault_path, PathBuf::from("/tmp/custom-vault"));
299    }
300}