Skip to content

Commit

Permalink
fix(etherscan): support null result (#2249)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattsse committed Mar 13, 2023
1 parent 7ae2ed1 commit 862d923
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
2 changes: 2 additions & 0 deletions ethers-etherscan/src/errors.rs
Expand Up @@ -29,6 +29,8 @@ pub enum EtherscanError {
IO(#[from] std::io::Error),
#[error("Local networks (e.g. anvil, ganache, geth --dev) cannot be indexed by etherscan")]
LocalNetworksNotSupported,
#[error("Received error response: status={status},message={message}, result={result:?}")]
ErrorResponse { status: String, message: String, result: Option<String> },
#[error("Unknown error: {0}")]
Unknown(String),
#[error("Missing field: {0}")]
Expand Down
27 changes: 18 additions & 9 deletions ethers-etherscan/src/lib.rs
Expand Up @@ -214,14 +214,15 @@ impl Client {
})?;

match res {
ResponseData::Error { result, .. } => {
if result.starts_with("Max rate limit reached") {
Err(EtherscanError::RateLimitExceeded)
} else if result.to_lowercase() == "invalid api key" {
Err(EtherscanError::InvalidApiKey)
} else {
Err(EtherscanError::Unknown(result))
ResponseData::Error { result, message, status } => {
if let Some(ref result) = result {
if result.starts_with("Max rate limit reached") {
return Err(EtherscanError::RateLimitExceeded)
} else if result.to_lowercase() == "invalid api key" {
return Err(EtherscanError::InvalidApiKey)
}
}
Err(EtherscanError::ErrorResponse { status, message, result })
}
ResponseData::Success(res) => Ok(res),
}
Expand Down Expand Up @@ -426,7 +427,7 @@ pub struct Response<T> {
#[serde(untagged)]
pub enum ResponseData<T> {
Success(Response<T>),
Error { status: String, message: String, result: String },
Error { status: String, message: String, result: Option<String> },
}

/// The type that gets serialized as query
Expand Down Expand Up @@ -461,9 +462,17 @@ fn into_url(url: impl IntoUrl) -> std::result::Result<Url, reqwest::Error> {

#[cfg(test)]
mod tests {
use crate::{Client, EtherscanError};
use crate::{Client, EtherscanError, ResponseData};
use ethers_core::types::{Address, Chain, H256};

// <https://github.com/foundry-rs/foundry/issues/4406>
#[test]
fn can_parse_block_scout_err() {
let err = "{\"message\":\"Something went wrong.\",\"result\":null,\"status\":\"0\"}";
let resp: ResponseData<Address> = serde_json::from_str(err).unwrap();
assert!(matches!(resp, ResponseData::Error { .. }));
}

#[test]
fn test_api_paths() {
let client = Client::new(Chain::Goerli, "").unwrap();
Expand Down

0 comments on commit 862d923

Please sign in to comment.