Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ensure urls have trailing / #2069

Merged
merged 2 commits into from Jan 22, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 29 additions & 2 deletions ethers-etherscan/src/lib.rs
Expand Up @@ -285,7 +285,7 @@ impl ClientBuilder {
///
/// Fails if the `etherscan_url` is not a valid `Url`
pub fn with_url(mut self, etherscan_url: impl IntoUrl) -> Result<Self> {
self.etherscan_url = Some(etherscan_url.into_url()?);
self.etherscan_url = Some(ensure_url(etherscan_url)?);
Ok(self)
}

Expand All @@ -301,7 +301,7 @@ impl ClientBuilder {
///
/// Fails if the `etherscan_api_url` is not a valid `Url`
pub fn with_api_url(mut self, etherscan_api_url: impl IntoUrl) -> Result<Self> {
self.etherscan_api_url = Some(etherscan_api_url.into_url()?);
self.etherscan_api_url = Some(ensure_url(etherscan_api_url)?);
Ok(self)
}

Expand Down Expand Up @@ -441,6 +441,25 @@ struct Query<'a, T: Serialize> {
other: T,
}

/// Ensures that the url is well formatted to be used by the Client's functions that join paths.
fn ensure_url(url: impl IntoUrl) -> std::result::Result<Url, reqwest::Error> {
let url_str = url.as_str();

// ensure URL ends with `/`
if url_str.ends_with('/') {
url.into_url()
} else {
into_url(format!("{url_str}/"))
}
}

/// This is a hack to work around `IntoUrl`'s sealed private functions, which can't be called
/// normally.
#[inline]
fn into_url(url: impl IntoUrl) -> std::result::Result<Url, reqwest::Error> {
url.into_url()
}

#[cfg(test)]
mod tests {
use crate::{Client, EtherscanError};
Expand All @@ -450,6 +469,14 @@ mod tests {
time::{Duration, SystemTime},
};

#[test]
fn test_api_paths() {
let client = Client::new(Chain::Goerli, "").unwrap();
assert_eq!(client.etherscan_api_url.as_str(), "https://api-goerli.etherscan.io/api/");

assert_eq!(client.block_url(100), "https://goerli.etherscan.io/block/100");
}

#[test]
fn chain_not_supported() {
let err = Client::new_from_env(Chain::Morden).unwrap_err();
Expand Down