|
| 1 | +use anyhow::{Context, Result}; |
| 2 | +use serde::{Deserialize, Serialize}; |
| 3 | +use std::fs; |
| 4 | +use std::path::Path; |
| 5 | + |
| 6 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 7 | +pub struct RpcEndpoint { |
| 8 | + pub name: String, |
| 9 | + pub url: String, |
| 10 | + pub description: String, |
| 11 | +} |
| 12 | + |
| 13 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 14 | +pub struct Config { |
| 15 | + pub endpoints: Vec<RpcEndpoint>, |
| 16 | + pub default_endpoint: String, |
| 17 | +} |
| 18 | + |
| 19 | +impl Config { |
| 20 | + pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self> { |
| 21 | + let content = fs::read_to_string(path.as_ref()) |
| 22 | + .with_context(|| format!("Failed to read config file: {}", path.as_ref().display()))?; |
| 23 | + |
| 24 | + let config: Config = |
| 25 | + serde_json::from_str(&content).with_context(|| "Failed to parse config file")?; |
| 26 | + |
| 27 | + config.validate()?; |
| 28 | + Ok(config) |
| 29 | + } |
| 30 | + |
| 31 | + #[cfg(test)] |
| 32 | + pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> { |
| 33 | + let content = serde_json::to_string_pretty(self).context("Failed to serialize config")?; |
| 34 | + |
| 35 | + fs::write(path.as_ref(), content) |
| 36 | + .with_context(|| format!("Failed to write config file: {}", path.as_ref().display()))?; |
| 37 | + |
| 38 | + Ok(()) |
| 39 | + } |
| 40 | + |
| 41 | + pub fn get_endpoint(&self, name: &str) -> Option<&RpcEndpoint> { |
| 42 | + self.endpoints.iter().find(|e| e.name == name) |
| 43 | + } |
| 44 | + |
| 45 | + pub fn get_endpoint_url(&self, name: &str) -> Option<&str> { |
| 46 | + self.get_endpoint(name).map(|e| e.url.as_str()) |
| 47 | + } |
| 48 | + |
| 49 | + pub fn get_default_endpoint(&self) -> Option<&RpcEndpoint> { |
| 50 | + self.get_endpoint(&self.default_endpoint) |
| 51 | + } |
| 52 | + |
| 53 | + pub fn get_default_url(&self) -> Option<&str> { |
| 54 | + self.get_default_endpoint().map(|e| e.url.as_str()) |
| 55 | + } |
| 56 | + |
| 57 | + fn validate(&self) -> Result<()> { |
| 58 | + if self.endpoints.is_empty() { |
| 59 | + anyhow::bail!("Config must contain at least one endpoint"); |
| 60 | + } |
| 61 | + |
| 62 | + if !self |
| 63 | + .endpoints |
| 64 | + .iter() |
| 65 | + .any(|e| e.name == self.default_endpoint) |
| 66 | + { |
| 67 | + anyhow::bail!( |
| 68 | + "Default endpoint '{}' not found in endpoints list", |
| 69 | + self.default_endpoint |
| 70 | + ); |
| 71 | + } |
| 72 | + |
| 73 | + let names: Vec<_> = self.endpoints.iter().map(|e| &e.name).collect(); |
| 74 | + let unique_names: std::collections::HashSet<_> = names.iter().collect(); |
| 75 | + if names.len() != unique_names.len() { |
| 76 | + anyhow::bail!("Endpoint names must be unique"); |
| 77 | + } |
| 78 | + |
| 79 | + for endpoint in &self.endpoints { |
| 80 | + if endpoint.name.is_empty() { |
| 81 | + anyhow::bail!("Endpoint name cannot be empty"); |
| 82 | + } |
| 83 | + if endpoint.url.is_empty() { |
| 84 | + anyhow::bail!("Endpoint URL cannot be empty"); |
| 85 | + } |
| 86 | + if !endpoint.url.starts_with("ws://") && !endpoint.url.starts_with("wss://") { |
| 87 | + anyhow::bail!( |
| 88 | + "Endpoint URL '{}' must start with ws:// or wss://", |
| 89 | + endpoint.url |
| 90 | + ); |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + Ok(()) |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +#[allow(dead_code)] |
| 99 | +pub fn chain_name_from_endpoint(endpoint: &str, config: &Config) -> String { |
| 100 | + if let Some(rpc_endpoint) = config.endpoints.iter().find(|e| e.url == endpoint) { |
| 101 | + return rpc_endpoint.description.clone(); |
| 102 | + } |
| 103 | + |
| 104 | + match endpoint { |
| 105 | + e if e.contains("polkadot") && !e.contains("kusama") && !e.contains("westend") => { |
| 106 | + "Polkadot".to_string() |
| 107 | + } |
| 108 | + e if e.contains("kusama") => "Kusama".to_string(), |
| 109 | + e if e.contains("westend") => "Westend".to_string(), |
| 110 | + e if e.contains("rococo") => "Rococo".to_string(), |
| 111 | + e if e.contains("paseo") => "Paseo".to_string(), |
| 112 | + e if e.contains("asset-hub") && e.contains("polkadot") => "Asset Hub Polkadot".to_string(), |
| 113 | + e if e.contains("asset-hub") && e.contains("kusama") => "Asset Hub Kusama".to_string(), |
| 114 | + e if e.contains("asset-hub") && e.contains("westend") => "Asset Hub Westend".to_string(), |
| 115 | + _ => "Custom Chain".to_string(), |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +#[cfg(test)] |
| 120 | +mod tests { |
| 121 | + use super::*; |
| 122 | + use std::fs; |
| 123 | + use std::path::PathBuf; |
| 124 | + |
| 125 | + #[test] |
| 126 | + fn test_load_existing_config() { |
| 127 | + // Test loading the actual config file |
| 128 | + let config = Config::load_from_file("rpc_endpoints.json"); |
| 129 | + assert!(config.is_ok(), "Should be able to load rpc_endpoints.json"); |
| 130 | + |
| 131 | + let config = config.unwrap(); |
| 132 | + assert!(!config.endpoints.is_empty()); |
| 133 | + assert!(!config.default_endpoint.is_empty()); |
| 134 | + assert!(config.get_endpoint(&config.default_endpoint).is_some()); |
| 135 | + } |
| 136 | + |
| 137 | + #[test] |
| 138 | + fn test_config_validation() { |
| 139 | + // Create a test config manually |
| 140 | + let mut config = Config { |
| 141 | + endpoints: vec![], |
| 142 | + default_endpoint: "test".to_string(), |
| 143 | + }; |
| 144 | + |
| 145 | + // Test empty endpoints |
| 146 | + assert!(config.validate().is_err()); |
| 147 | + |
| 148 | + // Test invalid default endpoint |
| 149 | + config.endpoints = vec![RpcEndpoint { |
| 150 | + name: "test".to_string(), |
| 151 | + url: "wss://test.com".to_string(), |
| 152 | + description: "Test".to_string(), |
| 153 | + }]; |
| 154 | + config.default_endpoint = "nonexistent".to_string(); |
| 155 | + assert!(config.validate().is_err()); |
| 156 | + |
| 157 | + // Test duplicate names |
| 158 | + config.endpoints.push(RpcEndpoint { |
| 159 | + name: "test".to_string(), |
| 160 | + url: "wss://test2.com".to_string(), |
| 161 | + description: "Test 2".to_string(), |
| 162 | + }); |
| 163 | + config.default_endpoint = "test".to_string(); |
| 164 | + assert!(config.validate().is_err()); |
| 165 | + } |
| 166 | + |
| 167 | + #[test] |
| 168 | + fn test_save_and_load() { |
| 169 | + let temp_file = PathBuf::from("test_config_temp.json"); |
| 170 | + let config = Config { |
| 171 | + endpoints: vec![RpcEndpoint { |
| 172 | + name: "test".to_string(), |
| 173 | + url: "wss://test.com".to_string(), |
| 174 | + description: "Test endpoint".to_string(), |
| 175 | + }], |
| 176 | + default_endpoint: "test".to_string(), |
| 177 | + }; |
| 178 | + |
| 179 | + // Save config |
| 180 | + assert!(config.save_to_file(&temp_file).is_ok()); |
| 181 | + |
| 182 | + // Load config |
| 183 | + let loaded = Config::load_from_file(&temp_file).unwrap(); |
| 184 | + assert_eq!(loaded.endpoints.len(), config.endpoints.len()); |
| 185 | + assert_eq!(loaded.default_endpoint, config.default_endpoint); |
| 186 | + assert_eq!(loaded.endpoints[0].name, config.endpoints[0].name); |
| 187 | + |
| 188 | + // Clean up |
| 189 | + fs::remove_file(temp_file).ok(); |
| 190 | + } |
| 191 | +} |
0 commit comments