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 figment::{
8    Error, Metadata, Profile, Provider,
9    providers::Env,
10    value::{Dict, Map},
11};
12use heck::ToKebabCase;
13use serde::{Deserialize, Deserializer, Serialize, Serializer};
14use std::{
15    collections::BTreeMap,
16    fmt,
17    ops::{Deref, DerefMut},
18    time::Duration,
19};
20
21/// A [Provider] that provides Etherscan API key from the environment if it's not empty.
22///
23/// This prevents `ETHERSCAN_API_KEY=""` if it's set but empty
24#[derive(Debug, Clone, PartialEq, Eq, Default)]
25#[non_exhaustive]
26pub(crate) struct EtherscanEnvProvider;
27
28impl Provider for EtherscanEnvProvider {
29    fn metadata(&self) -> Metadata {
30        Env::raw().metadata()
31    }
32
33    fn data(&self) -> Result<Map<Profile, Dict>, Error> {
34        let mut dict = Dict::default();
35        let env_provider = Env::raw().only(&["ETHERSCAN_API_KEY"]);
36        if let Some((key, value)) = env_provider.iter().next()
37            && !value.trim().is_empty()
38        {
39            dict.insert(key.as_str().to_string(), value.into());
40        }
41
42        Ok(Map::from([(Config::selected_profile(), dict)]))
43    }
44}
45
46/// Errors that can occur when creating an `EtherscanConfig`
47#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
48pub enum EtherscanConfigError {
49    #[error(transparent)]
50    Unresolved(#[from] UnresolvedEnvVarError),
51
52    #[error(
53        "No known Etherscan API URL for chain `{1}`. To fix this, please:\n\
54        1. Specify a `url` {0}\n\
55        2. Verify the chain `{1}` is correct"
56    )]
57    UnknownChain(String, Chain),
58
59    #[error("At least one of `url` or `chain` must be present{0}")]
60    MissingUrlOrChain(String),
61}
62
63/// Container type for Etherscan API keys and URLs.
64#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(transparent)]
66pub struct EtherscanConfigs {
67    configs: BTreeMap<String, EtherscanConfig>,
68}
69
70impl EtherscanConfigs {
71    /// Creates a new list of etherscan configs
72    pub fn new(configs: impl IntoIterator<Item = (impl Into<String>, EtherscanConfig)>) -> Self {
73        Self { configs: configs.into_iter().map(|(name, config)| (name.into(), config)).collect() }
74    }
75
76    /// Returns `true` if this type doesn't contain any configs
77    pub fn is_empty(&self) -> bool {
78        self.configs.is_empty()
79    }
80
81    /// Returns the first config that matches the chain
82    pub fn find_chain(&self, chain: Chain) -> Option<&EtherscanConfig> {
83        self.configs.values().find(|config| config.chain == Some(chain))
84    }
85
86    /// Returns all (alias -> url) pairs
87    pub fn resolved(self) -> ResolvedEtherscanConfigs {
88        ResolvedEtherscanConfigs {
89            configs: self
90                .configs
91                .into_iter()
92                .map(|(name, e)| {
93                    let resolved = e.resolve(Some(&name));
94                    (name, resolved)
95                })
96                .collect(),
97        }
98    }
99}
100
101impl Deref for EtherscanConfigs {
102    type Target = BTreeMap<String, EtherscanConfig>;
103
104    fn deref(&self) -> &Self::Target {
105        &self.configs
106    }
107}
108
109impl DerefMut for EtherscanConfigs {
110    fn deref_mut(&mut self) -> &mut Self::Target {
111        &mut self.configs
112    }
113}
114
115/// Container type for _resolved_ etherscan keys, see [`EtherscanConfigs::resolved`].
116#[derive(Clone, Debug, Default, PartialEq, Eq)]
117pub struct ResolvedEtherscanConfigs {
118    /// contains all named `ResolvedEtherscanConfig` or an error if we failed to resolve the env
119    /// var alias
120    configs: BTreeMap<String, Result<ResolvedEtherscanConfig, EtherscanConfigError>>,
121}
122
123impl ResolvedEtherscanConfigs {
124    /// Creates a new list of resolved etherscan configs
125    pub fn new(
126        configs: impl IntoIterator<Item = (impl Into<String>, ResolvedEtherscanConfig)>,
127    ) -> Self {
128        Self {
129            configs: configs.into_iter().map(|(name, config)| (name.into(), Ok(config))).collect(),
130        }
131    }
132
133    /// Returns the first config that matches the chain
134    pub fn find_chain(
135        self,
136        chain: Chain,
137    ) -> Option<Result<ResolvedEtherscanConfig, EtherscanConfigError>> {
138        for (_, config) in self.configs.into_iter() {
139            match config {
140                Ok(c) if c.chain == Some(chain) => return Some(Ok(c)),
141                Err(e) => return Some(Err(e)),
142                _ => continue,
143            }
144        }
145        None
146    }
147
148    /// Returns true if there's a config that couldn't be resolved
149    pub fn has_unresolved(&self) -> bool {
150        self.configs.values().any(|val| val.is_err())
151    }
152}
153
154impl Deref for ResolvedEtherscanConfigs {
155    type Target = BTreeMap<String, Result<ResolvedEtherscanConfig, EtherscanConfigError>>;
156
157    fn deref(&self) -> &Self::Target {
158        &self.configs
159    }
160}
161
162impl DerefMut for ResolvedEtherscanConfigs {
163    fn deref_mut(&mut self) -> &mut Self::Target {
164        &mut self.configs
165    }
166}
167
168/// Represents all info required to create an etherscan client
169#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
170pub struct EtherscanConfig {
171    /// The chain name or EIP-155 chain ID used to derive the API URL.
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub chain: Option<Chain>,
174    /// Etherscan API URL
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub url: Option<String>,
177    /// The etherscan API KEY that's required to make requests
178    pub key: EtherscanApiKey,
179}
180
181impl EtherscanConfig {
182    /// Returns the etherscan config required to create a client.
183    ///
184    /// # Errors
185    ///
186    /// Returns an error if the type holds a reference to an env var and the env var is not set or
187    /// no chain or url is configured
188    pub fn resolve(
189        self,
190        alias: Option<&str>,
191    ) -> Result<ResolvedEtherscanConfig, EtherscanConfigError> {
192        let Self { chain, mut url, key } = self;
193
194        if let Some(url) = &mut url {
195            *url = interpolate(url)?;
196        }
197
198        let (chain, alias) = match (chain, alias) {
199            // fill one with the other
200            (Some(chain), None) => (Some(chain), Some(chain.to_string())),
201            (None, Some(alias)) => {
202                // alloy chain is parsed as kebab case
203                (
204                    alias.to_kebab_case().parse().ok().or_else(|| {
205                        // if this didn't work try to parse as json because the deserialize impl
206                        // supports more aliases
207                        serde_json::from_str::<NamedChain>(&format!("\"{alias}\""))
208                            .map(Into::into)
209                            .ok()
210                    }),
211                    Some(alias.into()),
212                )
213            }
214            // leave as is
215            (Some(chain), Some(alias)) => (Some(chain), Some(alias.into())),
216            (None, None) => (None, None),
217        };
218        let key = key.resolve()?;
219
220        match (chain, url) {
221            (Some(chain), Some(api_url)) => Ok(ResolvedEtherscanConfig {
222                api_url,
223                browser_url: chain.etherscan_urls().map(|(_, url)| url.to_string()),
224                key,
225                chain: Some(chain),
226            }),
227            (Some(chain), None) => ResolvedEtherscanConfig::create(key, chain).ok_or_else(|| {
228                let msg = alias.map(|a| format!("for `{a}`")).unwrap_or_default();
229                EtherscanConfigError::UnknownChain(msg, chain)
230            }),
231            (None, Some(api_url)) => {
232                Ok(ResolvedEtherscanConfig { api_url, browser_url: None, key, chain: None })
233            }
234            (None, None) => {
235                let msg = alias
236                    .map(|a| format!(" for Etherscan config with unknown alias `{a}`"))
237                    .unwrap_or_default();
238                Err(EtherscanConfigError::MissingUrlOrChain(msg))
239            }
240        }
241    }
242}
243
244/// Contains required url + api key to set up an etherscan client
245#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
246pub struct ResolvedEtherscanConfig {
247    /// Etherscan API URL.
248    #[serde(rename = "url")]
249    pub api_url: String,
250    /// Optional browser URL.
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub browser_url: Option<String>,
253    /// The resolved API key.
254    pub key: String,
255    /// The chain name or EIP-155 chain ID.
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub chain: Option<Chain>,
258}
259
260impl ResolvedEtherscanConfig {
261    /// Creates a new instance using the api key and chain
262    pub fn create(api_key: impl Into<String>, chain: impl Into<Chain>) -> Option<Self> {
263        let chain = chain.into();
264        let (api_url, browser_url) = chain.etherscan_urls()?;
265        Some(Self {
266            api_url: api_url.to_string(),
267            browser_url: Some(browser_url.to_string()),
268            key: api_key.into(),
269            chain: Some(chain),
270        })
271    }
272
273    /// Sets the chain value and consumes the type
274    ///
275    /// This is only used to set derive the appropriate Cache path for the etherscan client
276    pub fn with_chain(mut self, chain: impl Into<Chain>) -> Self {
277        self.set_chain(chain);
278        self
279    }
280
281    /// Sets the chain value
282    pub fn set_chain(&mut self, chain: impl Into<Chain>) -> &mut Self {
283        let chain = chain.into();
284        if let Some((api, browser)) = chain.etherscan_urls() {
285            self.api_url = api.to_string();
286            self.browser_url = Some(browser.to_string());
287        }
288        self.chain = Some(chain);
289        self
290    }
291
292    /// Returns the corresponding `foundry_block_explorers::Client`, configured with the `api_url`,
293    /// `api_key` and cache
294    pub fn into_client(
295        self,
296    ) -> Result<foundry_block_explorers::Client, foundry_block_explorers::errors::EtherscanError>
297    {
298        let Self { api_url, browser_url, key: api_key, chain } = self;
299
300        let chain = chain.unwrap_or_default();
301        let cache = Config::foundry_etherscan_chain_cache_dir(chain);
302
303        if let Some(cache_path) = &cache {
304            // we also create the `sources` sub dir here
305            if let Err(err) = std::fs::create_dir_all(cache_path.join("sources")) {
306                warn!("could not create etherscan cache dir: {:?}", err);
307            }
308        }
309
310        let mut client_builder = foundry_block_explorers::Client::builder()
311            .with_api_key(api_key)
312            .with_cache(cache, Duration::from_secs(24 * 60 * 60));
313        if let Some(ref browser_url) = browser_url {
314            client_builder = client_builder.with_url(browser_url)?;
315        }
316
317        // Use the provided URL (either custom from foundry.toml or chain's default from resolve())
318        client_builder = client_builder.with_api_url(&api_url)?;
319        // Fallback: Use api_url as browser URL if browser_url is not set
320        if browser_url.is_none() {
321            client_builder = client_builder.with_url(&api_url)?;
322        }
323        client_builder.build()
324    }
325}
326
327/// Represents a single etherscan API key
328///
329/// This type preserves the value as it's stored in the config. If the value is a reference to an
330/// env var, then the `EtherscanKey::Key` var will hold the reference (`${MAIN_NET}`) and _not_ the
331/// value of the env var itself.
332/// In other words, this type does not resolve env vars when it's being deserialized
333#[derive(Clone, Debug, PartialEq, Eq)]
334pub enum EtherscanApiKey {
335    /// A raw key
336    Key(String),
337    /// An endpoint that contains at least one `${ENV_VAR}` placeholder
338    ///
339    /// **Note:** this contains the key or `${ETHERSCAN_KEY}`
340    Env(String),
341}
342
343impl EtherscanApiKey {
344    /// Returns the key this type holds
345    ///
346    /// # Error
347    ///
348    /// Returns an error if the type holds a reference to an env var and the env var is not set
349    pub fn resolve(self) -> Result<String, UnresolvedEnvVarError> {
350        match self {
351            Self::Key(key) => Ok(key),
352            Self::Env(val) => interpolate(&val),
353        }
354    }
355}
356
357impl Serialize for EtherscanApiKey {
358    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
359    where
360        S: Serializer,
361    {
362        serializer.serialize_str(&self.to_string())
363    }
364}
365
366impl<'de> Deserialize<'de> for EtherscanApiKey {
367    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
368    where
369        D: Deserializer<'de>,
370    {
371        let val = String::deserialize(deserializer)?;
372        let endpoint = if RE_PLACEHOLDER.is_match(&val) { Self::Env(val) } else { Self::Key(val) };
373
374        Ok(endpoint)
375    }
376}
377
378impl fmt::Display for EtherscanApiKey {
379    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380        match self {
381            Self::Key(key) => key.fmt(f),
382            Self::Env(var) => var.fmt(f),
383        }
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390    use NamedChain::Mainnet;
391
392    #[test]
393    fn can_create_client_via_chain() {
394        let mut configs = EtherscanConfigs::default();
395        configs.insert(
396            "mainnet".to_string(),
397            EtherscanConfig {
398                chain: Some(Mainnet.into()),
399                url: None,
400                key: EtherscanApiKey::Key("ABCDEFG".to_string()),
401            },
402        );
403
404        let mut resolved = configs.resolved();
405        let config = resolved.remove("mainnet").unwrap().unwrap();
406
407        let client = config.into_client().unwrap();
408        assert_eq!(
409            client.etherscan_api_url().as_str(),
410            "https://api.etherscan.io/v2/api?chainid=1"
411        );
412    }
413
414    #[test]
415    fn can_create_client_via_url_and_chain() {
416        let mut configs = EtherscanConfigs::default();
417        configs.insert(
418            "mainnet".to_string(),
419            EtherscanConfig {
420                chain: Some(Mainnet.into()),
421                url: Some("https://api.etherscan.io/api".to_string()),
422                key: EtherscanApiKey::Key("ABCDEFG".to_string()),
423            },
424        );
425
426        let mut resolved = configs.resolved();
427        let config = resolved.remove("mainnet").unwrap().unwrap();
428        let _ = config.into_client().unwrap();
429    }
430
431    #[test]
432    fn can_create_client_via_url_and_chain_env_var() {
433        let mut configs = EtherscanConfigs::default();
434        let env = "_CONFIG_ETHERSCAN_API_KEY";
435        configs.insert(
436            "mainnet".to_string(),
437            EtherscanConfig {
438                chain: Some(Mainnet.into()),
439                url: Some("https://api.etherscan.io/api".to_string()),
440                key: EtherscanApiKey::Env(format!("${{{env}}}")),
441            },
442        );
443
444        let mut resolved = configs.clone().resolved();
445        let config = resolved.remove("mainnet").unwrap();
446        assert!(config.is_err());
447
448        unsafe {
449            std::env::set_var(env, "ABCDEFG");
450        }
451
452        let mut resolved = configs.resolved();
453        let config = resolved.remove("mainnet").unwrap().unwrap();
454        assert_eq!(config.key, "ABCDEFG");
455        let client = config.into_client().unwrap();
456        // Custom URL should be used even when chain has a default URL
457        assert_eq!(client.etherscan_api_url().as_str(), "https://api.etherscan.io/api");
458
459        unsafe {
460            std::env::remove_var(env);
461        }
462    }
463
464    #[test]
465    fn resolve_etherscan_alias_config() {
466        let mut configs = EtherscanConfigs::default();
467        configs.insert(
468            "blast_sepolia".to_string(),
469            EtherscanConfig {
470                chain: None,
471                url: Some("https://api.etherscan.io/api".to_string()),
472                key: EtherscanApiKey::Key("ABCDEFG".to_string()),
473            },
474        );
475
476        let mut resolved = configs.clone().resolved();
477        let config = resolved.remove("blast_sepolia").unwrap().unwrap();
478        assert_eq!(config.chain, Some(Chain::blast_sepolia()));
479    }
480
481    #[test]
482    fn resolve_etherscan_alias() {
483        let config = EtherscanConfig {
484            chain: None,
485            url: Some("https://api.etherscan.io/api".to_string()),
486            key: EtherscanApiKey::Key("ABCDEFG".to_string()),
487        };
488        let resolved = config.clone().resolve(Some("base_sepolia")).unwrap();
489        assert_eq!(resolved.chain, Some(Chain::base_sepolia()));
490
491        let resolved = config.resolve(Some("base-sepolia")).unwrap();
492        assert_eq!(resolved.chain, Some(Chain::base_sepolia()));
493    }
494
495    #[test]
496    fn can_create_client_with_custom_url_for_chain_without_default_url() {
497        // Chains without default Etherscan URLs (e.g., Dev, AnvilHardhat networks)
498        // should work if a custom URL is provided in foundry.toml.
499        let mut configs = EtherscanConfigs::default();
500        configs.insert(
501            "dev".to_string(),
502            EtherscanConfig {
503                chain: Some(Chain::dev()),
504                url: Some("https://custom.api.url/verify/etherscan".to_string()),
505                key: EtherscanApiKey::Key("test_key".to_string()),
506            },
507        );
508
509        let mut resolved = configs.resolved();
510        let config = resolved.remove("dev").unwrap().unwrap();
511        let result = config.into_client();
512        assert!(
513            result.is_ok(),
514            "Should succeed with custom URL even for chains without default Etherscan URLs"
515        );
516    }
517
518    #[test]
519    fn fails_without_custom_url_for_chain_without_default_url() {
520        // Chains without default Etherscan URLs (e.g., Dev, AnvilHardhat networks)
521        // should fail if no custom URL is provided in foundry.toml.
522        let mut configs = EtherscanConfigs::default();
523        configs.insert(
524            "dev".to_string(),
525            EtherscanConfig {
526                chain: Some(Chain::dev()),
527                url: None,
528                key: EtherscanApiKey::Key("test_key".to_string()),
529            },
530        );
531
532        let mut resolved = configs.resolved();
533        let config = resolved.remove("dev").unwrap();
534
535        assert!(
536            config.is_err(),
537            "Should fail: chains without default Etherscan URLs require custom URL"
538        );
539    }
540}