Skip to content

Commit

Permalink
client: derive cluster ws url like web3.js
Browse files Browse the repository at this point in the history
This fixes two issues with `Cluster`'s `FromStr` implementation, namely:

  * url being lowercased
  * websocket port defaulting to 8900

The implementation has been changed to match that of the official
`web3.js` library.

See https://github.com/solana-labs/solana/blob/aea8f0df1610248d29d8ca3bc0d60e9fabc99e31/web3.js/src/util/url.ts.
  • Loading branch information
cherryman committed Jan 27, 2022
1 parent d8d7200 commit a62bf4c
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions client/src/cluster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,16 @@ impl FromStr for Cluster {
"d" | "devnet" => Ok(Cluster::Devnet),
"l" | "localnet" => Ok(Cluster::Localnet),
"g" | "debug" => Ok(Cluster::Debug),
url if url.contains("http") => {
let http_url = url;
_ if s.starts_with("http") => {
let http_url = s;

// Taken from:
// https://github.com/solana-labs/solana/blob/aea8f0df1610248d29d8ca3bc0d60e9fabc99e31/web3.js/src/util/url.ts

// Websocket port is always +1 the http port.
let mut ws_url = Url::parse(http_url)?;
if let Some(port) = ws_url.port() {
ws_url.set_port(Some(port + 1))
.map_err(|_| anyhow!("Unable to set port"))?;
} else {
ws_url.set_port(Some(8900))
.map_err(|_| anyhow!("Unable to set port"))?;
}
if ws_url.scheme() == "https" {
ws_url.set_scheme("wss")
Expand Down Expand Up @@ -134,7 +133,7 @@ mod tests {
let url = "http://my-url.com/";
let cluster = Cluster::from_str(url).unwrap();
assert_eq!(
Cluster::Custom(url.to_string(), "ws://my-url.com:8900/".to_string()),
Cluster::Custom(url.to_string(), "ws://my-url.com/".to_string()),
cluster
);
}
Expand All @@ -153,7 +152,17 @@ mod tests {
let url = "https://my-url.com/";
let cluster = Cluster::from_str(url).unwrap();
assert_eq!(
Cluster::Custom(url.to_string(), "wss://my-url.com:8900/".to_string()),
Cluster::Custom(url.to_string(), "wss://my-url.com/".to_string()),
cluster
);
}

#[test]
fn test_upper_case() {
let url = "http://my-url.com/FooBar";
let cluster = Cluster::from_str(url).unwrap();
assert_eq!(
Cluster::Custom(url.to_string(), "ws://my-url.com/FooBar".to_string()),
cluster
);
}
Expand Down

0 comments on commit a62bf4c

Please sign in to comment.