solana_cli_config/config.rs
1use std::sync::LazyLock;
2// Wallet settings that can be configured for long-term use
3use {
4 serde::{Deserialize, Serialize},
5 std::{collections::HashMap, io, path::Path},
6 url::Url,
7};
8
9/// The default path to the CLI configuration file.
10///
11/// This is a [LazyLock] of `Option<String>`, the value of which is
12///
13/// > `~/.config/solana/cli/config.yml`
14///
15/// It will only be `None` if it is unable to identify the user's home
16/// directory, which should not happen under typical OS environments.
17pub static CONFIG_FILE: LazyLock<Option<String>> = LazyLock::new(|| {
18 dirs_next::home_dir().map(|mut path| {
19 path.extend([".config", "solana", "cli", "config.yml"]);
20 path.to_str().unwrap().to_string()
21 })
22});
23
24/// The Solana CLI configuration.
25#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
26pub struct Config {
27 /// The RPC address of a Solana validator node.
28 ///
29 /// Typical values for mainnet, devnet, and testnet are [described in the
30 /// Solana documentation][rpcdocs].
31 ///
32 /// For local testing, the typical value is `http://localhost:8899`.
33 ///
34 /// [rpcdocs]: https://solana.com/docs/core/clusters
35 pub json_rpc_url: String,
36 /// The address to connect to for receiving event notifications.
37 ///
38 /// If it is an empty string then the correct value will be derived
39 /// from `json_rpc_url`.
40 ///
41 /// The default value is the empty string.
42 pub websocket_url: String,
43 /// The default signing source, which may be a keypair file, but may also
44 /// represent several other types of signers, as described in the
45 /// documentation for `solana_clap_utils::keypair::signer_from_path`.
46 /// Because it represents sources other than a simple path, the name
47 /// `keypair_path` is misleading, and exists for backwards compatibility
48 /// reasons.
49 ///
50 /// The signing source can be loaded with either the `signer_from_path`
51 /// function, or with `solana_clap_utils::keypair::DefaultSigner`.
52 pub keypair_path: String,
53 /// A mapping from Solana addresses to human-readable names.
54 ///
55 /// By default the only value in this map is the system program.
56 #[serde(default)]
57 pub address_labels: HashMap<String, String>,
58 /// The default commitment level.
59 ///
60 /// By default the value is "confirmed", as defined by
61 /// `solana_commitment_config::CommitmentLevel::Confirmed`.
62 #[serde(default)]
63 pub commitment: String,
64}
65
66impl Default for Config {
67 fn default() -> Self {
68 let keypair_path = {
69 let mut keypair_path = dirs_next::home_dir().expect("home directory");
70 keypair_path.extend([".config", "solana", "id.json"]);
71 keypair_path.to_str().unwrap().to_string()
72 };
73 let json_rpc_url = "https://api.mainnet-beta.solana.com".to_string();
74
75 // Empty websocket_url string indicates the client should
76 // `Config::compute_websocket_url(&json_rpc_url)`
77 let websocket_url = "".to_string();
78
79 let mut address_labels = HashMap::new();
80 address_labels.insert(
81 "11111111111111111111111111111111".to_string(),
82 "System Program".to_string(),
83 );
84
85 let commitment = "confirmed".to_string();
86
87 Self {
88 json_rpc_url,
89 websocket_url,
90 keypair_path,
91 address_labels,
92 commitment,
93 }
94 }
95}
96
97impl Config {
98 /// Load a configuration from file.
99 ///
100 /// # Errors
101 ///
102 /// This function may return typical file I/O errors.
103 pub fn load(config_file: &str) -> Result<Self, io::Error> {
104 crate::load_config_file(config_file)
105 }
106
107 /// Save a configuration to file.
108 ///
109 /// If the file's directory does not exist, it will be created. If the file
110 /// already exists, it will be overwritten.
111 ///
112 /// # Errors
113 ///
114 /// This function may return typical file I/O errors.
115 pub fn save(&self, config_file: &str) -> Result<(), io::Error> {
116 crate::save_config_file(self, config_file)
117 }
118
119 /// Compute the websocket URL from the RPC URL.
120 ///
121 /// The address is created from the RPC URL by:
122 ///
123 /// - adding 1 to the port number,
124 /// - using the "wss" scheme if the RPC URL has an "https" scheme, or the
125 /// "ws" scheme if the RPC URL has an "http" scheme.
126 ///
127 /// If `json_rpc_url` cannot be parsed as a URL then this function returns
128 /// the empty string.
129 pub fn compute_websocket_url(json_rpc_url: &str) -> String {
130 let json_rpc_url: Option<Url> = json_rpc_url.parse().ok();
131 if json_rpc_url.is_none() {
132 return "".to_string();
133 }
134 let json_rpc_url = json_rpc_url.unwrap();
135 let is_secure = json_rpc_url.scheme().eq_ignore_ascii_case("https");
136 let mut ws_url = json_rpc_url.clone();
137 ws_url
138 .set_scheme(if is_secure { "wss" } else { "ws" })
139 .expect("unable to set scheme");
140 if let Some(port) = json_rpc_url.port() {
141 let port = port.checked_add(1).expect("port out of range");
142 ws_url.set_port(Some(port)).expect("unable to set port");
143 }
144 ws_url.to_string()
145 }
146
147 /// Load a map of address/name pairs from a YAML file at the given path and
148 /// insert them into the configuration.
149 pub fn import_address_labels<P>(&mut self, filename: P) -> Result<(), io::Error>
150 where
151 P: AsRef<Path>,
152 {
153 let imports: HashMap<String, String> = crate::load_config_file(filename)?;
154 for (address, label) in imports.into_iter() {
155 self.address_labels.insert(address, label);
156 }
157 Ok(())
158 }
159
160 /// Save the map of address/name pairs contained in the configuration to a
161 /// YAML file at the given path.
162 pub fn export_address_labels<P>(&self, filename: P) -> Result<(), io::Error>
163 where
164 P: AsRef<Path>,
165 {
166 crate::save_config_file(&self.address_labels, filename)
167 }
168}
169
170#[cfg(test)]
171mod test {
172 use super::*;
173
174 #[test]
175 fn compute_websocket_url() {
176 assert_eq!(
177 Config::compute_websocket_url("http://api.devnet.solana.com"),
178 "ws://api.devnet.solana.com/".to_string()
179 );
180
181 assert_eq!(
182 Config::compute_websocket_url("https://api.devnet.solana.com"),
183 "wss://api.devnet.solana.com/".to_string()
184 );
185
186 assert_eq!(
187 Config::compute_websocket_url("http://example.com:8899"),
188 "ws://example.com:8900/".to_string()
189 );
190 assert_eq!(
191 Config::compute_websocket_url("https://example.com:1234"),
192 "wss://example.com:1235/".to_string()
193 );
194
195 assert_eq!(Config::compute_websocket_url("garbage"), String::new());
196 }
197}