2023-02-27 20:03:17 +00:00
|
|
|
#![doc = include_str!("../README.md")]
|
|
|
|
#![deny(unsafe_code, rustdoc::broken_intra_doc_links)]
|
2021-10-04 19:05:11 +00:00
|
|
|
|
2023-02-06 01:32:55 +00:00
|
|
|
use crate::errors::{is_blocked_by_cloudflare_response, is_cloudflare_security_challenge};
|
2022-06-08 10:29:00 +00:00
|
|
|
use contract::ContractMetadata;
|
|
|
|
use errors::EtherscanError;
|
|
|
|
use ethers_core::{
|
|
|
|
abi::{Abi, Address},
|
|
|
|
types::{Chain, H256},
|
|
|
|
};
|
|
|
|
use reqwest::{header, IntoUrl, Url};
|
|
|
|
use serde::{de::DeserializeOwned, Deserialize, Serialize};
|
2022-04-06 02:01:44 +00:00
|
|
|
use std::{
|
|
|
|
borrow::Cow,
|
|
|
|
io::Write,
|
|
|
|
path::PathBuf,
|
|
|
|
time::{Duration, SystemTime, UNIX_EPOCH},
|
|
|
|
};
|
2022-09-14 16:43:10 +00:00
|
|
|
use tracing::{error, trace};
|
2022-09-15 19:44:52 +00:00
|
|
|
|
2022-02-26 14:35:43 +00:00
|
|
|
pub mod account;
|
2021-11-27 07:54:20 +00:00
|
|
|
pub mod contract;
|
|
|
|
pub mod errors;
|
|
|
|
pub mod gas;
|
2022-03-06 15:21:19 +00:00
|
|
|
pub mod source_tree;
|
2021-11-27 07:54:20 +00:00
|
|
|
pub mod transaction;
|
2022-05-09 17:44:32 +00:00
|
|
|
pub mod utils;
|
2022-09-29 15:07:50 +00:00
|
|
|
pub mod verify;
|
2021-10-17 10:01:20 +00:00
|
|
|
|
2021-12-02 00:54:16 +00:00
|
|
|
pub(crate) type Result<T> = std::result::Result<T, EtherscanError>;
|
2021-10-04 19:05:11 +00:00
|
|
|
|
2021-10-17 10:01:20 +00:00
|
|
|
/// The Etherscan.io API client.
|
2021-10-24 18:41:50 +00:00
|
|
|
#[derive(Clone, Debug)]
|
2021-10-04 19:05:11 +00:00
|
|
|
pub struct Client {
|
2021-10-17 10:01:20 +00:00
|
|
|
/// Client that executes HTTP requests
|
2021-10-04 19:05:11 +00:00
|
|
|
client: reqwest::Client,
|
2021-10-17 10:01:20 +00:00
|
|
|
/// Etherscan API key
|
2023-01-22 21:08:33 +00:00
|
|
|
api_key: Option<String>,
|
2022-03-19 17:05:39 +00:00
|
|
|
/// Etherscan API endpoint like <https://api(-chain).etherscan.io/api>
|
2021-10-04 19:05:11 +00:00
|
|
|
etherscan_api_url: Url,
|
2022-03-19 17:05:39 +00:00
|
|
|
/// Etherscan base endpoint like <https://etherscan.io>
|
2021-10-04 19:05:11 +00:00
|
|
|
etherscan_url: Url,
|
2022-04-06 02:01:44 +00:00
|
|
|
/// Path to where ABI files should be cached
|
|
|
|
cache: Option<Cache>,
|
|
|
|
}
|
|
|
|
|
2022-04-29 11:25:52 +00:00
|
|
|
impl Client {
|
|
|
|
/// Creates a `ClientBuilder` to configure a `Client`.
|
2023-02-27 20:14:36 +00:00
|
|
|
///
|
2022-04-29 11:25:52 +00:00
|
|
|
/// This is the same as `ClientBuilder::default()`.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use ethers_core::types::Chain;
|
|
|
|
/// use ethers_etherscan::Client;
|
|
|
|
/// let client = Client::builder().with_api_key("<API KEY>").chain(Chain::Mainnet).unwrap().build().unwrap();
|
|
|
|
/// ```
|
|
|
|
pub fn builder() -> ClientBuilder {
|
|
|
|
ClientBuilder::default()
|
2022-04-06 02:01:44 +00:00
|
|
|
}
|
2021-10-04 19:05:11 +00:00
|
|
|
|
2022-04-29 11:25:52 +00:00
|
|
|
/// Creates a new instance that caches etherscan requests
|
2022-04-06 02:01:44 +00:00
|
|
|
pub fn new_cached(
|
|
|
|
chain: Chain,
|
|
|
|
api_key: impl Into<String>,
|
|
|
|
cache_root: Option<PathBuf>,
|
|
|
|
cache_ttl: Duration,
|
|
|
|
) -> Result<Self> {
|
|
|
|
let mut this = Self::new(chain, api_key)?;
|
|
|
|
this.cache = cache_root.map(|root| Cache::new(root, cache_ttl));
|
|
|
|
Ok(this)
|
|
|
|
}
|
|
|
|
|
2021-10-17 10:01:20 +00:00
|
|
|
/// Create a new client with the correct endpoints based on the chain and provided API key
|
2021-10-24 18:41:50 +00:00
|
|
|
pub fn new(chain: Chain, api_key: impl Into<String>) -> Result<Self> {
|
2022-04-29 11:25:52 +00:00
|
|
|
Client::builder().with_api_key(api_key).chain(chain)?.build()
|
2021-10-17 10:01:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Create a new client with the correct endpoints based on the chain and API key
|
2023-02-27 20:14:36 +00:00
|
|
|
/// from the default environment variable defined in [`Chain`].
|
2021-10-17 10:01:20 +00:00
|
|
|
pub fn new_from_env(chain: Chain) -> Result<Self> {
|
2021-11-22 09:02:28 +00:00
|
|
|
let api_key = match chain {
|
2023-02-27 20:14:36 +00:00
|
|
|
// Extra aliases
|
|
|
|
Chain::Fantom | Chain::FantomTestnet => std::env::var("FMTSCAN_API_KEY")
|
|
|
|
.or_else(|_| std::env::var("FANTOMSCAN_API_KEY"))
|
|
|
|
.map_err(Into::into),
|
|
|
|
|
|
|
|
// Backwards compatibility, ideally these should return an error.
|
2022-06-03 16:16:35 +00:00
|
|
|
Chain::XDai |
|
2022-10-31 16:01:34 +00:00
|
|
|
Chain::Chiado |
|
2022-06-03 16:16:35 +00:00
|
|
|
Chain::Sepolia |
|
|
|
|
Chain::Rsk |
|
|
|
|
Chain::Sokol |
|
|
|
|
Chain::Poa |
|
|
|
|
Chain::Oasis |
|
|
|
|
Chain::Emerald |
|
2022-06-22 17:09:05 +00:00
|
|
|
Chain::EmeraldTestnet |
|
|
|
|
Chain::Evmos |
|
2023-02-27 20:14:36 +00:00
|
|
|
Chain::EvmosTestnet => Ok(String::new()),
|
|
|
|
Chain::AnvilHardhat | Chain::Dev => Err(EtherscanError::LocalNetworksNotSupported),
|
|
|
|
|
|
|
|
_ => chain
|
|
|
|
.etherscan_api_key_name()
|
|
|
|
.ok_or_else(|| EtherscanError::ChainNotSupported(chain))
|
|
|
|
.and_then(|key_name| std::env::var(key_name).map_err(Into::into)),
|
|
|
|
}?;
|
2021-11-22 09:02:28 +00:00
|
|
|
Self::new(chain, api_key)
|
2021-10-04 19:05:11 +00:00
|
|
|
}
|
|
|
|
|
2023-03-01 00:26:27 +00:00
|
|
|
/// Create a new client with the correct endpoints based on the chain and API key
|
|
|
|
/// from the default environment variable defined in [`Chain`].
|
|
|
|
///
|
|
|
|
/// If the environment variable is not set, create a new client without it.
|
|
|
|
pub fn new_from_opt_env(chain: Chain) -> Result<Self> {
|
|
|
|
match Self::new_from_env(chain) {
|
|
|
|
Ok(client) => Ok(client),
|
|
|
|
Err(EtherscanError::EnvVarNotFound(_)) => {
|
|
|
|
Self::builder().chain(chain).and_then(|c| c.build())
|
|
|
|
}
|
|
|
|
Err(e) => Err(e),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-11 23:43:46 +00:00
|
|
|
/// Sets the root to the cache dir and the ttl to use
|
|
|
|
pub fn set_cache(&mut self, root: impl Into<PathBuf>, ttl: Duration) -> &mut Self {
|
|
|
|
self.cache = Some(Cache { root: root.into(), ttl });
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2021-10-04 19:05:11 +00:00
|
|
|
pub fn etherscan_api_url(&self) -> &Url {
|
|
|
|
&self.etherscan_api_url
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn etherscan_url(&self) -> &Url {
|
|
|
|
&self.etherscan_url
|
|
|
|
}
|
|
|
|
|
2021-10-17 10:01:20 +00:00
|
|
|
/// Return the URL for the given block number
|
|
|
|
pub fn block_url(&self, block: u64) -> String {
|
2022-11-07 23:43:11 +00:00
|
|
|
format!("{}block/{block}", self.etherscan_url)
|
2021-10-17 10:01:20 +00:00
|
|
|
}
|
|
|
|
|
2021-10-04 19:05:11 +00:00
|
|
|
/// Return the URL for the given address
|
|
|
|
pub fn address_url(&self, address: Address) -> String {
|
2022-11-07 23:43:11 +00:00
|
|
|
format!("{}address/{address:?}", self.etherscan_url)
|
2021-10-17 10:01:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the URL for the given transaction hash
|
2022-04-10 16:04:43 +00:00
|
|
|
pub fn transaction_url(&self, tx_hash: H256) -> String {
|
2022-11-07 23:43:11 +00:00
|
|
|
format!("{}tx/{tx_hash:?}", self.etherscan_url)
|
2021-10-04 19:05:11 +00:00
|
|
|
}
|
|
|
|
|
2021-10-17 10:01:20 +00:00
|
|
|
/// Return the URL for the given token hash
|
2022-04-10 16:04:43 +00:00
|
|
|
pub fn token_url(&self, token_hash: Address) -> String {
|
2022-11-07 23:43:11 +00:00
|
|
|
format!("{}token/{token_hash:?}", self.etherscan_url)
|
2021-10-17 10:01:20 +00:00
|
|
|
}
|
|
|
|
|
2022-09-29 15:07:50 +00:00
|
|
|
/// Execute an GET request with parameters.
|
|
|
|
async fn get_json<T: DeserializeOwned, Q: Serialize>(&self, query: &Q) -> Result<Response<T>> {
|
|
|
|
let res = self.get(query).await?;
|
|
|
|
self.sanitize_response(res)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Execute a GET request with parameters, without sanity checking the response.
|
|
|
|
async fn get<Q: Serialize>(&self, query: &Q) -> Result<String> {
|
|
|
|
trace!(target: "etherscan", "GET {}", self.etherscan_api_url);
|
2022-09-14 16:43:10 +00:00
|
|
|
let response = self
|
2021-10-04 19:05:11 +00:00
|
|
|
.client
|
2022-09-29 15:07:50 +00:00
|
|
|
.get(self.etherscan_api_url.clone())
|
|
|
|
.header(header::ACCEPT, "application/json")
|
|
|
|
.query(query)
|
2021-10-04 19:05:11 +00:00
|
|
|
.send()
|
|
|
|
.await?
|
2022-09-14 16:43:10 +00:00
|
|
|
.text()
|
|
|
|
.await?;
|
2022-09-29 15:07:50 +00:00
|
|
|
Ok(response)
|
|
|
|
}
|
2022-09-14 16:43:10 +00:00
|
|
|
|
2022-09-29 15:07:50 +00:00
|
|
|
/// Execute a POST request with a form.
|
|
|
|
async fn post_form<T: DeserializeOwned, F: Serialize>(&self, form: &F) -> Result<Response<T>> {
|
|
|
|
let res = self.post(form).await?;
|
|
|
|
self.sanitize_response(res)
|
2021-10-04 19:05:11 +00:00
|
|
|
}
|
|
|
|
|
2022-09-29 15:07:50 +00:00
|
|
|
/// Execute a POST request with a form, without sanity checking the response.
|
|
|
|
async fn post<F: Serialize>(&self, form: &F) -> Result<String> {
|
|
|
|
trace!(target: "etherscan", "POST {}", self.etherscan_api_url);
|
2022-09-14 16:43:10 +00:00
|
|
|
let response = self
|
2021-10-04 19:05:11 +00:00
|
|
|
.client
|
2022-09-29 15:07:50 +00:00
|
|
|
.post(self.etherscan_api_url.clone())
|
|
|
|
.form(form)
|
2021-10-04 19:05:11 +00:00
|
|
|
.send()
|
|
|
|
.await?
|
2022-09-14 16:43:10 +00:00
|
|
|
.text()
|
2022-04-06 02:01:44 +00:00
|
|
|
.await?;
|
2022-09-29 15:07:50 +00:00
|
|
|
Ok(response)
|
|
|
|
}
|
2022-04-06 02:01:44 +00:00
|
|
|
|
2022-09-29 15:07:50 +00:00
|
|
|
/// Perform sanity checks on a response and deserialize it into a [Response].
|
|
|
|
fn sanitize_response<T: DeserializeOwned>(&self, res: impl AsRef<str>) -> Result<Response<T>> {
|
|
|
|
let res = res.as_ref();
|
|
|
|
let res: ResponseData<T> = serde_json::from_str(res).map_err(|err| {
|
|
|
|
error!(target: "etherscan", ?res, "Failed to deserialize response: {}", err);
|
2023-02-10 19:51:13 +00:00
|
|
|
if res == "Page not found" {
|
|
|
|
EtherscanError::PageNotFound
|
|
|
|
} else if is_blocked_by_cloudflare_response(res) {
|
2022-09-15 19:44:52 +00:00
|
|
|
EtherscanError::BlockedByCloudflare
|
2023-02-06 01:32:55 +00:00
|
|
|
} else if is_cloudflare_security_challenge(res) {
|
|
|
|
EtherscanError::CloudFlareSecurityChallenge
|
2022-09-15 19:44:52 +00:00
|
|
|
} else {
|
|
|
|
EtherscanError::Serde(err)
|
|
|
|
}
|
2022-09-14 16:43:10 +00:00
|
|
|
})?;
|
|
|
|
|
2022-09-29 15:07:50 +00:00
|
|
|
match res {
|
2023-03-13 19:43:17 +00:00
|
|
|
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)
|
|
|
|
}
|
2022-04-06 02:01:44 +00:00
|
|
|
}
|
2023-03-13 19:43:17 +00:00
|
|
|
Err(EtherscanError::ErrorResponse { status, message, result })
|
2022-04-06 02:01:44 +00:00
|
|
|
}
|
|
|
|
ResponseData::Success(res) => Ok(res),
|
|
|
|
}
|
2021-10-04 19:05:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn create_query<T: Serialize>(
|
|
|
|
&self,
|
|
|
|
module: &'static str,
|
|
|
|
action: &'static str,
|
|
|
|
other: T,
|
|
|
|
) -> Query<T> {
|
|
|
|
Query {
|
2023-01-22 21:08:33 +00:00
|
|
|
apikey: self.api_key.as_deref().map(Cow::Borrowed),
|
2021-10-04 19:05:11 +00:00
|
|
|
module: Cow::Borrowed(module),
|
|
|
|
action: Cow::Borrowed(action),
|
|
|
|
other,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-29 11:25:52 +00:00
|
|
|
#[derive(Clone, Debug, Default)]
|
|
|
|
pub struct ClientBuilder {
|
|
|
|
/// Client that executes HTTP requests
|
|
|
|
client: Option<reqwest::Client>,
|
|
|
|
/// Etherscan API key
|
|
|
|
api_key: Option<String>,
|
|
|
|
/// Etherscan API endpoint like <https://api(-chain).etherscan.io/api>
|
|
|
|
etherscan_api_url: Option<Url>,
|
|
|
|
/// Etherscan base endpoint like <https://etherscan.io>
|
|
|
|
etherscan_url: Option<Url>,
|
|
|
|
/// Path to where ABI files should be cached
|
|
|
|
cache: Option<Cache>,
|
|
|
|
}
|
|
|
|
|
|
|
|
// === impl ClientBuilder ===
|
|
|
|
|
|
|
|
impl ClientBuilder {
|
|
|
|
/// Configures the etherscan url and api url for the given chain
|
|
|
|
///
|
|
|
|
/// # Errors
|
|
|
|
///
|
|
|
|
/// Fails if the chain is not supported by etherscan
|
|
|
|
pub fn chain(self, chain: Chain) -> Result<Self> {
|
|
|
|
fn urls(
|
|
|
|
api: impl IntoUrl,
|
|
|
|
url: impl IntoUrl,
|
|
|
|
) -> (reqwest::Result<Url>, reqwest::Result<Url>) {
|
|
|
|
(api.into_url(), url.into_url())
|
|
|
|
}
|
2022-08-09 21:50:18 +00:00
|
|
|
let (etherscan_api_url, etherscan_url) = chain
|
|
|
|
.etherscan_urls()
|
|
|
|
.map(|(api, base)| urls(api, base))
|
2022-10-11 17:49:05 +00:00
|
|
|
.ok_or_else(|| EtherscanError::ChainNotSupported(chain))?;
|
2022-04-29 11:25:52 +00:00
|
|
|
self.with_api_url(etherscan_api_url?)?.with_url(etherscan_url?)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Configures the etherscan url
|
|
|
|
///
|
|
|
|
/// # Errors
|
|
|
|
///
|
|
|
|
/// Fails if the `etherscan_url` is not a valid `Url`
|
|
|
|
pub fn with_url(mut self, etherscan_url: impl IntoUrl) -> Result<Self> {
|
2023-01-22 21:08:17 +00:00
|
|
|
self.etherscan_url = Some(ensure_url(etherscan_url)?);
|
2022-04-29 11:25:52 +00:00
|
|
|
Ok(self)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Configures the `reqwest::Client`
|
|
|
|
pub fn with_client(mut self, client: reqwest::Client) -> Self {
|
|
|
|
self.client = Some(client);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Configures the etherscan api url
|
|
|
|
///
|
|
|
|
/// # Errors
|
|
|
|
///
|
|
|
|
/// 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> {
|
2023-01-22 21:08:17 +00:00
|
|
|
self.etherscan_api_url = Some(ensure_url(etherscan_api_url)?);
|
2022-04-29 11:25:52 +00:00
|
|
|
Ok(self)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Configures the etherscan api key
|
|
|
|
pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
|
2023-01-22 21:08:33 +00:00
|
|
|
self.api_key = Some(api_key.into()).filter(|s| !s.is_empty());
|
2022-04-29 11:25:52 +00:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Configures cache for etherscan request
|
|
|
|
pub fn with_cache(mut self, cache_root: Option<PathBuf>, cache_ttl: Duration) -> Self {
|
|
|
|
self.cache = cache_root.map(|root| Cache::new(root, cache_ttl));
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a Client that uses this ClientBuilder configuration.
|
|
|
|
///
|
|
|
|
/// # Errors
|
2023-03-01 00:26:27 +00:00
|
|
|
///
|
|
|
|
/// If the following required fields are missing:
|
2022-04-29 11:25:52 +00:00
|
|
|
/// - `etherscan_api_url`
|
|
|
|
/// - `etherscan_url`
|
|
|
|
pub fn build(self) -> Result<Client> {
|
|
|
|
let ClientBuilder { client, api_key, etherscan_api_url, etherscan_url, cache } = self;
|
|
|
|
|
|
|
|
let client = Client {
|
|
|
|
client: client.unwrap_or_default(),
|
2023-01-22 21:08:33 +00:00
|
|
|
api_key,
|
2022-04-29 11:25:52 +00:00
|
|
|
etherscan_api_url: etherscan_api_url
|
|
|
|
.ok_or_else(|| EtherscanError::Builder("etherscan api url".to_string()))?,
|
|
|
|
etherscan_url: etherscan_url
|
|
|
|
.ok_or_else(|| EtherscanError::Builder("etherscan url".to_string()))?,
|
|
|
|
cache,
|
|
|
|
};
|
|
|
|
Ok(client)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A wrapper around an Etherscan cache object with an expiry
|
|
|
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
|
|
|
struct CacheEnvelope<T> {
|
|
|
|
expiry: u64,
|
|
|
|
data: T,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Simple cache for etherscan requests
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
struct Cache {
|
|
|
|
root: PathBuf,
|
|
|
|
ttl: Duration,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Cache {
|
|
|
|
fn new(root: PathBuf, ttl: Duration) -> Self {
|
|
|
|
Self { root, ttl }
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_abi(&self, address: Address) -> Option<Option<ethers_core::abi::Abi>> {
|
|
|
|
self.get("abi", address)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn set_abi(&self, address: Address, abi: Option<&Abi>) {
|
|
|
|
self.set("abi", address, abi)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_source(&self, address: Address) -> Option<Option<ContractMetadata>> {
|
|
|
|
self.get("sources", address)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn set_source(&self, address: Address, source: Option<&ContractMetadata>) {
|
|
|
|
self.set("sources", address, source)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn set<T: Serialize>(&self, prefix: &str, address: Address, item: T) {
|
2022-11-07 23:43:11 +00:00
|
|
|
let path = self.root.join(prefix).join(format!("{address:?}.json"));
|
2022-04-29 11:25:52 +00:00
|
|
|
let writer = std::fs::File::create(path).ok().map(std::io::BufWriter::new);
|
|
|
|
if let Some(mut writer) = writer {
|
|
|
|
let _ = serde_json::to_writer(
|
|
|
|
&mut writer,
|
|
|
|
&CacheEnvelope {
|
|
|
|
expiry: SystemTime::now()
|
|
|
|
.checked_add(self.ttl)
|
|
|
|
.expect("cache ttl overflowed")
|
|
|
|
.duration_since(UNIX_EPOCH)
|
|
|
|
.expect("system time is before unix epoch")
|
|
|
|
.as_secs(),
|
|
|
|
data: item,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
let _ = writer.flush();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get<T: DeserializeOwned>(&self, prefix: &str, address: Address) -> Option<T> {
|
2022-11-07 23:43:11 +00:00
|
|
|
let path = self.root.join(prefix).join(format!("{address:?}.json"));
|
2022-04-29 11:25:52 +00:00
|
|
|
let reader = std::io::BufReader::new(std::fs::File::open(path).ok()?);
|
|
|
|
if let Ok(inner) = serde_json::from_reader::<_, CacheEnvelope<T>>(reader) {
|
|
|
|
// If this does not return None then we have passed the expiry
|
|
|
|
if SystemTime::now()
|
|
|
|
.duration_since(UNIX_EPOCH)
|
|
|
|
.expect("system time is before unix epoch")
|
|
|
|
.checked_sub(Duration::from_secs(inner.expiry))
|
|
|
|
.is_some()
|
|
|
|
{
|
|
|
|
return None
|
|
|
|
}
|
|
|
|
|
|
|
|
return Some(inner.data)
|
|
|
|
}
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-04 19:05:11 +00:00
|
|
|
/// The API response type
|
|
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
|
|
pub struct Response<T> {
|
|
|
|
pub status: String,
|
|
|
|
pub message: String,
|
|
|
|
pub result: T,
|
|
|
|
}
|
|
|
|
|
2022-04-06 02:01:44 +00:00
|
|
|
#[derive(Deserialize, Debug, Clone)]
|
|
|
|
#[serde(untagged)]
|
|
|
|
pub enum ResponseData<T> {
|
|
|
|
Success(Response<T>),
|
2023-03-13 19:43:17 +00:00
|
|
|
Error { status: String, message: String, result: Option<String> },
|
2022-04-06 02:01:44 +00:00
|
|
|
}
|
|
|
|
|
2021-10-04 19:05:11 +00:00
|
|
|
/// The type that gets serialized as query
|
2022-08-24 19:50:29 +00:00
|
|
|
#[derive(Clone, Debug, Serialize)]
|
2021-10-04 19:05:11 +00:00
|
|
|
struct Query<'a, T: Serialize> {
|
2023-01-22 21:08:33 +00:00
|
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
|
|
apikey: Option<Cow<'a, str>>,
|
2021-10-04 19:05:11 +00:00
|
|
|
module: Cow<'a, str>,
|
|
|
|
action: Cow<'a, str>,
|
|
|
|
#[serde(flatten)]
|
|
|
|
other: T,
|
|
|
|
}
|
2021-10-24 18:41:50 +00:00
|
|
|
|
2023-01-22 21:08:17 +00:00
|
|
|
/// 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()
|
|
|
|
}
|
|
|
|
|
2021-10-24 18:41:50 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2023-03-13 19:43:17 +00:00
|
|
|
use crate::{Client, EtherscanError, ResponseData};
|
2022-04-23 08:42:12 +00:00
|
|
|
use ethers_core::types::{Address, Chain, H256};
|
2021-11-27 07:54:20 +00:00
|
|
|
|
2023-03-13 19:43:17 +00:00
|
|
|
// <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 { .. }));
|
|
|
|
}
|
|
|
|
|
2023-01-22 21:08:17 +00:00
|
|
|
#[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");
|
|
|
|
}
|
|
|
|
|
2022-03-31 23:42:31 +00:00
|
|
|
#[test]
|
|
|
|
fn stringifies_block_url() {
|
2023-03-01 00:26:27 +00:00
|
|
|
let etherscan = Client::new(Chain::Mainnet, "").unwrap();
|
2022-03-31 23:42:31 +00:00
|
|
|
let block: u64 = 1;
|
|
|
|
let block_url: String = etherscan.block_url(block);
|
2022-11-07 23:43:11 +00:00
|
|
|
assert_eq!(block_url, format!("https://etherscan.io/block/{block}"));
|
2022-03-31 23:42:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn stringifies_address_url() {
|
2023-03-01 00:26:27 +00:00
|
|
|
let etherscan = Client::new(Chain::Mainnet, "").unwrap();
|
2022-03-31 23:42:31 +00:00
|
|
|
let addr: Address = Address::zero();
|
|
|
|
let address_url: String = etherscan.address_url(addr);
|
2022-11-07 23:43:11 +00:00
|
|
|
assert_eq!(address_url, format!("https://etherscan.io/address/{addr:?}"));
|
2022-03-31 23:42:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn stringifies_transaction_url() {
|
2023-03-01 00:26:27 +00:00
|
|
|
let etherscan = Client::new(Chain::Mainnet, "").unwrap();
|
2022-04-10 16:04:43 +00:00
|
|
|
let tx_hash = H256::zero();
|
2022-03-31 23:42:31 +00:00
|
|
|
let tx_url: String = etherscan.transaction_url(tx_hash);
|
2022-11-07 23:43:11 +00:00
|
|
|
assert_eq!(tx_url, format!("https://etherscan.io/tx/{tx_hash:?}"));
|
2022-03-31 23:42:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn stringifies_token_url() {
|
2023-03-01 00:26:27 +00:00
|
|
|
let etherscan = Client::new(Chain::Mainnet, "").unwrap();
|
2022-04-10 16:04:43 +00:00
|
|
|
let token_hash = Address::zero();
|
2022-03-31 23:42:31 +00:00
|
|
|
let token_url: String = etherscan.token_url(token_hash);
|
2022-11-07 23:43:11 +00:00
|
|
|
assert_eq!(token_url, format!("https://etherscan.io/token/{token_hash:?}"));
|
2022-03-31 23:42:31 +00:00
|
|
|
}
|
|
|
|
|
2022-03-30 18:20:23 +00:00
|
|
|
#[test]
|
|
|
|
fn local_networks_not_supported() {
|
|
|
|
let err = Client::new_from_env(Chain::Dev).unwrap_err();
|
|
|
|
assert!(matches!(err, EtherscanError::LocalNetworksNotSupported));
|
|
|
|
}
|
2021-10-24 18:41:50 +00:00
|
|
|
}
|