1use 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#[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#[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#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(transparent)]
66pub struct EtherscanConfigs {
67 configs: BTreeMap<String, EtherscanConfig>,
68}
69
70impl EtherscanConfigs {
71 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 pub fn is_empty(&self) -> bool {
78 self.configs.is_empty()
79 }
80
81 pub fn find_chain(&self, chain: Chain) -> Option<&EtherscanConfig> {
83 self.configs.values().find(|config| config.chain == Some(chain))
84 }
85
86 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
117pub struct ResolvedEtherscanConfigs {
118 configs: BTreeMap<String, Result<ResolvedEtherscanConfig, EtherscanConfigError>>,
121}
122
123impl ResolvedEtherscanConfigs {
124 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 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
170pub struct EtherscanConfig {
171 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub chain: Option<Chain>,
174 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub url: Option<String>,
177 pub key: EtherscanApiKey,
179}
180
181impl EtherscanConfig {
182 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 (Some(chain), None) => (Some(chain), Some(chain.to_string())),
201 (None, Some(alias)) => {
202 (
204 alias.to_kebab_case().parse().ok().or_else(|| {
205 serde_json::from_str::<NamedChain>(&format!("\"{alias}\""))
208 .map(Into::into)
209 .ok()
210 }),
211 Some(alias.into()),
212 )
213 }
214 (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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
246pub struct ResolvedEtherscanConfig {
247 #[serde(rename = "url")]
249 pub api_url: String,
250 #[serde(default, skip_serializing_if = "Option::is_none")]
252 pub browser_url: Option<String>,
253 pub key: String,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
257 pub chain: Option<Chain>,
258}
259
260impl ResolvedEtherscanConfig {
261 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 pub fn with_chain(mut self, chain: impl Into<Chain>) -> Self {
277 self.set_chain(chain);
278 self
279 }
280
281 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 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 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 client_builder = client_builder.with_api_url(&api_url)?;
319 if browser_url.is_none() {
321 client_builder = client_builder.with_url(&api_url)?;
322 }
323 client_builder.build()
324 }
325}
326
327#[derive(Clone, Debug, PartialEq, Eq)]
334pub enum EtherscanApiKey {
335 Key(String),
337 Env(String),
341}
342
343impl EtherscanApiKey {
344 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 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 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 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}