Skip to main content

foundry_config/
etherscan.rs

1//! Support for multiple Etherscan keys.
2
3use crate::{
4    Chain, Config, NamedChain,
5    resolve::{RE_PLACEHOLDER, UnresolvedEnvVarError, interpolate},
6};
7use alloy_primitives::keccak256;
8use figment::{
9    Error, Metadata, Profile, Provider,
10    providers::Env,
11    value::{Dict, Map},
12};
13use heck::ToKebabCase;
14use serde::{Deserialize, Deserializer, Serialize, Serializer};
15use std::{
16    collections::BTreeMap,
17    fmt,
18    ops::{Deref, DerefMut},
19    path::PathBuf,
20    time::Duration,
21};
22
23/// A [Provider] that provides Etherscan API key from the environment if it's not empty.
24///
25/// This prevents `ETHERSCAN_API_KEY=""` if it's set but empty
26#[derive(Debug, Clone, PartialEq, Eq, Default)]
27#[non_exhaustive]
28pub(crate) struct EtherscanEnvProvider;
29
30impl Provider for EtherscanEnvProvider {
31    fn metadata(&self) -> Metadata {
32        Env::raw().metadata()
33    }
34
35    fn data(&self) -> Result<Map<Profile, Dict>, Error> {
36        let mut dict = Dict::default();
37        let env_provider = Env::raw().only(&["ETHERSCAN_API_KEY"]);
38        if let Some((key, value)) = env_provider.iter().next()
39            && !value.trim().is_empty()
40        {
41            dict.insert(key.as_str().to_string(), value.into());
42        }
43
44        Ok(Map::from([(Config::selected_profile(), dict)]))
45    }
46}
47
48/// Errors that can occur when creating an `EtherscanConfig`
49#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
50pub enum EtherscanConfigError {
51    #[error(transparent)]
52    Unresolved(#[from] UnresolvedEnvVarError),
53
54    #[error(
55        "No known Etherscan API URL for chain `{1}`. To fix this, please:\n\
56        1. Specify a `url` {0}\n\
57        2. Verify the chain `{1}` is correct"
58    )]
59    UnknownChain(String, Chain),
60
61    #[error("At least one of `url` or `chain` must be present{0}")]
62    MissingUrlOrChain(String),
63}
64
65/// Container type for Etherscan API keys and URLs.
66#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(transparent)]
68pub struct EtherscanConfigs {
69    configs: BTreeMap<String, EtherscanConfig>,
70}
71
72impl EtherscanConfigs {
73    /// Creates a new list of etherscan configs
74    pub fn new(configs: impl IntoIterator<Item = (impl Into<String>, EtherscanConfig)>) -> Self {
75        Self { configs: configs.into_iter().map(|(name, config)| (name.into(), config)).collect() }
76    }
77
78    /// Returns `true` if this type doesn't contain any configs
79    pub fn is_empty(&self) -> bool {
80        self.configs.is_empty()
81    }
82
83    /// Returns the first config that matches the chain
84    pub fn find_chain(&self, chain: Chain) -> Option<&EtherscanConfig> {
85        self.configs.values().find(|config| config.chain == Some(chain))
86    }
87
88    /// Picks the explorer config to use, given the settings that select between the entries.
89    ///
90    /// `alias` names an entry outright and wins if it matches one. Otherwise the first entry whose
91    /// chain id matches `chain` is used, with `api_key` — which usually comes from an env var or a
92    /// CLI flag — overriding the key that entry carries. With no matching entry, `api_key` alone is
93    /// enough to build a config for `chain`.
94    ///
95    /// Shared by [`Config::get_etherscan_config_with_chain`] and by consumers that keep only a
96    /// snapshot of the config and resolve later, against a chain they don't learn until runtime.
97    pub fn resolve_for(
98        &self,
99        alias: Option<&str>,
100        api_key: Option<&str>,
101        chain: Option<Chain>,
102    ) -> Result<Option<ResolvedEtherscanConfig>, EtherscanConfigError> {
103        if let Some(alias) = alias
104            && self.contains_key(alias)
105        {
106            return self.clone().resolved().remove(alias).transpose();
107        }
108
109        if let Some(res) = chain.and_then(|chain| self.clone().resolved().find_chain(chain)) {
110            match (res, api_key) {
111                (Ok(mut config), Some(key)) => {
112                    config.key = key.to_string();
113                    return Ok(Some(config));
114                }
115                (Ok(config), None) => return Ok(Some(config)),
116                (Err(err), None) => return Err(err),
117                // Unresolvable entry, but there is a key to fall back on.
118                (Err(_), Some(_)) => {}
119            }
120        }
121
122        if let Some(key) = api_key {
123            return Ok(ResolvedEtherscanConfig::create(key, chain.unwrap_or_default()));
124        }
125        Ok(None)
126    }
127
128    /// Returns all (alias -> url) pairs
129    pub fn resolved(self) -> ResolvedEtherscanConfigs {
130        ResolvedEtherscanConfigs {
131            configs: self
132                .configs
133                .into_iter()
134                .map(|(name, e)| {
135                    let resolved = e.resolve(Some(&name));
136                    (name, resolved)
137                })
138                .collect(),
139        }
140    }
141}
142
143impl Deref for EtherscanConfigs {
144    type Target = BTreeMap<String, EtherscanConfig>;
145
146    fn deref(&self) -> &Self::Target {
147        &self.configs
148    }
149}
150
151impl DerefMut for EtherscanConfigs {
152    fn deref_mut(&mut self) -> &mut Self::Target {
153        &mut self.configs
154    }
155}
156
157/// Container type for _resolved_ etherscan keys, see [`EtherscanConfigs::resolved`].
158#[derive(Clone, Debug, Default, PartialEq, Eq)]
159pub struct ResolvedEtherscanConfigs {
160    /// contains all named `ResolvedEtherscanConfig` or an error if we failed to resolve the env
161    /// var alias
162    configs: BTreeMap<String, Result<ResolvedEtherscanConfig, EtherscanConfigError>>,
163}
164
165impl ResolvedEtherscanConfigs {
166    /// Creates a new list of resolved etherscan configs
167    pub fn new(
168        configs: impl IntoIterator<Item = (impl Into<String>, ResolvedEtherscanConfig)>,
169    ) -> Self {
170        Self {
171            configs: configs.into_iter().map(|(name, config)| (name.into(), Ok(config))).collect(),
172        }
173    }
174
175    /// Returns the first config that matches the chain
176    pub fn find_chain(
177        self,
178        chain: Chain,
179    ) -> Option<Result<ResolvedEtherscanConfig, EtherscanConfigError>> {
180        for (_, config) in self.configs {
181            match config {
182                Ok(c) if c.chain == Some(chain) => return Some(Ok(c)),
183                Err(e) => return Some(Err(e)),
184                _ => {}
185            }
186        }
187        None
188    }
189
190    /// Returns true if there's a config that couldn't be resolved
191    pub fn has_unresolved(&self) -> bool {
192        self.configs.values().any(|val| val.is_err())
193    }
194}
195
196impl Deref for ResolvedEtherscanConfigs {
197    type Target = BTreeMap<String, Result<ResolvedEtherscanConfig, EtherscanConfigError>>;
198
199    fn deref(&self) -> &Self::Target {
200        &self.configs
201    }
202}
203
204impl DerefMut for ResolvedEtherscanConfigs {
205    fn deref_mut(&mut self) -> &mut Self::Target {
206        &mut self.configs
207    }
208}
209
210/// Represents all info required to create an etherscan client
211#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
212pub struct EtherscanConfig {
213    /// The chain name or EIP-155 chain ID used to derive the API URL.
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub chain: Option<Chain>,
216    /// Etherscan API URL
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub url: Option<String>,
219    /// The etherscan API KEY that's required to make requests
220    pub key: EtherscanApiKey,
221}
222
223impl EtherscanConfig {
224    /// Returns the etherscan config required to create a client.
225    ///
226    /// # Errors
227    ///
228    /// Returns an error if the type holds a reference to an env var and the env var is not set or
229    /// no chain or url is configured
230    pub fn resolve(
231        self,
232        alias: Option<&str>,
233    ) -> Result<ResolvedEtherscanConfig, EtherscanConfigError> {
234        let Self { chain, mut url, key } = self;
235
236        if let Some(url) = &mut url {
237            *url = interpolate(url)?;
238        }
239
240        let (chain, alias) = match (chain, alias) {
241            // fill one with the other
242            (Some(chain), None) => (Some(chain), Some(chain.to_string())),
243            (None, Some(alias)) => {
244                // alloy chain is parsed as kebab case
245                (
246                    alias.to_kebab_case().parse().ok().or_else(|| {
247                        // if this didn't work try to parse as json because the deserialize impl
248                        // supports more aliases
249                        serde_json::from_str::<NamedChain>(&format!("\"{alias}\""))
250                            .map(Into::into)
251                            .ok()
252                    }),
253                    Some(alias.into()),
254                )
255            }
256            // leave as is
257            (Some(chain), Some(alias)) => (Some(chain), Some(alias.into())),
258            (None, None) => (None, None),
259        };
260        let key = key.resolve()?;
261
262        match (chain, url) {
263            (Some(chain), Some(api_url)) => Ok(ResolvedEtherscanConfig {
264                api_url,
265                browser_url: chain.etherscan_urls().map(|(_, url)| url.to_string()),
266                key,
267                chain: Some(chain),
268            }),
269            (Some(chain), None) => ResolvedEtherscanConfig::create(key, chain).ok_or_else(|| {
270                let msg = alias.map(|a| format!("for `{a}`")).unwrap_or_default();
271                EtherscanConfigError::UnknownChain(msg, chain)
272            }),
273            (None, Some(api_url)) => {
274                Ok(ResolvedEtherscanConfig { api_url, browser_url: None, key, chain: None })
275            }
276            (None, None) => {
277                let msg = alias
278                    .map(|a| format!(" for Etherscan config with unknown alias `{a}`"))
279                    .unwrap_or_default();
280                Err(EtherscanConfigError::MissingUrlOrChain(msg))
281            }
282        }
283    }
284}
285
286/// Contains required url + api key to set up an etherscan client
287#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
288pub struct ResolvedEtherscanConfig {
289    /// Etherscan API URL.
290    #[serde(rename = "url")]
291    pub api_url: String,
292    /// Optional browser URL.
293    #[serde(default, skip_serializing_if = "Option::is_none")]
294    pub browser_url: Option<String>,
295    /// The resolved API key.
296    pub key: String,
297    /// The chain name or EIP-155 chain ID.
298    #[serde(default, skip_serializing_if = "Option::is_none")]
299    pub chain: Option<Chain>,
300}
301
302impl ResolvedEtherscanConfig {
303    /// Creates a new instance using the api key and chain
304    pub fn create(api_key: impl Into<String>, chain: impl Into<Chain>) -> Option<Self> {
305        let chain = chain.into();
306        let (api_url, browser_url) = chain.etherscan_urls()?;
307        Some(Self {
308            api_url: api_url.to_string(),
309            browser_url: Some(browser_url.to_string()),
310            key: api_key.into(),
311            chain: Some(chain),
312        })
313    }
314
315    /// Sets the chain value and consumes the type
316    ///
317    /// This is only used to set derive the appropriate Cache path for the etherscan client
318    pub fn with_chain(mut self, chain: impl Into<Chain>) -> Self {
319        self.set_chain(chain);
320        self
321    }
322
323    /// Sets the chain value
324    pub fn set_chain(&mut self, chain: impl Into<Chain>) -> &mut Self {
325        let chain = chain.into();
326        if let Some((api, browser)) = chain.etherscan_urls() {
327            self.api_url = api.to_string();
328            self.browser_url = Some(browser.to_string());
329        }
330        self.chain = Some(chain);
331        self
332    }
333
334    /// Returns the corresponding `foundry_block_explorers::Client`, configured with the `api_url`,
335    /// `api_key` and cache.
336    ///
337    /// Responses are cached for 24 hours using the cache directory for this chain or endpoint.
338    pub fn into_client(
339        self,
340    ) -> Result<foundry_block_explorers::Client, foundry_block_explorers::errors::EtherscanError>
341    {
342        self.into_client_with_no_proxy(false)
343    }
344
345    /// Same as [`Self::into_client`] but optionally disables automatic proxy detection.
346    ///
347    /// When `no_proxy` is `true`, calls [`foundry_block_explorers::ClientBuilder::no_proxy`],
348    /// which prevents system proxy lookups that can crash in sandboxed environments (e.g.,
349    /// Cursor IDE, macOS App Sandbox).
350    /// See: <https://github.com/foundry-rs/foundry/issues/12733>
351    pub fn into_client_with_no_proxy(
352        self,
353        no_proxy: bool,
354    ) -> Result<foundry_block_explorers::Client, foundry_block_explorers::errors::EtherscanError>
355    {
356        let cache = self.explorer_cache_dir();
357        let Self { api_url, browser_url, key: api_key, .. } = self;
358
359        if let Some(cache_path) = &cache {
360            // we also create the `sources` sub dir here
361            if let Err(err) = std::fs::create_dir_all(cache_path.join("sources")) {
362                warn!("could not create etherscan cache dir: {:?}", err);
363            }
364        }
365
366        // Disable automatic proxy detection. In sandboxed environments (e.g., Cursor IDE,
367        // macOS App Sandbox), reqwest's system proxy lookup via SCDynamicStore can crash
368        // when the API returns NULL. See: https://github.com/foundry-rs/foundry/issues/12733
369        let mut client_builder = foundry_block_explorers::Client::builder()
370            .with_api_key(api_key)
371            .with_cache(cache, Duration::from_secs(24 * 60 * 60));
372        if no_proxy {
373            client_builder = client_builder.no_proxy();
374        }
375        if let Some(ref browser_url) = browser_url {
376            client_builder = client_builder.with_url(browser_url)?;
377        }
378
379        // Use the provided URL (either custom from foundry.toml or chain's default from resolve())
380        client_builder = client_builder.with_api_url(&api_url)?;
381        // Fallback: Use api_url as browser URL if browser_url is not set
382        if browser_url.is_none() {
383            client_builder = client_builder.with_url(&api_url)?;
384        }
385        client_builder.build()
386    }
387
388    /// Returns the directory to cache responses from this explorer's endpoint in.
389    ///
390    /// A config that names its chain is cached under that chain's directory. Mainnet uses a new
391    /// subdirectory to avoid legacy chain-less entries. A config without a chain can point at any
392    /// endpoint, so its responses are keyed by the endpoint instead: the explorer crate derives
393    /// cache file names from the contract address alone, and putting such responses under a chain's
394    /// directory would serve them to that chain's lookups of the same address.
395    fn explorer_cache_dir(&self) -> Option<PathBuf> {
396        if let Some(chain) = self.chain {
397            let cache_dir = Config::foundry_etherscan_chain_cache_dir(chain)?;
398            return Some(if chain == Chain::mainnet() {
399                // Older chain-less clients wrote into this directory via their mainnet fallback.
400                cache_dir.join("client-v2")
401            } else {
402                cache_dir
403            });
404        }
405
406        // Keep URL credentials and query parameters out of persistent filesystem paths.
407        let digest = keccak256(self.api_url.as_bytes());
408        Some(Config::foundry_etherscan_cache_dir()?.join(format!("endpoint-{digest:x}")))
409    }
410}
411
412/// Represents a single etherscan API key
413///
414/// This type preserves the value as it's stored in the config. If the value is a reference to an
415/// env var, then the `EtherscanKey::Key` var will hold the reference (`${MAIN_NET}`) and _not_ the
416/// value of the env var itself.
417/// In other words, this type does not resolve env vars when it's being deserialized
418#[derive(Clone, Debug, PartialEq, Eq)]
419pub enum EtherscanApiKey {
420    /// A raw key
421    Key(String),
422    /// An endpoint that contains at least one `${ENV_VAR}` placeholder
423    ///
424    /// **Note:** this contains the key or `${ETHERSCAN_KEY}`
425    Env(String),
426}
427
428impl EtherscanApiKey {
429    /// Returns the key this type holds
430    ///
431    /// # Error
432    ///
433    /// Returns an error if the type holds a reference to an env var and the env var is not set
434    pub fn resolve(self) -> Result<String, UnresolvedEnvVarError> {
435        match self {
436            Self::Key(key) => Ok(key),
437            Self::Env(val) => interpolate(&val),
438        }
439    }
440}
441
442impl Serialize for EtherscanApiKey {
443    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
444    where
445        S: Serializer,
446    {
447        serializer.serialize_str(&self.to_string())
448    }
449}
450
451impl<'de> Deserialize<'de> for EtherscanApiKey {
452    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
453    where
454        D: Deserializer<'de>,
455    {
456        let val = String::deserialize(deserializer)?;
457        let endpoint = if RE_PLACEHOLDER.is_match(&val) { Self::Env(val) } else { Self::Key(val) };
458
459        Ok(endpoint)
460    }
461}
462
463impl fmt::Display for EtherscanApiKey {
464    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465        match self {
466            Self::Key(key) => key.fmt(f),
467            Self::Env(var) => var.fmt(f),
468        }
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475    use NamedChain::Mainnet;
476
477    #[test]
478    fn can_create_client_via_chain() {
479        let mut configs = EtherscanConfigs::default();
480        configs.insert(
481            "mainnet".to_string(),
482            EtherscanConfig {
483                chain: Some(Mainnet.into()),
484                url: None,
485                key: EtherscanApiKey::Key("ABCDEFG".to_string()),
486            },
487        );
488
489        let mut resolved = configs.resolved();
490        let config = resolved.remove("mainnet").unwrap().unwrap();
491
492        let client = config.into_client().unwrap();
493        assert_eq!(
494            client.etherscan_api_url().as_str(),
495            "https://api.etherscan.io/v2/api?chainid=1"
496        );
497    }
498
499    #[test]
500    fn can_create_client_via_url_and_chain() {
501        let mut configs = EtherscanConfigs::default();
502        configs.insert(
503            "mainnet".to_string(),
504            EtherscanConfig {
505                chain: Some(Mainnet.into()),
506                url: Some("https://api.etherscan.io/api".to_string()),
507                key: EtherscanApiKey::Key("ABCDEFG".to_string()),
508            },
509        );
510
511        let mut resolved = configs.resolved();
512        let config = resolved.remove("mainnet").unwrap().unwrap();
513        let _ = config.into_client().unwrap();
514    }
515
516    #[test]
517    fn can_create_client_via_url_and_chain_env_var() {
518        let mut configs = EtherscanConfigs::default();
519        let env = "_CONFIG_ETHERSCAN_API_KEY";
520        configs.insert(
521            "mainnet".to_string(),
522            EtherscanConfig {
523                chain: Some(Mainnet.into()),
524                url: Some("https://api.etherscan.io/api".to_string()),
525                key: EtherscanApiKey::Env(format!("${{{env}}}")),
526            },
527        );
528
529        let mut resolved = configs.clone().resolved();
530        let config = resolved.remove("mainnet").unwrap();
531        assert!(config.is_err());
532
533        unsafe {
534            std::env::set_var(env, "ABCDEFG");
535        }
536
537        let mut resolved = configs.resolved();
538        let config = resolved.remove("mainnet").unwrap().unwrap();
539        assert_eq!(config.key, "ABCDEFG");
540        let client = config.into_client().unwrap();
541        // Custom URL should be used even when chain has a default URL
542        assert_eq!(client.etherscan_api_url().as_str(), "https://api.etherscan.io/api");
543
544        unsafe {
545            std::env::remove_var(env);
546        }
547    }
548
549    #[test]
550    fn resolve_etherscan_alias_config() {
551        let mut configs = EtherscanConfigs::default();
552        configs.insert(
553            "blast_sepolia".to_string(),
554            EtherscanConfig {
555                chain: None,
556                url: Some("https://api.etherscan.io/api".to_string()),
557                key: EtherscanApiKey::Key("ABCDEFG".to_string()),
558            },
559        );
560
561        let mut resolved = configs.clone().resolved();
562        let config = resolved.remove("blast_sepolia").unwrap().unwrap();
563        assert_eq!(config.chain, Some(Chain::blast_sepolia()));
564    }
565
566    #[test]
567    fn resolve_etherscan_alias() {
568        let config = EtherscanConfig {
569            chain: None,
570            url: Some("https://api.etherscan.io/api".to_string()),
571            key: EtherscanApiKey::Key("ABCDEFG".to_string()),
572        };
573        let resolved = config.clone().resolve(Some("base_sepolia")).unwrap();
574        assert_eq!(resolved.chain, Some(Chain::base_sepolia()));
575
576        let resolved = config.resolve(Some("base-sepolia")).unwrap();
577        assert_eq!(resolved.chain, Some(Chain::base_sepolia()));
578    }
579
580    #[test]
581    fn can_create_client_with_custom_url_for_chain_without_default_url() {
582        // Chains without default Etherscan URLs (e.g., Dev, AnvilHardhat networks)
583        // should work if a custom URL is provided in foundry.toml.
584        let mut configs = EtherscanConfigs::default();
585        configs.insert(
586            "dev".to_string(),
587            EtherscanConfig {
588                chain: Some(Chain::dev()),
589                url: Some("https://custom.api.url/verify/etherscan".to_string()),
590                key: EtherscanApiKey::Key("test_key".to_string()),
591            },
592        );
593
594        let mut resolved = configs.resolved();
595        let config = resolved.remove("dev").unwrap().unwrap();
596        let result = config.into_client();
597        assert!(
598            result.is_ok(),
599            "Should succeed with custom URL even for chains without default Etherscan URLs"
600        );
601    }
602
603    #[test]
604    fn fails_without_custom_url_for_chain_without_default_url() {
605        // Chains without default Etherscan URLs (e.g., Dev, AnvilHardhat networks)
606        // should fail if no custom URL is provided in foundry.toml.
607        let mut configs = EtherscanConfigs::default();
608        configs.insert(
609            "dev".to_string(),
610            EtherscanConfig {
611                chain: Some(Chain::dev()),
612                url: None,
613                key: EtherscanApiKey::Key("test_key".to_string()),
614            },
615        );
616
617        let mut resolved = configs.resolved();
618        let config = resolved.remove("dev").unwrap();
619
620        assert!(
621            config.is_err(),
622            "Should fail: chains without default Etherscan URLs require custom URL"
623        );
624    }
625
626    #[test]
627    fn chainless_explorers_get_their_own_cache_dirs() {
628        // Responses are cached by address alone, so chain-less entries must neither share
629        // mainnet's directory nor each other's.
630        let cache_dir = |url: &str| {
631            let config = EtherscanConfig {
632                chain: None,
633                url: Some(url.to_string()),
634                key: EtherscanApiKey::Key("ABCDEFG".to_string()),
635            }
636            .resolve(Some("mychain"))
637            .unwrap();
638            assert_eq!(config.chain, None);
639            config.explorer_cache_dir().unwrap()
640        };
641
642        let first = cache_dir("https://api.example.com/api?chainid=1");
643        assert_ne!(first, Config::foundry_etherscan_chain_cache_dir(Chain::mainnet()).unwrap());
644        assert_ne!(first, cache_dir("https://api.example.com/api?chainid=2"));
645        assert_eq!(first, cache_dir("https://api.example.com/api?chainid=1"));
646    }
647}