1use 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#[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#[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#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(transparent)]
68pub struct EtherscanConfigs {
69 configs: BTreeMap<String, EtherscanConfig>,
70}
71
72impl EtherscanConfigs {
73 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 pub fn is_empty(&self) -> bool {
80 self.configs.is_empty()
81 }
82
83 pub fn find_chain(&self, chain: Chain) -> Option<&EtherscanConfig> {
85 self.configs.values().find(|config| config.chain == Some(chain))
86 }
87
88 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 (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 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
159pub struct ResolvedEtherscanConfigs {
160 configs: BTreeMap<String, Result<ResolvedEtherscanConfig, EtherscanConfigError>>,
163}
164
165impl ResolvedEtherscanConfigs {
166 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 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
212pub struct EtherscanConfig {
213 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub chain: Option<Chain>,
216 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub url: Option<String>,
219 pub key: EtherscanApiKey,
221}
222
223impl EtherscanConfig {
224 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 (Some(chain), None) => (Some(chain), Some(chain.to_string())),
243 (None, Some(alias)) => {
244 (
246 alias.to_kebab_case().parse().ok().or_else(|| {
247 serde_json::from_str::<NamedChain>(&format!("\"{alias}\""))
250 .map(Into::into)
251 .ok()
252 }),
253 Some(alias.into()),
254 )
255 }
256 (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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
288pub struct ResolvedEtherscanConfig {
289 #[serde(rename = "url")]
291 pub api_url: String,
292 #[serde(default, skip_serializing_if = "Option::is_none")]
294 pub browser_url: Option<String>,
295 pub key: String,
297 #[serde(default, skip_serializing_if = "Option::is_none")]
299 pub chain: Option<Chain>,
300}
301
302impl ResolvedEtherscanConfig {
303 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 pub fn with_chain(mut self, chain: impl Into<Chain>) -> Self {
319 self.set_chain(chain);
320 self
321 }
322
323 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 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 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 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 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 client_builder = client_builder.with_api_url(&api_url)?;
381 if browser_url.is_none() {
383 client_builder = client_builder.with_url(&api_url)?;
384 }
385 client_builder.build()
386 }
387
388 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 cache_dir.join("client-v2")
401 } else {
402 cache_dir
403 });
404 }
405
406 let digest = keccak256(self.api_url.as_bytes());
408 Some(Config::foundry_etherscan_cache_dir()?.join(format!("endpoint-{digest:x}")))
409 }
410}
411
412#[derive(Clone, Debug, PartialEq, Eq)]
419pub enum EtherscanApiKey {
420 Key(String),
422 Env(String),
426}
427
428impl EtherscanApiKey {
429 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 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 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 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 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}