1#![cfg_attr(not(test), warn(unused_crate_dependencies))]
6#![cfg_attr(docsrs, feature(doc_cfg))]
7
8#[macro_use]
9extern crate tracing;
10
11use crate::{cache::StorageCachingConfig, etherscan::EtherscanEnvProvider};
12use alloy_primitives::{Address, B256, U256, address, map::AddressHashMap};
13use eyre::{ContextCompat, WrapErr};
14use figment::{
15 Error, Figment, Metadata, Profile, Provider,
16 providers::{Env, Format, Serialized, Toml},
17 value::{Dict, Map, Value},
18};
19use filter::GlobMatcher;
20use foundry_compilers::{
21 ArtifactOutput, ConfigurableArtifacts, Graph, Project, ProjectBuilder, ProjectPathsConfig,
22 RestrictionsWithVersion, VyperLanguage,
23 artifacts::{
24 BytecodeHash, Contract, DebuggingSettings, EvmVersion, Libraries, ModelCheckerSettings,
25 ModelCheckerTarget, Optimizer, OptimizerDetails, RevertStrings, Settings, SettingsMetadata,
26 Severity,
27 output_selection::{ContractOutputSelection, OutputSelection},
28 remappings::{RelativeRemapping, Remapping},
29 serde_helpers,
30 },
31 cache::SOLIDITY_FILES_CACHE_FILENAME,
32 compilers::{
33 Compiler,
34 multi::{MultiCompiler, MultiCompilerSettings},
35 solc::{Solc, SolcCompiler},
36 vyper::{Vyper, VyperSettings},
37 },
38 error::SolcError,
39 multi::{MultiCompilerLanguage, MultiCompilerParser, MultiCompilerRestrictions},
40 solc::{CliSettings, SolcLanguage, SolcSettings},
41 utils::canonicalize,
42};
43use regex::Regex;
44use semver::Version;
45use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
46use std::{
47 borrow::Cow,
48 collections::{BTreeMap, HashSet},
49 fs, io,
50 path::{Component, Path, PathBuf},
51 str::FromStr,
52};
53
54#[cfg(windows)]
55use path_slash::PathBufExt as _;
56
57mod macros;
58
59pub mod utils;
60pub use foundry_evm_hardforks::{
61 ExecutionSpec, FoundryHardfork, FromEvmVersion, evm_spec_id, evm_spec_id_from_str,
62};
63pub use utils::*;
64
65mod endpoints;
66pub use endpoints::{
67 ResolvedRpcEndpoint, ResolvedRpcEndpoints, RpcEndpoint, RpcEndpointUrl, RpcEndpoints,
68 builtin_rpc_url,
69};
70
71mod etherscan;
72pub use etherscan::{EtherscanConfigError, EtherscanConfigs, ResolvedEtherscanConfig};
73
74pub mod resolve;
75pub use resolve::UnresolvedEnvVarError;
76
77pub mod cache;
78use cache::{Cache, ChainCache};
79
80pub mod fmt;
81pub use fmt::FormatterConfig;
82
83pub mod lint;
84pub use lint::{LinterConfig, Severity as LintSeverity};
85
86pub mod fs_permissions;
87use fs_permissions::PathPermission;
88
89pub use fs_permissions::FsPermissions;
90
91pub mod error;
92use error::ExtractConfigError;
93
94pub use error::SolidityErrorCode;
95
96pub mod doc;
97pub use doc::DocConfig;
98
99pub mod filter;
100pub use filter::SkipBuildFilters;
101
102mod warning;
103pub use warning::*;
104
105pub mod fix;
106
107pub use alloy_chains::{Chain, NamedChain};
109pub use figment;
110
111pub mod providers;
112use providers::*;
113
114pub use providers::Remappings;
115
116mod fuzz;
117pub use fuzz::{FuzzConfig, FuzzCorpusConfig, FuzzCorpusMutationWeights, FuzzDictionaryConfig};
118
119mod invariant;
120pub use invariant::{InvariantConfig, InvariantDepthMode, InvariantWorkers};
121
122mod symbolic;
123pub use symbolic::{SymbolicConfig, SymbolicExplorationOrder, SymbolicStorageLayout};
124
125mod coverage;
126pub use coverage::{CoverageConfig, CoverageReportKind, parse_lcov_version};
127
128mod trace;
129pub use trace::TracingConfig;
130
131mod fee;
132pub use fee::Eip1559FeeEstimatePreset;
133
134pub mod mutation;
135pub use mutation::{MutationConfig, MutatorType};
136
137mod inline;
138pub use inline::{InlineConfig, InlineConfigError, NatSpec};
139
140pub mod soldeer;
141use soldeer::{SoldeerConfig, SoldeerDependencyConfig};
142
143mod vyper;
144pub use vyper::VyperConfig;
145
146mod bind_json;
147use bind_json::BindJsonConfig;
148
149mod compilation;
150pub use compilation::{CompilationRestrictions, SettingsOverrides};
151
152mod external_compiler;
153pub use external_compiler::ExternalCompiler;
154
155pub mod extend;
156use extend::Extends;
157use foundry_evm_networks::NetworkConfigs;
158
159pub use semver;
160
161#[cfg(not(test))]
162static SELECTED_PROFILE: std::sync::OnceLock<Profile> = std::sync::OnceLock::new();
163
164#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
196pub struct Config {
197 #[serde(skip)]
204 pub profile: Profile,
205 #[serde(skip)]
209 pub profiles: Vec<Profile>,
210
211 #[serde(default = "root_default", skip_serializing)]
216 pub root: PathBuf,
217
218 #[serde(default, skip_serializing)]
223 pub extends: Option<Extends>,
224
225 pub src: PathBuf,
229 pub test: PathBuf,
231 pub script: PathBuf,
233 pub out: PathBuf,
235 pub libs: Vec<PathBuf>,
237 #[serde(serialize_with = "remappings_serde::serialize")]
239 pub remappings: Vec<RelativeRemapping>,
240 pub auto_detect_remappings: bool,
247 pub libraries: Vec<String>,
252 pub cache: bool,
254 pub cache_path: PathBuf,
256 pub dynamic_test_linking: bool,
258 pub allow_linked_libraries: bool,
264 pub snapshots: PathBuf,
266 pub gas_snapshot_check: bool,
268 pub gas_snapshot_emit: bool,
270 pub broadcast: PathBuf,
272 pub allow_paths: Vec<PathBuf>,
274 pub include_paths: Vec<PathBuf>,
276 pub skip: Vec<GlobMatcher>,
278 pub force: bool,
280 #[serde(with = "from_str_lowercase")]
282 pub evm_version: EvmVersion,
283 pub hardfork: Option<FoundryHardfork>,
285 pub gas_reports: Vec<String>,
287 pub gas_reports_ignore: Vec<String>,
289 pub gas_reports_include_tests: bool,
291 #[doc(hidden)]
301 pub solc: Option<SolcReq>,
302 pub auto_detect_solc: bool,
304 pub offline: bool,
311 pub optimizer: Option<bool>,
313 pub optimizer_runs: Option<usize>,
324 pub optimizer_details: Option<OptimizerDetails>,
328 pub model_checker: Option<ModelCheckerSettings>,
330 pub verbosity: u8,
332 pub eth_rpc_url: Option<String>,
334 pub eth_rpc_accept_invalid_certs: bool,
336 pub eth_rpc_no_proxy: bool,
341 pub eth_rpc_jwt: Option<String>,
343 pub eth_rpc_timeout: Option<u64>,
345 pub eth_rpc_headers: Option<Vec<String>>,
354 pub eth_rpc_curl: bool,
356 pub etherscan_api_key: Option<String>,
358 #[serde(default, skip_serializing_if = "EtherscanConfigs::is_empty")]
360 pub etherscan: EtherscanConfigs,
361 pub ignored_error_codes: Vec<SolidityErrorCode>,
363 pub ignored_error_codes_from: Vec<(PathBuf, Vec<SolidityErrorCode>)>,
365 #[serde(rename = "ignored_warnings_from")]
367 pub ignored_file_paths: Vec<PathBuf>,
368 pub deny: DenyLevel,
370 #[serde(default, skip_serializing)]
372 pub deny_warnings: bool,
373 #[serde(rename = "match_test")]
375 pub test_pattern: Option<RegexWrapper>,
376 #[serde(rename = "no_match_test")]
378 pub test_pattern_inverse: Option<RegexWrapper>,
379 #[serde(rename = "match_contract")]
381 pub contract_pattern: Option<RegexWrapper>,
382 #[serde(rename = "no_match_contract")]
384 pub contract_pattern_inverse: Option<RegexWrapper>,
385 #[serde(rename = "match_path", with = "from_opt_glob")]
387 pub path_pattern: Option<globset::Glob>,
388 #[serde(rename = "no_match_path", with = "from_opt_glob")]
390 pub path_pattern_inverse: Option<globset::Glob>,
391 #[serde(rename = "no_match_coverage")]
393 pub coverage_pattern_inverse: Option<RegexWrapper>,
394 pub test_failures_file: PathBuf,
396 pub mutation_dir: PathBuf,
398 pub threads: Option<usize>,
400 pub show_progress: bool,
402 pub fuzz: FuzzConfig,
404 pub invariant: InvariantConfig,
406 pub symbolic: SymbolicConfig,
408 pub coverage: CoverageConfig,
410 pub mutation: MutationConfig,
412 pub tracing: TracingConfig,
414 pub ffi: bool,
416 pub live_logs: bool,
421 pub allow_internal_expect_revert: bool,
423 pub always_use_create_2_factory: bool,
425 #[serde(default)]
429 pub eip1559_fee_estimate: Eip1559FeeEstimatePreset,
430 pub prompt_timeout: u64,
432 pub sender: Address,
434 pub tx_origin: Address,
436 pub initial_balance: U256,
438 #[serde(
440 deserialize_with = "crate::deserialize_u64_to_u256",
441 serialize_with = "crate::serialize_u64_or_u256"
442 )]
443 pub block_number: U256,
444 pub fork_block_number: Option<u64>,
446 #[serde(default)]
448 pub fork_state_by_number: bool,
449 #[serde(rename = "chain_id", alias = "chain")]
451 pub chain: Option<Chain>,
452 pub gas_limit: GasLimit,
454 pub code_size_limit: Option<usize>,
456 pub gas_price: Option<u64>,
461 pub block_base_fee_per_gas: u64,
463 pub block_coinbase: Address,
465 #[serde(
467 deserialize_with = "crate::deserialize_u64_to_u256",
468 serialize_with = "crate::serialize_u64_or_u256"
469 )]
470 pub block_timestamp: U256,
471 pub block_difficulty: u64,
473 pub block_prevrandao: B256,
475 pub block_gas_limit: Option<GasLimit>,
477 pub memory_limit: u64,
482 #[serde(default)]
499 pub extra_output: Vec<ContractOutputSelection>,
500 #[serde(default)]
511 pub extra_output_files: Vec<ContractOutputSelection>,
512 pub names: bool,
514 pub sizes: bool,
516 pub via_ir: bool,
519 pub via_ssa_cfg: bool,
523 pub experimental: bool,
528 pub ast: bool,
530 pub rpc_storage_caching: StorageCachingConfig,
532 pub no_storage_caching: bool,
535 #[serde(default)]
545 pub no_fork_bal: bool,
546 #[serde(default)]
554 pub fork_prefetch: bool,
555 pub no_rpc_rate_limit: bool,
558 #[serde(default, skip_serializing_if = "RpcEndpoints::is_empty")]
560 pub rpc_endpoints: RpcEndpoints,
561 pub use_literal_content: bool,
563 #[serde(with = "from_str_lowercase")]
570 pub bytecode_hash: BytecodeHash,
571 pub cbor_metadata: bool,
576 #[serde(with = "serde_helpers::display_from_str_opt")]
578 pub revert_strings: Option<RevertStrings>,
579 pub sparse_mode: bool,
584 pub build_info: bool,
587 pub build_info_path: Option<PathBuf>,
589 #[serde(skip)]
591 pub build_info_without_ast: bool,
592 pub fmt: FormatterConfig,
594 pub lint: LinterConfig,
596 pub doc: DocConfig,
598 pub bind_json: BindJsonConfig,
600 pub fs_permissions: FsPermissions,
604
605 pub isolate: bool,
609
610 pub disable_block_gas_limit: bool,
612
613 pub enable_tx_gas_limit: bool,
616
617 #[serde(default, skip_serializing_if = "AddressHashMap::is_empty")]
619 pub labels: AddressHashMap<String>,
620
621 pub unchecked_cheatcode_artifacts: bool,
624
625 pub decode_external_storage: bool,
631
632 pub create2_library_salt: B256,
634
635 pub create2_deployer: Address,
637
638 pub vyper: VyperConfig,
640
641 #[serde(default, skip_serializing_if = "Vec::is_empty")]
643 pub external_compilers: Vec<ExternalCompiler>,
644
645 pub dependencies: Option<SoldeerDependencyConfig>,
647
648 pub soldeer: Option<SoldeerConfig>,
650
651 pub assertions_revert: bool,
655
656 pub legacy_assertions: bool,
658
659 #[serde(default, skip_serializing_if = "Vec::is_empty")]
661 pub extra_args: Vec<String>,
662
663 #[serde(flatten)]
665 pub networks: NetworkConfigs,
666
667 pub transaction_timeout: u64,
669
670 #[serde(rename = "__warnings", default, skip_serializing)]
672 pub warnings: Vec<Warning>,
673
674 #[serde(default)]
676 pub additional_compiler_profiles: Vec<SettingsOverrides>,
677
678 #[serde(default)]
680 pub compilation_restrictions: Vec<CompilationRestrictions>,
681
682 pub script_execution_protection: bool,
684
685 #[doc(hidden)]
690 #[serde(skip)]
691 pub restrict_inline_config: bool,
692
693 #[doc(hidden)]
702 #[serde(skip)]
703 pub _non_exhaustive: (),
704}
705
706#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, Default, Serialize)]
708#[serde(rename_all = "lowercase")]
709pub enum DenyLevel {
710 #[default]
712 Never,
713 Warnings,
715 Notes,
717}
718
719impl<'de> Deserialize<'de> for DenyLevel {
722 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
723 where
724 D: Deserializer<'de>,
725 {
726 struct DenyLevelVisitor;
727
728 impl<'de> de::Visitor<'de> for DenyLevelVisitor {
729 type Value = DenyLevel;
730
731 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
732 formatter.write_str("one of the following strings: `never`, `warnings`, `notes`")
733 }
734
735 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
736 where
737 E: de::Error,
738 {
739 Ok(DenyLevel::from(value))
740 }
741
742 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
743 where
744 E: de::Error,
745 {
746 DenyLevel::from_str(value).map_err(de::Error::custom)
747 }
748 }
749
750 deserializer.deserialize_any(DenyLevelVisitor)
751 }
752}
753
754impl FromStr for DenyLevel {
755 type Err = String;
756
757 fn from_str(s: &str) -> Result<Self, Self::Err> {
758 match s.to_lowercase().as_str() {
759 "warnings" | "warning" | "w" => Ok(Self::Warnings),
760 "notes" | "note" | "n" => Ok(Self::Notes),
761 "never" | "false" | "f" => Ok(Self::Never),
762 _ => Err(format!(
763 "unknown variant: found `{s}`, expected one of `never`, `warnings`, `notes`"
764 )),
765 }
766 }
767}
768
769impl From<bool> for DenyLevel {
770 fn from(deny: bool) -> Self {
771 if deny { Self::Warnings } else { Self::Never }
772 }
773}
774
775impl DenyLevel {
776 pub const fn warnings(&self) -> bool {
778 match self {
779 Self::Never => false,
780 Self::Warnings | Self::Notes => true,
781 }
782 }
783
784 pub const fn notes(&self) -> bool {
786 match self {
787 Self::Never | Self::Warnings => false,
788 Self::Notes => true,
789 }
790 }
791
792 pub const fn never(&self) -> bool {
794 match self {
795 Self::Never => true,
796 Self::Warnings | Self::Notes => false,
797 }
798 }
799}
800
801pub const STANDALONE_FALLBACK_SECTIONS: &[(&str, &str)] = &[("invariant", "fuzz")];
803
804pub const DEPRECATIONS: &[(&str, &str)] =
808 &[("cancun", "evm_version = Cancun"), ("deny_warnings", "deny = warnings")];
809
810impl Config {
811 pub const DEFAULT_PROFILE: Profile = Profile::Default;
813
814 pub const HARDHAT_PROFILE: Profile = Profile::const_new("hardhat");
816
817 pub const PROFILE_SECTION: &'static str = "profile";
819
820 pub const EXTERNAL_SECTION: &'static str = "external";
822
823 pub const STANDALONE_SECTIONS: &'static [&'static str] = &[
825 "rpc_endpoints",
826 "etherscan",
827 "fmt",
828 "lint",
829 "doc",
830 "fuzz",
831 "invariant",
832 "symbolic",
833 "coverage",
834 "mutation",
835 "tracing",
836 "labels",
837 "dependencies",
838 "soldeer",
839 "vyper",
840 "bind_json",
841 ];
842
843 pub(crate) fn is_standalone_section<T: ?Sized + PartialEq<str>>(section: &T) -> bool {
844 section == Self::PROFILE_SECTION
845 || section == Self::EXTERNAL_SECTION
846 || Self::STANDALONE_SECTIONS.iter().any(|s| section == *s)
847 }
848
849 pub const FILE_NAME: &'static str = "foundry.toml";
851
852 const DEFAULT_SRC: &'static str = "src";
853
854 pub const FOUNDRY_DIR_NAME: &'static str = ".foundry";
856
857 pub const DEFAULT_SENDER: Address = address!("0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38");
861
862 pub const DEFAULT_CREATE2_LIBRARY_SALT: B256 = B256::ZERO;
864
865 pub const DEFAULT_CREATE2_DEPLOYER: Address =
867 address!("0x4e59b44847b379578588920ca78fbf26c0b4956c");
868
869 pub fn load() -> Result<Self, ExtractConfigError> {
873 Self::from_provider(Self::figment())
874 }
875
876 pub fn load_with_providers(providers: FigmentProviders) -> Result<Self, ExtractConfigError> {
880 Self::from_provider(Self::default().to_figment(providers))
881 }
882
883 #[track_caller]
887 pub fn load_with_root(root: impl AsRef<Path>) -> Result<Self, ExtractConfigError> {
888 Self::from_provider(Self::figment_with_root(root.as_ref()))
889 }
890
891 #[track_caller]
898 pub fn load_with_root_and_fallback(root: impl AsRef<Path>) -> Result<Self, ExtractConfigError> {
899 let figment = Self::figment_with_root(root.as_ref());
900 Self::from_figment_fallback(Figment::from(figment))
901 }
902
903 #[doc(alias = "try_from")]
918 pub fn from_provider<T: Provider>(provider: T) -> Result<Self, ExtractConfigError> {
919 trace!("load config with provider: {:?}", provider.metadata());
920 Self::from_figment(Figment::from(provider.legacy_labels()))
921 }
922
923 pub fn merge_inline_provider<T: Provider>(&self, provider: T) -> Result<Self, Error> {
926 let provider = Figment::from(provider.legacy_labels()).select(self.profile.clone());
927 let invariant_corpus_random_sequence_weight_configured =
928 self.invariant.corpus_random_sequence_weight_configured
929 || provider.contains("invariant.corpus_random_sequence_weight")
930 || provider
931 .extract_inner::<bool>("invariant.corpus_random_sequence_weight_configured")
932 .unwrap_or(false);
933 let invariant_workers_configured = self.invariant.workers_configured
934 || provider.contains("invariant.workers")
935 || provider.extract_inner::<bool>("invariant.workers_configured").unwrap_or(false)
936 || provider.extract_inner::<InvariantWorkers>("invariant.workers").is_ok();
937 let figment = self.to_figment(FigmentProviders::None).merge(provider);
938 let mut config = figment.extract::<Self>()?;
939 config.profile = self.profile.clone();
940 config.profiles = self.profiles.clone();
941 config.root = self.root.clone();
944 config.invariant.corpus_random_sequence_weight_configured =
945 invariant_corpus_random_sequence_weight_configured;
946 config.invariant.workers_configured = invariant_workers_configured;
947 config.restrict_inline_config = self.restrict_inline_config;
948 config.normalize_hardfork_settings()?;
949 if self.restrict_inline_config
950 && let Some(change) = self.restricted_inline_change(&config)
951 {
952 return Err(Error::from(format!("inline config cannot {change} in generated tests")));
953 }
954
955 Ok(config)
956 }
957
958 fn restricted_inline_change(&self, inline: &Self) -> Option<String> {
962 let (fuzz, invariant) = (&inline.fuzz, &inline.invariant);
963 let rejects = |rejects: u32| if rejects == 0 { u32::MAX } else { rejects };
965 let caps_raised = |base: &FuzzDictionaryConfig, inline: &FuzzDictionaryConfig| {
966 inline.max_fuzz_dictionary_addresses > base.max_fuzz_dictionary_addresses
967 || inline.max_fuzz_dictionary_values > base.max_fuzz_dictionary_values
968 || inline.max_fuzz_dictionary_literals > base.max_fuzz_dictionary_literals
969 };
970 let raised = [
971 ("fuzz.runs", fuzz.runs > self.fuzz.runs),
972 (
973 "fuzz.max_test_rejects",
974 rejects(fuzz.max_test_rejects) > rejects(self.fuzz.max_test_rejects),
975 ),
976 ("fuzz.dictionary", caps_raised(&self.fuzz.dictionary, &fuzz.dictionary)),
977 (
978 "invariant.dictionary",
979 caps_raised(&self.invariant.dictionary, &invariant.dictionary),
980 ),
981 ("invariant.runs", invariant.runs > self.invariant.runs),
982 ("invariant.depth", invariant.depth > self.invariant.depth),
983 ("invariant.min_depth", invariant.min_depth > self.invariant.min_depth),
984 (
985 "invariant.shrink_run_limit",
986 invariant.shrink_run_limit > self.invariant.shrink_run_limit,
987 ),
988 (
989 "invariant.max_assume_rejects",
990 invariant.max_assume_rejects > self.invariant.max_assume_rejects,
991 ),
992 ];
993 if let Some((key, _)) = raised.into_iter().find(|(_, raised)| *raised) {
994 return Some(format!("raise `{key}`"));
995 }
996 let mut allowed = inline.clone();
997 allowed.fuzz.runs = self.fuzz.runs;
998 allowed.fuzz.max_test_rejects = self.fuzz.max_test_rejects;
999 allowed.fuzz.dictionary = self.fuzz.dictionary;
1000 allowed.fuzz.show_logs = self.fuzz.show_logs;
1001 allowed.invariant.runs = self.invariant.runs;
1002 allowed.invariant.depth = self.invariant.depth;
1003 allowed.invariant.min_depth = self.invariant.min_depth;
1004 allowed.invariant.depth_mode = self.invariant.depth_mode;
1005 allowed.invariant.shrink_run_limit = self.invariant.shrink_run_limit;
1006 allowed.invariant.max_assume_rejects = self.invariant.max_assume_rejects;
1007 allowed.invariant.call_override = self.invariant.call_override;
1008 allowed.invariant.dictionary = self.invariant.dictionary;
1009 allowed.invariant.max_time_delay = self.invariant.max_time_delay;
1010 allowed.invariant.max_block_delay = self.invariant.max_block_delay;
1011 allowed.invariant.check_interval = self.invariant.check_interval;
1012 allowed.invariant.call_gas_limit = self.invariant.call_gas_limit;
1013 allowed.invariant.show_metrics = self.invariant.show_metrics;
1014 allowed.invariant.show_solidity = self.invariant.show_solidity;
1015 allowed.allow_internal_expect_revert = self.allow_internal_expect_revert;
1016 fn changed_key(base: &serde_json::Value, other: &serde_json::Value) -> Option<String> {
1017 match (base, other) {
1018 (serde_json::Value::Object(base), serde_json::Value::Object(other)) => {
1019 base.keys().chain(other.keys()).find_map(|key| {
1020 let null = serde_json::Value::Null;
1021 let (a, b) =
1022 (base.get(key).unwrap_or(&null), other.get(key).unwrap_or(&null));
1023 changed_key(a, b).map(|rest| {
1024 if rest.is_empty() { key.clone() } else { format!("{key}.{rest}") }
1025 })
1026 })
1027 }
1028 _ => (base != other).then(String::new),
1029 }
1030 }
1031 let (Ok(base), Ok(allowed)) = (serde_json::to_value(self), serde_json::to_value(&allowed))
1032 else {
1033 return Some("change settings that do not serialize".to_string());
1034 };
1035 Some(format!("change `{}`", changed_key(&base, &allowed)?))
1036 }
1037
1038 #[doc(hidden)]
1039 #[deprecated(note = "use `Config::from_provider` instead")]
1040 pub fn try_from<T: Provider>(provider: T) -> Result<Self, ExtractConfigError> {
1041 Self::from_provider(provider)
1042 }
1043
1044 fn from_figment(figment: Figment) -> Result<Self, ExtractConfigError> {
1045 Self::from_figment_inner(figment, true)
1046 }
1047
1048 fn from_figment_fallback(figment: Figment) -> Result<Self, ExtractConfigError> {
1051 Self::from_figment_inner(figment, false)
1052 }
1053
1054 fn from_figment_inner(
1055 figment: Figment,
1056 strict_profile: bool,
1057 ) -> Result<Self, ExtractConfigError> {
1058 let invariant_corpus_random_sequence_weight_configured = figment
1059 .extract_inner::<bool>("invariant.corpus_random_sequence_weight_configured")
1060 .unwrap_or_else(|_| {
1061 figment_value_is_configured(&figment, "invariant.corpus_random_sequence_weight")
1062 });
1063 let invariant_workers_configured = figment
1064 .extract_inner::<bool>("invariant.workers_configured")
1065 .unwrap_or_else(|_| figment_value_is_configured(&figment, "invariant.workers"));
1066 let mut config = figment.extract::<Self>().map_err(ExtractConfigError::new)?;
1067 config.invariant.corpus_random_sequence_weight_configured =
1068 invariant_corpus_random_sequence_weight_configured;
1069 config.invariant.workers_configured = invariant_workers_configured;
1070 let selected_profile = figment.profile().clone();
1071
1072 fn add_profile(profiles: &mut Vec<Profile>, profile: &Profile) {
1074 if !profiles.contains(profile) {
1075 profiles.push(profile.clone());
1076 }
1077 }
1078 let figment = figment.select(Self::PROFILE_SECTION);
1079 if let Ok(data) = figment.data()
1080 && let Some(profiles) = data.get(&Profile::new(Self::PROFILE_SECTION))
1081 {
1082 for profile in profiles.keys() {
1083 add_profile(&mut config.profiles, &Profile::new(profile));
1084 }
1085 }
1086 add_profile(&mut config.profiles, &Self::DEFAULT_PROFILE);
1087
1088 if config.profiles.contains(&selected_profile) {
1090 config.profile = selected_profile;
1091 } else {
1092 if strict_profile {
1096 config
1097 .warnings
1098 .push(Warning::UnknownProfile { profile: selected_profile.to_string() });
1099 }
1100 config.profile = Self::DEFAULT_PROFILE;
1101 }
1102
1103 config.normalize_optimizer_settings();
1104 config.normalize_hardfork_settings().map_err(ExtractConfigError::new)?;
1105
1106 if let Some(runs) = config.optimizer_runs
1108 && runs > u32::MAX as usize
1109 {
1110 return Err(ExtractConfigError::new(Error::from(format!(
1111 "`optimizer_runs` value {} exceeds maximum allowed value of {}",
1112 runs,
1113 u32::MAX
1114 ))));
1115 }
1116
1117 Ok(config)
1118 }
1119
1120 fn normalize_hardfork_settings(&mut self) -> Result<(), Error> {
1121 self.networks.validate()?;
1122 let Some(hardfork) = self.hardfork else { return Ok(()) };
1123 self.networks = self.networks.normalize_for_hardfork(hardfork)?;
1124 Ok(())
1125 }
1126
1127 fn uses_default_src(&self) -> bool {
1128 self.src == Path::new(Self::DEFAULT_SRC)
1129 }
1130
1131 pub fn to_figment(&self, providers: FigmentProviders) -> Figment {
1136 if providers.is_none() {
1139 return Figment::from(self);
1140 }
1141
1142 let root = self.root.as_path();
1143 let profile = Self::selected_profile();
1144 let mut figment = Figment::default()
1145 .merge(DappHardhatDirProvider { root, detect_src: self.uses_default_src() });
1146
1147 if let Some(global_toml) = Self::foundry_dir_toml().filter(|p| p.exists()) {
1149 figment = Self::merge_toml_provider(
1150 figment,
1151 TomlFileProvider::new(None, global_toml),
1152 profile.clone(),
1153 );
1154 }
1155 figment = Self::merge_toml_provider(
1157 figment,
1158 TomlFileProvider::new(Some("FOUNDRY_CONFIG"), root.join(Self::FILE_NAME)),
1159 profile.clone(),
1160 );
1161
1162 figment = figment
1164 .merge(
1165 Env::prefixed("DAPP_")
1166 .ignore(&["REMAPPINGS", "LIBRARIES", "FFI", "FS_PERMISSIONS"])
1167 .global()
1168 .legacy_labels(),
1169 )
1170 .merge(
1171 Env::prefixed("DAPP_TEST_")
1172 .ignore(&["CACHE", "FUZZ_RUNS", "DEPTH", "FFI", "FS_PERMISSIONS"])
1173 .global()
1174 .legacy_labels(),
1175 )
1176 .merge(DappEnvCompatProvider)
1177 .merge(EtherscanEnvProvider::default())
1178 .merge(
1179 Env::prefixed("FOUNDRY_")
1180 .ignore(&["PROFILE", "REMAPPINGS", "LIBRARIES", "FFI", "FS_PERMISSIONS"])
1181 .map(|key| {
1182 let key = key.as_str();
1183 if Self::STANDALONE_SECTIONS.iter().any(|section| {
1184 key.starts_with(&format!("{}_", section.to_ascii_uppercase()))
1185 }) {
1186 key.replacen('_', ".", 1).into()
1187 } else {
1188 key.into()
1189 }
1190 })
1191 .global()
1192 .legacy_labels(),
1193 )
1194 .select(profile.clone());
1195
1196 if providers.is_all() {
1198 let remappings = RemappingsProvider {
1202 auto_detect_remappings: figment
1203 .extract_inner::<bool>("auto_detect_remappings")
1204 .unwrap_or(true),
1205 lib_paths: figment
1206 .extract_inner::<Vec<PathBuf>>("libs")
1207 .map(Cow::Owned)
1208 .unwrap_or_else(|_| Cow::Borrowed(&self.libs)),
1209 root,
1210 remappings: figment.extract_inner::<Vec<Remapping>>("remappings"),
1211 project_paths: [("src", &self.src), ("test", &self.test), ("script", &self.script)]
1212 .into_iter()
1213 .map(|(key, default)| {
1214 figment.extract_inner::<PathBuf>(key).unwrap_or_else(|_| default.clone())
1215 })
1216 .collect(),
1217 include_paths: figment
1218 .extract_inner::<Vec<PathBuf>>("include_paths")
1219 .unwrap_or_else(|_| self.include_paths.clone()),
1220 warnings: match figment.extract_inner::<Vec<Warning>>("__warnings") {
1221 Err(error) if error.missing() => Ok(Vec::new()),
1222 warnings => warnings,
1223 },
1224 };
1225 figment = figment.merge(remappings);
1226 }
1227
1228 let invariant_corpus_random_sequence_weight_configured = self
1229 .invariant
1230 .corpus_random_sequence_weight_configured
1231 || figment
1232 .extract_inner::<bool>("invariant.corpus_random_sequence_weight_configured")
1233 .unwrap_or_else(|_| {
1234 figment_value_is_configured(&figment, "invariant.corpus_random_sequence_weight")
1235 });
1236 let invariant_workers_configured = self.invariant.workers_configured
1237 || figment.extract_inner::<bool>("invariant.workers_configured").unwrap_or_else(|_| {
1238 figment.extract_inner::<InvariantWorkers>("invariant.workers").is_ok()
1239 });
1240
1241 figment = self.normalize_defaults(figment);
1243 if invariant_corpus_random_sequence_weight_configured {
1244 figment = figment.merge(("invariant.corpus_random_sequence_weight_configured", true));
1245 }
1246 if invariant_workers_configured {
1247 figment = figment.merge(("invariant.workers_configured", true));
1248 }
1249
1250 Figment::from(self).merge(figment).select(profile)
1251 }
1252
1253 #[must_use]
1258 pub fn canonic(self) -> Self {
1259 let root = self.root.clone();
1260 self.canonic_at(root)
1261 }
1262
1263 #[must_use]
1281 pub fn canonic_at(mut self, root: impl Into<PathBuf>) -> Self {
1282 let root = canonic(root);
1283
1284 fn p(root: &Path, rem: &Path) -> PathBuf {
1285 canonic(root.join(rem))
1286 }
1287
1288 self.src = p(&root, &self.src);
1289 self.test = p(&root, &self.test);
1290 self.script = p(&root, &self.script);
1291 self.out = p(&root, &self.out);
1292 self.broadcast = p(&root, &self.broadcast);
1293 self.cache_path = p(&root, &self.cache_path);
1294 self.snapshots = p(&root, &self.snapshots);
1295 self.test_failures_file = p(&root, &self.test_failures_file);
1296
1297 if let Some(build_info_path) = self.build_info_path {
1298 self.build_info_path = Some(p(&root, &build_info_path));
1299 }
1300
1301 self.libs = self.libs.into_iter().map(|lib| p(&root, &lib)).collect();
1302
1303 self.remappings = self
1304 .remappings
1305 .into_iter()
1306 .map(|r| relative_remapping_preserving_context_boundary(r.into(), &root))
1307 .collect();
1308
1309 self.allow_paths = self.allow_paths.into_iter().map(|allow| p(&root, &allow)).collect();
1310
1311 self.include_paths = self.include_paths.into_iter().map(|allow| p(&root, &allow)).collect();
1312
1313 self.fs_permissions.join_all(&root);
1314
1315 if let Some(model_checker) = &mut self.model_checker {
1316 model_checker.contracts = std::mem::take(&mut model_checker.contracts)
1317 .into_iter()
1318 .map(|(path, contracts)| {
1319 (format!("{}", p(&root, path.as_ref()).display()), contracts)
1320 })
1321 .collect();
1322 }
1323
1324 self
1325 }
1326
1327 pub fn normalized_evm_version(mut self) -> Self {
1329 self.normalize_evm_version();
1330 self
1331 }
1332
1333 pub const fn normalized_optimizer_settings(mut self) -> Self {
1336 self.normalize_optimizer_settings();
1337 self
1338 }
1339
1340 pub fn normalize_evm_version(&mut self) {
1342 self.evm_version = self.get_normalized_evm_version();
1343 }
1344
1345 pub const fn normalize_optimizer_settings(&mut self) {
1350 match (self.optimizer, self.optimizer_runs) {
1351 (None, None) => {
1353 self.optimizer = Some(false);
1354 self.optimizer_runs = Some(200);
1355 }
1356 (Some(_), None) => self.optimizer_runs = Some(200),
1358 (None, Some(runs)) => self.optimizer = Some(runs > 0),
1360 _ => {}
1361 }
1362 }
1363
1364 pub fn get_normalized_evm_version(&self) -> EvmVersion {
1368 if let Some(SolcReq::Version(version)) = &self.solc
1369 && let Some(evm_version) = self.evm_version.normalize_version_solc(version)
1370 {
1371 return evm_version;
1372 }
1373 self.evm_version
1374 }
1375
1376 #[must_use]
1381 pub fn sanitized(self) -> Self {
1382 let mut config = self.canonic();
1383
1384 config.sanitize_remappings();
1385
1386 config.libs.sort_unstable();
1387 config.libs.dedup();
1388
1389 config
1390 }
1391
1392 #[allow(clippy::missing_const_for_fn)]
1396 pub fn sanitize_remappings(&mut self) {
1397 #[cfg(target_os = "windows")]
1398 {
1399 use path_slash::PathBufExt;
1401 self.remappings.iter_mut().for_each(|r| {
1402 r.path.path = r.path.path.to_slash_lossy().into_owned().into();
1403 });
1404 }
1405 }
1406
1407 pub fn install_lib_dir(&self) -> &Path {
1411 self.libs
1412 .iter()
1413 .find(|p| !p.ends_with("node_modules"))
1414 .map(|p| p.as_path())
1415 .unwrap_or_else(|| Path::new("lib"))
1416 }
1417
1418 pub fn project(&self) -> Result<Project<MultiCompiler>, SolcError> {
1433 self.create_project(self.cache, false)
1434 }
1435
1436 pub fn ephemeral_project(&self) -> Result<Project<MultiCompiler>, SolcError> {
1439 self.create_project(false, true)
1440 }
1441
1442 pub fn solar_project(&self) -> Result<Project<MultiCompiler>, SolcError> {
1446 let ui_testing = std::env::var_os("FOUNDRY_LINT_UI_TESTING").is_some();
1447 let mut project = self.create_project(self.cache && !ui_testing, false)?;
1448 project.update_output_selection(|selection| {
1449 *selection = OutputSelection::common_output_selection(["abi".into()]);
1452 });
1453 Ok(project)
1454 }
1455
1456 fn additional_settings(
1458 &self,
1459 base: &MultiCompilerSettings,
1460 ) -> BTreeMap<String, MultiCompilerSettings> {
1461 let mut map = BTreeMap::new();
1462
1463 for profile in &self.additional_compiler_profiles {
1464 let mut settings = base.clone();
1465 profile.apply(&mut settings);
1466 map.insert(profile.name.clone(), settings);
1467 }
1468
1469 map
1470 }
1471
1472 #[expect(clippy::disallowed_macros)]
1474 fn restrictions(
1475 &self,
1476 paths: &ProjectPathsConfig,
1477 ) -> Result<BTreeMap<PathBuf, RestrictionsWithVersion<MultiCompilerRestrictions>>, SolcError>
1478 {
1479 let mut map: BTreeMap<PathBuf, RestrictionsWithVersion<MultiCompilerRestrictions>> =
1480 BTreeMap::new();
1481 if self.compilation_restrictions.is_empty() {
1482 return Ok(BTreeMap::new());
1483 }
1484
1485 let graph = Graph::<MultiCompilerParser>::resolve(paths)?;
1486 let (sources, _) = graph.into_sources();
1487
1488 for res in &self.compilation_restrictions {
1489 for source in sources.keys().filter(|path| {
1490 if res.paths.is_match(path) {
1491 true
1492 } else if let Ok(path) = path.strip_prefix(&paths.root) {
1493 res.paths.is_match(path)
1494 } else {
1495 false
1496 }
1497 }) {
1498 let res: RestrictionsWithVersion<_> =
1499 res.clone().try_into().map_err(SolcError::msg)?;
1500 if map.contains_key(source) {
1501 let value = map.remove(source.as_path()).unwrap();
1502 if let Some(merged) = value.clone().merge(res) {
1503 map.insert(source.clone(), merged);
1504 } else {
1505 eprintln!(
1507 "{}",
1508 yansi::Paint::yellow(&format!(
1509 "Failed to merge compilation restrictions for {}",
1510 source.display()
1511 ))
1512 );
1513 map.insert(source.clone(), value);
1514 }
1515 } else {
1516 map.insert(source.clone(), res);
1517 }
1518 }
1519 }
1520
1521 Ok(map)
1522 }
1523
1524 pub fn create_project(&self, cached: bool, no_artifacts: bool) -> Result<Project, SolcError> {
1528 let project =
1529 self.create_project_with_compiler(|| self.compiler(), cached, no_artifacts)?;
1530
1531 if self.force {
1532 let _ = self.cleanup(&project);
1535 }
1536
1537 Ok(project)
1538 }
1539
1540 pub fn create_project_with_compiler<C>(
1545 &self,
1546 compiler: impl FnOnce() -> Result<C, SolcError>,
1547 cached: bool,
1548 no_artifacts: bool,
1549 ) -> Result<Project<C>, SolcError>
1550 where
1551 C: Compiler<
1552 Settings = MultiCompilerSettings,
1553 Language = MultiCompilerLanguage,
1554 CompilerContract = Contract,
1555 >,
1556 {
1557 let settings = self.compiler_settings()?;
1558 let paths = self.project_paths();
1559
1560 let parse_path = |path: &PathBuf| path.strip_prefix("./").unwrap_or(path).to_path_buf();
1562
1563 let solar_codes = self.is_solar().then_some(2264);
1568
1569 let mut builder = ProjectBuilder::<C>::default()
1570 .artifacts(self.configured_artifacts_handler())
1571 .additional_settings(self.additional_settings(&settings))
1572 .restrictions(self.restrictions(&paths)?)
1573 .settings(settings)
1574 .paths(paths)
1575 .ignore_error_codes(
1576 self.ignored_error_codes.iter().copied().map(Into::into).chain(solar_codes),
1577 )
1578 .ignore_error_codes_from(self.ignored_error_codes_from.iter().map(|(path, codes)| {
1579 (parse_path(path), codes.iter().copied().map(Into::into).collect())
1580 }))
1581 .ignore_paths(self.ignored_file_paths.iter().map(parse_path).collect())
1582 .set_compiler_severity_filter(if self.deny.warnings() {
1583 Severity::Warning
1584 } else {
1585 Severity::Error
1586 })
1587 .set_offline(self.offline)
1588 .set_cached(cached && !self.deny.warnings())
1589 .set_build_info(!no_artifacts && self.build_info)
1590 .set_no_artifacts(no_artifacts);
1591
1592 if !self.skip.is_empty() {
1593 let filter = SkipBuildFilters::new(self.skip.clone(), self.root.clone());
1594 builder = builder.sparse_output(filter);
1595 }
1596
1597 let project = builder.build(compiler()?)?;
1598
1599 #[cfg(windows)]
1603 let mut project = project;
1604 #[cfg(windows)]
1605 for remapping in &mut project.paths.remappings {
1606 if let Some(context) = &mut remapping.context
1607 && context.ends_with('/')
1608 {
1609 context.pop();
1610 context.push(std::path::MAIN_SEPARATOR);
1611 }
1612 }
1613
1614 Ok(project)
1615 }
1616
1617 pub fn disable_optimizations(&self, project: &mut Project, ir_minimum: bool) {
1619 if ir_minimum {
1620 project.settings.solc.settings = std::mem::take(&mut project.settings.solc.settings)
1623 .with_via_ir_minimum_optimization();
1624
1625 let evm_version = project.settings.solc.evm_version;
1628 let version = self.solc_version().unwrap_or_else(|| Version::new(0, 8, 4));
1629 project.settings.solc.settings.sanitize(&version, SolcLanguage::Solidity);
1630 project.settings.solc.evm_version = evm_version;
1631 } else {
1632 project.settings.solc.optimizer.disable();
1633 project.settings.solc.optimizer.runs = None;
1634 project.settings.solc.optimizer.details = None;
1635 project.settings.solc.via_ir = None;
1636 }
1637 }
1638
1639 pub fn cleanup<C: Compiler, T: ArtifactOutput<CompilerContract = C::CompilerContract>>(
1644 &self,
1645 project: &Project<C, T>,
1646 ) -> Result<Vec<String>, SolcError> {
1647 let mut warnings = Vec::new();
1648
1649 if let Some(coverage_cache) = self.coverage_cache_path()
1650 && coverage_cache.exists()
1651 {
1652 let result = Self::lock_coverage_cache(&coverage_cache)
1653 .and_then(|_lock| fs::remove_dir_all(&coverage_cache));
1654 if let Err(err) = result
1655 && err.kind() != io::ErrorKind::NotFound
1656 {
1657 warnings.push(format!(
1658 "failed to remove coverage cache {}: {err}",
1659 coverage_cache.display()
1660 ));
1661 }
1662 }
1663
1664 let external_cache = self.root.join(&self.cache_path).join("external-compilers");
1665 if let Err(err) = fs::remove_dir_all(&external_cache)
1666 && err.kind() != io::ErrorKind::NotFound
1667 {
1668 warnings.push(format!(
1669 "failed to remove external compiler cache {}: {err}",
1670 external_cache.display()
1671 ));
1672 }
1673
1674 if let Err(err) = project.cleanup() {
1675 warnings.push(format!("failed to clean project artifacts: {err}"));
1676 }
1677
1678 if let Err(err) = fs::remove_file(&self.test_failures_file)
1680 && err.kind() != io::ErrorKind::NotFound
1681 {
1682 warnings.push(format!(
1683 "failed to remove test failures file {}: {err}",
1684 self.test_failures_file.display()
1685 ));
1686 }
1687
1688 let _ = fs::remove_dir_all(project.root().join(&self.mutation_dir));
1690
1691 let mut remove_test_dir = |test_dir: &Option<PathBuf>| {
1693 if let Some(test_dir) = test_dir {
1694 let path = project.root().join(test_dir);
1695 if let Err(err) = fs::remove_dir_all(&path)
1696 && err.kind() != io::ErrorKind::NotFound
1697 {
1698 warnings.push(format!(
1699 "failed to remove test cache directory {}: {err}",
1700 path.display()
1701 ));
1702 }
1703 }
1704 };
1705 remove_test_dir(&self.fuzz.failure_persist_dir);
1706 remove_test_dir(&self.fuzz.corpus.corpus_dir);
1707 remove_test_dir(&self.fuzz.corpus.frontier_dir);
1708 remove_test_dir(&self.invariant.corpus.corpus_dir);
1709 remove_test_dir(&self.invariant.failure_persist_dir);
1710
1711 Ok(warnings)
1712 }
1713
1714 pub const COVERAGE_CACHE_MARKER: &str = ".foundry-coverage-cache";
1716
1717 pub fn coverage_cache_path(&self) -> Option<PathBuf> {
1719 let resolve = |path: PathBuf| {
1722 let existing = path.ancestors().find(|path| path.exists())?;
1723 let suffix = path.strip_prefix(existing).ok()?;
1724 if suffix.components().any(|part| !matches!(part, Component::Normal(_))) {
1725 return None;
1726 }
1727 let path = canonicalize(existing).ok()?.join(suffix);
1728 #[cfg(windows)]
1729 let path = PathBuf::from(path.to_slash_lossy().as_ref());
1730 Some(path)
1731 };
1732 let root = resolve(self.root.clone())?;
1733 let cache = resolve(self.root.join(&self.cache_path).join("coverage"))?;
1734 if root.starts_with(&cache) {
1735 return None;
1736 }
1737 for path in [&self.src, &self.test, &self.script, &self.out]
1738 .into_iter()
1739 .chain(&self.libs)
1740 .chain(&self.build_info_path)
1741 {
1742 let path = resolve(self.root.join(path))?;
1743 if path.starts_with(&cache) || cache.starts_with(path) {
1744 return None;
1745 }
1746 }
1747 if cache.exists() && !cache.join(Self::COVERAGE_CACHE_MARKER).is_file() {
1748 return None;
1749 }
1750 Some(cache)
1751 }
1752
1753 pub fn lock_coverage_cache(path: &Path) -> io::Result<fs::File> {
1758 let lock = fs::OpenOptions::new()
1759 .read(true)
1760 .write(true)
1761 .create(true)
1762 .truncate(false)
1763 .open(path.with_extension("lock"))?;
1764 lock.try_lock()?;
1765 Ok(lock)
1766 }
1767
1768 fn ensure_solc(&self) -> Result<Option<Solc>, SolcError> {
1778 if let Some(solc) = &self.solc {
1779 let solc = match solc {
1780 SolcReq::Version(version) => {
1781 if let Some(solc) = Solc::find_svm_installed_version(version)? {
1782 solc
1783 } else {
1784 if self.offline {
1785 return Err(SolcError::msg(format!(
1786 "can't install missing solc {version} in offline mode"
1787 )));
1788 }
1789 Solc::blocking_install(version)?
1790 }
1791 }
1792 SolcReq::Solar(version) => {
1793 if let Some(solar) = Solc::find_installed_solar(version) {
1794 solar
1795 } else {
1796 if self.offline {
1797 return Err(SolcError::msg(format!(
1798 "can't install missing solar {version} in offline mode"
1799 )));
1800 }
1801 Solc::blocking_install_solar(version)?
1802 }
1803 }
1804 SolcReq::Local(solc) => Solc::new(resolve_solc_path(solc)?)?,
1805 };
1806 return Ok(Some(solc));
1807 }
1808
1809 Ok(None)
1810 }
1811
1812 pub fn evm_spec_id<SPEC: FromEvmVersion>(&self) -> SPEC {
1814 self.hardfork.map(Into::into).unwrap_or_else(|| evm_spec_id(self.evm_version))
1815 }
1816
1817 pub const fn is_auto_detect(&self) -> bool {
1822 if self.solc.is_some() {
1823 return false;
1824 }
1825 self.auto_detect_solc
1826 }
1827
1828 pub fn enable_caching(&self, endpoint: &str, chain_id: impl Into<u64>) -> bool {
1830 !self.no_storage_caching
1831 && self.rpc_storage_caching.enable_for_chain_id(chain_id.into())
1832 && self.rpc_storage_caching.enable_for_endpoint(endpoint)
1833 }
1834
1835 pub fn project_paths<L>(&self) -> ProjectPathsConfig<L> {
1850 let mut builder = ProjectPathsConfig::builder()
1851 .cache(self.cache_path.join(SOLIDITY_FILES_CACHE_FILENAME))
1852 .sources(&self.src)
1853 .tests(&self.test)
1854 .scripts(&self.script)
1855 .artifacts(&self.out)
1856 .libs(self.libs.iter())
1857 .remappings(self.project_remappings())
1858 .allowed_path(&self.root)
1859 .allowed_paths(&self.libs)
1860 .allowed_paths(&self.allow_paths)
1861 .include_paths(&self.include_paths);
1862
1863 if let Some(build_info_path) = &self.build_info_path {
1864 builder = builder.build_infos(build_info_path);
1865 }
1866
1867 builder.build_with_root(&self.root)
1868 }
1869
1870 pub fn solc_compiler(&self) -> Result<SolcCompiler, SolcError> {
1872 if let Some(mut solc) = self.ensure_solc()? {
1873 self.forward_solar_threads(&mut solc);
1874 Ok(SolcCompiler::Specific(solc))
1875 } else {
1876 Ok(SolcCompiler::AutoDetect)
1877 }
1878 }
1879
1880 fn forward_solar_threads(&self, solc: &mut Solc) {
1885 if solc.solar_version().is_none() {
1886 return;
1887 }
1888 let is_threads_arg = |arg: &str| {
1889 arg.starts_with("--threads") || arg.starts_with("--jobs") || arg.starts_with("-j")
1890 };
1891 if solc.extra_args.iter().chain(&self.extra_args).any(|arg| is_threads_arg(arg)) {
1892 return;
1893 }
1894 solc.extra_args.push(format!("--threads={}", rayon::current_num_threads()));
1895 }
1896
1897 pub fn is_solar(&self) -> bool {
1900 matches!(self.solc, Some(SolcReq::Solar(_)))
1901 || self.solc_version().is_some_and(|version| version.build.as_str().contains("solar"))
1902 }
1903
1904 pub fn solc_version(&self) -> Option<Version> {
1906 self.solc.as_ref().and_then(|solc| solc.try_version().ok())
1907 }
1908
1909 pub fn vyper_compiler(&self) -> Result<Option<Vyper>, SolcError> {
1911 if !self.project_paths::<VyperLanguage>().has_input_files() {
1913 return Ok(None);
1914 }
1915 let vyper = if let Some(path) = &self.vyper.path {
1916 Some(Vyper::new(path)?)
1917 } else {
1918 Vyper::new("vyper").ok()
1919 };
1920 Ok(vyper)
1921 }
1922
1923 pub fn compiler(&self) -> Result<MultiCompiler, SolcError> {
1925 Ok(MultiCompiler { solc: Some(self.solc_compiler()?), vyper: self.vyper_compiler()? })
1926 }
1927
1928 pub fn compiler_settings(&self) -> Result<MultiCompilerSettings, SolcError> {
1930 Ok(MultiCompilerSettings { solc: self.solc_settings()?, vyper: self.vyper_settings()? })
1931 }
1932
1933 pub fn get_all_remappings(&self) -> impl Iterator<Item = Remapping> + '_ {
1935 self.remappings.iter().map(|m| m.clone().into())
1936 }
1937
1938 fn project_remappings(&self) -> Vec<Remapping> {
1940 let remappings = self.get_all_remappings().collect::<Vec<_>>();
1941 let mut adjusted = Vec::with_capacity(remappings.len());
1942
1943 for remapping in &remappings {
1948 adjusted.push(remapping.clone());
1949
1950 let Some(context) = remapping.context.as_deref() else { continue };
1951 if Path::new(context).is_absolute() {
1952 continue;
1953 }
1954 let Ok(context_path) = foundry_compilers::utils::normalize_solidity_import_path(
1955 &self.root,
1956 Path::new(context),
1957 ) else {
1958 continue;
1959 };
1960 #[cfg(windows)]
1964 let context_path = PathBuf::from_slash(context_path.to_string_lossy());
1965 if context_path.starts_with(&self.root) {
1966 continue;
1967 }
1968 let mut context_path = context_path.display().to_string();
1969 if context.ends_with(['/', '\\']) && !context_path.ends_with(['/', '\\']) {
1970 context_path.push(std::path::MAIN_SEPARATOR);
1971 }
1972
1973 let mut absolute = remapping.clone();
1974 absolute.context = Some(context_path);
1975 if !remappings.contains(&absolute) && !adjusted.contains(&absolute) {
1976 adjusted.push(absolute);
1977 }
1978 }
1979 adjusted
1980 }
1981
1982 pub fn get_rpc_jwt_secret(&self) -> Result<Option<Cow<'_, str>>, UnresolvedEnvVarError> {
1997 Ok(self.eth_rpc_jwt.as_ref().map(|jwt| Cow::Borrowed(jwt.as_str())))
1998 }
1999
2000 pub fn get_rpc_url(&self) -> Option<Result<Cow<'_, str>, UnresolvedEnvVarError>> {
2016 let maybe_alias = self.eth_rpc_url.as_deref()?;
2017 if let Some(alias) = self.get_rpc_url_with_alias(maybe_alias) {
2018 Some(alias)
2019 } else {
2020 Some(Ok(Cow::Borrowed(self.eth_rpc_url.as_deref()?)))
2021 }
2022 }
2023
2024 pub fn get_rpc_url_with_alias(
2049 &self,
2050 maybe_alias: &str,
2051 ) -> Option<Result<Cow<'_, str>, UnresolvedEnvVarError>> {
2052 let mut endpoints = self.rpc_endpoints.clone().resolved();
2053 if let Some(endpoint) = endpoints.remove(maybe_alias) {
2054 return Some(endpoint.url().map(Cow::Owned));
2055 }
2056
2057 if let Some(mesc_url) = self.get_rpc_url_from_mesc(maybe_alias) {
2058 return Some(Ok(Cow::Owned(mesc_url)));
2059 }
2060
2061 if let Some(builtin) = crate::endpoints::builtin_rpc_url(maybe_alias) {
2062 return Some(Ok(Cow::Borrowed(builtin)));
2063 }
2064
2065 None
2066 }
2067
2068 pub fn get_rpc_url_from_mesc(&self, maybe_alias: &str) -> Option<String> {
2070 let mesc_config = mesc::load::load_config_data()
2073 .inspect_err(|err| debug!(%err, "failed to load mesc config"))
2074 .ok()?;
2075
2076 if let Ok(Some(endpoint)) =
2077 mesc::query::get_endpoint_by_query(&mesc_config, maybe_alias, Some("foundry"))
2078 {
2079 return Some(endpoint.url);
2080 }
2081
2082 if maybe_alias.chars().all(|c| c.is_numeric()) {
2083 if let Ok(Some(endpoint)) =
2089 mesc::query::get_endpoint_by_network(&mesc_config, maybe_alias, Some("foundry"))
2090 {
2091 return Some(endpoint.url);
2092 }
2093 }
2094
2095 None
2096 }
2097
2098 pub fn get_rpc_url_or<'a>(
2110 &'a self,
2111 fallback: impl Into<Cow<'a, str>>,
2112 ) -> Result<Cow<'a, str>, UnresolvedEnvVarError> {
2113 self.get_rpc_url().unwrap_or_else(|| Ok(fallback.into()))
2114 }
2115
2116 pub fn get_rpc_url_or_localhost_http(&self) -> Result<Cow<'_, str>, UnresolvedEnvVarError> {
2128 self.get_rpc_url_or("http://localhost:8545")
2129 }
2130
2131 pub fn get_etherscan_config(
2151 &self,
2152 ) -> Option<Result<ResolvedEtherscanConfig, EtherscanConfigError>> {
2153 self.get_etherscan_config_with_chain(None).transpose()
2154 }
2155
2156 pub fn get_etherscan_config_with_chain(
2163 &self,
2164 chain: Option<Chain>,
2165 ) -> Result<Option<ResolvedEtherscanConfig>, EtherscanConfigError> {
2166 self.etherscan.resolve_for(
2167 self.etherscan_alias(),
2168 self.etherscan_api_key.as_deref(),
2169 chain.or(self.chain),
2170 )
2171 }
2172
2173 pub fn etherscan_alias(&self) -> Option<&str> {
2175 self.etherscan_api_key.as_deref().or(self.eth_rpc_url.as_deref())
2176 }
2177
2178 #[expect(clippy::disallowed_macros)]
2184 pub fn get_etherscan_api_key(&self, chain: Option<Chain>) -> Option<String> {
2185 self.get_etherscan_config_with_chain(chain)
2186 .map_err(|e| {
2187 eprintln!(
2189 "{}: failed getting etherscan config: {e}",
2190 yansi::Paint::yellow("Warning"),
2191 );
2192 })
2193 .ok()
2194 .flatten()
2195 .map(|c| c.key)
2196 }
2197
2198 pub fn get_source_dir_remapping(&self) -> Option<Remapping> {
2205 get_dir_remapping(&self.src)
2206 }
2207
2208 pub fn get_test_dir_remapping(&self) -> Option<Remapping> {
2210 if self.root.join(&self.test).exists() { get_dir_remapping(&self.test) } else { None }
2211 }
2212
2213 pub fn get_script_dir_remapping(&self) -> Option<Remapping> {
2215 if self.root.join(&self.script).exists() { get_dir_remapping(&self.script) } else { None }
2216 }
2217
2218 pub fn optimizer(&self) -> Optimizer {
2224 Optimizer {
2225 enabled: self.optimizer,
2226 runs: self.optimizer_runs,
2227 details: self.optimizer_details.clone(),
2230 }
2231 }
2232
2233 pub fn configured_artifacts_handler(&self) -> ConfigurableArtifacts {
2236 let mut extra_output = self.extra_output.clone();
2237
2238 if !extra_output.contains(&ContractOutputSelection::Metadata) {
2244 extra_output.push(ContractOutputSelection::Metadata);
2245 }
2246
2247 ConfigurableArtifacts::new(extra_output, self.extra_output_files.iter().copied())
2248 }
2249
2250 pub fn parsed_libraries(&self) -> Result<Libraries, SolcError> {
2253 Libraries::parse(&self.libraries)
2254 }
2255
2256 pub fn libraries_with_remappings(&self) -> Result<Libraries, SolcError> {
2258 let paths: ProjectPathsConfig = self.project_paths();
2259 Ok(self.parsed_libraries()?.apply(|libs| paths.apply_lib_remappings(libs)))
2260 }
2261
2262 pub fn solc_settings(&self) -> Result<SolcSettings, SolcError> {
2267 let mut model_checker = self.model_checker.clone();
2271 if let Some(model_checker_settings) = &mut model_checker
2272 && model_checker_settings.targets.is_none()
2273 {
2274 model_checker_settings.targets = Some(vec![ModelCheckerTarget::Assert]);
2275 }
2276
2277 let mut libraries = self.libraries_with_remappings()?;
2280 if !self.allow_linked_libraries {
2281 libraries.libs.clear();
2282 }
2283
2284 let mut settings = Settings {
2285 libraries,
2286 optimizer: self.optimizer(),
2287 evm_version: Some(self.evm_version),
2288 metadata: Some(SettingsMetadata {
2289 use_literal_content: Some(self.use_literal_content),
2290 bytecode_hash: Some(self.bytecode_hash),
2291 cbor_metadata: Some(self.cbor_metadata),
2292 }),
2293 debug: self.revert_strings.map(|revert_strings| DebuggingSettings {
2294 revert_strings: Some(revert_strings),
2295 debug_info: Vec::new(),
2297 }),
2298 model_checker,
2299 via_ir: Some(self.via_ir || self.via_ssa_cfg),
2302 via_ssa_cfg: Some(self.via_ssa_cfg),
2303 experimental: Some(self.experimental),
2304 stop_after: None,
2306 remappings: Vec::new(),
2308 output_selection: Default::default(),
2310 }
2311 .with_extra_output(self.configured_artifacts_handler().output_selection());
2312
2313 if self.ast || (self.build_info && !self.build_info_without_ast) {
2315 settings = settings.with_ast();
2316 }
2317
2318 let cli_settings =
2319 CliSettings { extra_args: self.extra_args.clone(), ..Default::default() };
2320
2321 Ok(SolcSettings { settings, cli_settings })
2322 }
2323
2324 pub fn enable_debug_build_info(&mut self) -> eyre::Result<()> {
2333 if self.build_info {
2334 return Ok(());
2335 }
2336 self.build_info = true;
2337 self.build_info_without_ast = true;
2338 if !self.dynamic_test_linking {
2339 return Ok(());
2340 }
2341 let paths = self.project_paths::<MultiCompilerLanguage>();
2342 let without_input = fs::read_dir(&paths.build_infos)
2343 .into_iter()
2344 .flatten()
2345 .flatten()
2346 .map(|entry| entry.path())
2347 .filter(|path| {
2348 path.extension().is_some_and(|extension| extension == "json")
2349 && matches!(read_build_info_input::<Present>(path), Ok(None))
2350 })
2351 .filter_map(|path| Some(path.file_stem()?.to_str()?.to_string()))
2352 .collect::<HashSet<_>>();
2353 if without_input.is_empty() || !paths.cache.exists() {
2354 return Ok(());
2355 }
2356 let mut cache = serde_json::from_slice::<serde_json::Value>(&fs::read(&paths.cache)?)?;
2357 let Some(files) = cache.get_mut("files").and_then(|files| files.as_object_mut()) else {
2358 return Ok(());
2359 };
2360 fn values(value: &serde_json::Value) -> impl Iterator<Item = &serde_json::Value> {
2361 value.as_object().into_iter().flat_map(|map| map.values())
2362 }
2363 let len = files.len();
2364 files.retain(|file, entry| {
2365 let file = self.root.join(file);
2366 !((file.starts_with(&self.test) || file.starts_with(&self.script))
2368 && values(&entry["artifacts"]).flat_map(values).flat_map(values).any(|artifact| {
2369 artifact["build_id"].as_str().is_some_and(|id| without_input.contains(id))
2370 }))
2371 });
2372 if files.len() == len {
2373 return Ok(());
2374 }
2375 let temp = paths.cache.with_extension("json.tmp");
2377 fs::write(&temp, serde_json::to_vec(&cache)?)
2378 .and_then(|()| fs::rename(&temp, &paths.cache))
2379 .wrap_err_with(|| format!("failed to write {}", paths.cache.display()))
2380 }
2381
2382 pub fn vyper_settings(&self) -> Result<VyperSettings, SolcError> {
2385 let optimize = if self.vyper.opt_level.is_some() { None } else { self.vyper.optimize };
2388
2389 Ok(VyperSettings {
2390 evm_version: Some(self.evm_version),
2391 optimize,
2392 opt_level: self.vyper.opt_level,
2393 bytecode_metadata: None,
2394 output_selection: OutputSelection::common_output_selection([
2397 "abi".to_string(),
2398 "evm.bytecode".to_string(),
2399 "evm.deployedBytecode".to_string(),
2400 ]),
2401 search_paths: None,
2402 experimental_codegen: self.vyper.experimental_codegen,
2403 debug: self.vyper.debug,
2404 enable_decimals: self.vyper.enable_decimals,
2405 venom_experimental: self.vyper.venom_experimental,
2406 venom: self.vyper.venom.clone(),
2407 })
2408 }
2409
2410 pub fn figment() -> Figment {
2431 Self::default().into()
2432 }
2433
2434 pub fn figment_with_root(root: impl AsRef<Path>) -> Figment {
2446 Self::with_root(root.as_ref()).into()
2447 }
2448
2449 pub fn current_project_figment(providers: FigmentProviders) -> Figment {
2454 match find_project_root(None) {
2455 Ok(root) => Self::with_root(&root).to_figment(providers),
2456 Err(err) => Figment::from(ProjectRootErrorProvider(err)),
2457 }
2458 }
2459
2460 #[doc(hidden)]
2461 #[track_caller]
2462 pub fn figment_with_root_opt(root: Option<&Path>) -> Figment {
2463 let root = match root {
2464 Some(root) => root,
2465 None => &find_project_root(None).expect("could not determine project root"),
2466 };
2467 Self::figment_with_root(root)
2468 }
2469
2470 pub fn with_root(root: impl AsRef<Path>) -> Self {
2479 Self::_with_root(root.as_ref())
2480 }
2481
2482 fn _with_root(root: &Path) -> Self {
2483 let paths = ProjectPathsConfig::builder()
2485 .remappings(Vec::new())
2489 .build_with_root::<()>(root);
2490 let artifacts: PathBuf = paths.artifacts.file_name().unwrap().into();
2491 let mut config = Self::default();
2492 if config.uses_default_src() {
2493 config.src = paths.sources.file_name().unwrap().into();
2494 }
2495 config.root = paths.root;
2496 config.out = artifacts.clone();
2497 config.libs =
2498 paths.libraries.into_iter().map(|lib| lib.file_name().unwrap().into()).collect();
2499 config.fs_permissions = FsPermissions::new([PathPermission::read(artifacts)]);
2500 config
2501 }
2502
2503 pub fn hardhat() -> Self {
2505 Self {
2506 src: "contracts".into(),
2507 out: "artifacts".into(),
2508 libs: vec!["node_modules".into()],
2509 ..Self::default()
2510 }
2511 }
2512
2513 pub fn into_basic(self) -> BasicConfig {
2522 BasicConfig {
2523 profile: self.profile,
2524 src: self.src,
2525 out: self.out,
2526 libs: self.libs,
2527 remappings: self.remappings,
2528 network: self.networks.resolved_network().map(|network| network.name().to_string()),
2529 }
2530 }
2531
2532 pub fn update_at<F>(root: &Path, f: F) -> eyre::Result<()>
2537 where
2538 F: FnOnce(&Self, &mut toml_edit::DocumentMut) -> bool,
2539 {
2540 let config = Self::load_with_root(root)?.sanitized();
2541 config.update(|doc| f(&config, doc))
2542 }
2543
2544 pub fn update<F>(&self, f: F) -> eyre::Result<()>
2549 where
2550 F: FnOnce(&mut toml_edit::DocumentMut) -> bool,
2551 {
2552 let file_path = self.get_config_path();
2553 if !file_path.exists() {
2554 return Ok(());
2555 }
2556 let contents = fs::read_to_string(&file_path)?;
2557 let mut doc = contents.parse::<toml_edit::DocumentMut>()?;
2558 if f(&mut doc) {
2559 fs::write(file_path, doc.to_string())?;
2560 }
2561 Ok(())
2562 }
2563
2564 pub fn update_libs(&self) -> eyre::Result<()> {
2570 self.update(|doc| {
2571 let profile = self.profile.as_str().as_str();
2572 let root = &self.root;
2573 let libs: toml_edit::Value = self
2574 .libs
2575 .iter()
2576 .map(|path| {
2577 let path =
2578 if let Ok(relative) = path.strip_prefix(root) { relative } else { path };
2579 toml_edit::Value::from(&*path.to_string_lossy())
2580 })
2581 .collect();
2582 let libs = toml_edit::value(libs);
2583 doc[Self::PROFILE_SECTION][profile]["libs"] = libs;
2584 true
2585 })
2586 }
2587
2588 pub fn to_string_pretty(&self) -> Result<String, toml::ser::Error> {
2600 let mut value = toml::Value::try_from(self)?;
2602 let value_table = value.as_table_mut().unwrap();
2604 let standalone_sections = Self::STANDALONE_SECTIONS
2606 .iter()
2607 .filter_map(|section| {
2608 let section = section.to_string();
2609 value_table.remove(§ion).map(|value| (section, value))
2610 })
2611 .collect::<Vec<_>>();
2612 let mut wrapping_table = [(
2614 Self::PROFILE_SECTION.into(),
2615 toml::Value::Table([(self.profile.to_string(), value)].into_iter().collect()),
2616 )]
2617 .into_iter()
2618 .collect::<toml::map::Map<_, _>>();
2619 for (section, value) in standalone_sections {
2621 wrapping_table.insert(section, value);
2622 }
2623 toml::to_string_pretty(&toml::Value::Table(wrapping_table))
2625 }
2626
2627 pub fn get_config_path(&self) -> PathBuf {
2629 self.root.join(Self::FILE_NAME)
2630 }
2631
2632 pub fn selected_profile() -> Profile {
2636 #[cfg(test)]
2638 {
2639 Self::force_selected_profile()
2640 }
2641 #[cfg(not(test))]
2642 {
2643 SELECTED_PROFILE.get_or_init(Self::force_selected_profile).clone()
2644 }
2645 }
2646
2647 pub fn try_set_selected_profile(profile: Profile) -> Result<(), Profile> {
2651 #[cfg(test)]
2652 {
2653 let _ = profile;
2654 Ok(())
2655 }
2656 #[cfg(not(test))]
2657 {
2658 match SELECTED_PROFILE.set(profile) {
2659 Ok(()) => Ok(()),
2660 Err(profile) if SELECTED_PROFILE.get() == Some(&profile) => Ok(()),
2661 Err(_) => Err(SELECTED_PROFILE.get().expect("profile initialized").clone()),
2662 }
2663 }
2664 }
2665
2666 fn force_selected_profile() -> Profile {
2667 Profile::from_env_or("FOUNDRY_PROFILE", Self::DEFAULT_PROFILE)
2668 }
2669
2670 pub fn foundry_dir_toml() -> Option<PathBuf> {
2672 Self::foundry_dir().map(|p| p.join(Self::FILE_NAME))
2673 }
2674
2675 pub fn foundry_dir() -> Option<PathBuf> {
2677 dirs::home_dir().map(|p| p.join(Self::FOUNDRY_DIR_NAME))
2678 }
2679
2680 pub fn foundry_cache_dir() -> Option<PathBuf> {
2682 Self::foundry_dir().map(|p| p.join("cache"))
2683 }
2684
2685 pub fn foundry_rpc_cache_dir() -> Option<PathBuf> {
2687 Some(Self::foundry_cache_dir()?.join("rpc"))
2688 }
2689 pub fn foundry_chain_cache_dir(chain_id: impl Into<Chain>) -> Option<PathBuf> {
2691 Some(Self::foundry_rpc_cache_dir()?.join(chain_id.into().to_string()))
2692 }
2693
2694 pub fn foundry_etherscan_cache_dir() -> Option<PathBuf> {
2696 Some(Self::foundry_cache_dir()?.join("etherscan"))
2697 }
2698
2699 pub fn foundry_keystores_dir() -> Option<PathBuf> {
2701 Some(Self::foundry_dir()?.join("keystores"))
2702 }
2703
2704 pub fn foundry_etherscan_chain_cache_dir(chain_id: impl Into<Chain>) -> Option<PathBuf> {
2707 Some(Self::foundry_etherscan_cache_dir()?.join(chain_id.into().to_string()))
2708 }
2709
2710 pub fn foundry_block_cache_dir(chain_id: impl Into<Chain>, block: u64) -> Option<PathBuf> {
2713 Some(Self::foundry_chain_cache_dir(chain_id)?.join(format!("{block}")))
2714 }
2715
2716 pub fn foundry_block_cache_file(chain_id: impl Into<Chain>, block: u64) -> Option<PathBuf> {
2719 Some(Self::foundry_block_cache_dir(chain_id, block)?.join("storage.json"))
2720 }
2721
2722 pub fn data_dir() -> eyre::Result<PathBuf> {
2730 let path = dirs::data_dir().wrap_err("Failed to find data directory")?.join("foundry");
2731 std::fs::create_dir_all(&path).wrap_err("Failed to create module directory")?;
2732 Ok(path)
2733 }
2734
2735 pub fn find_config_file() -> Option<PathBuf> {
2742 fn find(path: &Path) -> Option<PathBuf> {
2743 if path.is_absolute() {
2744 return match path.is_file() {
2745 true => Some(path.to_path_buf()),
2746 false => None,
2747 };
2748 }
2749 let cwd = std::env::current_dir().ok()?;
2750 let mut cwd = cwd.as_path();
2751 loop {
2752 let file_path = cwd.join(path);
2753 if file_path.is_file() {
2754 return Some(file_path);
2755 }
2756 cwd = cwd.parent()?;
2757 }
2758 }
2759 find(Env::var_or("FOUNDRY_CONFIG", Self::FILE_NAME).as_ref())
2760 .or_else(|| Self::foundry_dir_toml().filter(|p| p.exists()))
2761 }
2762
2763 pub fn clean_foundry_cache() -> eyre::Result<Vec<String>> {
2767 if let Some(cache_dir) = Self::foundry_cache_dir() {
2768 let path = cache_dir.as_path();
2769 if let Err(err) = fs::remove_dir_all(path)
2770 && err.kind() != io::ErrorKind::NotFound
2771 {
2772 return Ok(vec![format!(
2773 "failed to remove foundry cache at {}: {err}",
2774 path.display()
2775 )]);
2776 }
2777 } else {
2778 eyre::bail!("failed to get foundry_cache_dir");
2779 }
2780
2781 Ok(vec![])
2782 }
2783
2784 pub fn clean_foundry_chain_cache(chain: Chain) -> eyre::Result<Vec<String>> {
2788 if let Some(cache_dir) = Self::foundry_chain_cache_dir(chain) {
2789 let path = cache_dir.as_path();
2790 if let Err(err) = fs::remove_dir_all(path)
2791 && err.kind() != io::ErrorKind::NotFound
2792 {
2793 return Ok(vec![format!(
2794 "failed to remove foundry cache for chain {chain} at {}: {err}",
2795 path.display()
2796 )]);
2797 }
2798 } else {
2799 eyre::bail!("failed to get foundry_chain_cache_dir");
2800 }
2801
2802 Ok(vec![])
2803 }
2804
2805 pub fn clean_foundry_block_cache(chain: Chain, block: u64) -> eyre::Result<Vec<String>> {
2809 if let Some(cache_dir) = Self::foundry_block_cache_dir(chain, block) {
2810 let path = cache_dir.as_path();
2811 if let Err(err) = fs::remove_dir_all(path)
2812 && err.kind() != io::ErrorKind::NotFound
2813 {
2814 return Ok(vec![format!(
2815 "failed to remove foundry cache for chain {chain} block {block} at {}: {err}",
2816 path.display()
2817 )]);
2818 }
2819 } else {
2820 eyre::bail!("failed to get foundry_block_cache_dir");
2821 }
2822
2823 Ok(vec![])
2824 }
2825
2826 pub fn clean_foundry_etherscan_cache() -> eyre::Result<Vec<String>> {
2830 if let Some(cache_dir) = Self::foundry_etherscan_cache_dir() {
2831 let path = cache_dir.as_path();
2832 if let Err(err) = fs::remove_dir_all(path)
2833 && err.kind() != io::ErrorKind::NotFound
2834 {
2835 return Ok(vec![format!(
2836 "failed to remove foundry etherscan cache at {}: {err}",
2837 path.display()
2838 )]);
2839 }
2840 } else {
2841 eyre::bail!("failed to get foundry_etherscan_cache_dir");
2842 }
2843
2844 Ok(vec![])
2845 }
2846
2847 pub fn clean_foundry_etherscan_chain_cache(chain: Chain) -> eyre::Result<Vec<String>> {
2851 if let Some(cache_dir) = Self::foundry_etherscan_chain_cache_dir(chain) {
2852 let path = cache_dir.as_path();
2853 if let Err(err) = fs::remove_dir_all(path)
2854 && err.kind() != io::ErrorKind::NotFound
2855 {
2856 return Ok(vec![format!(
2857 "failed to remove foundry etherscan cache for chain {chain} at {}: {err}",
2858 path.display()
2859 )]);
2860 }
2861 } else {
2862 eyre::bail!("failed to get foundry_etherscan_cache_dir for chain: {}", chain);
2863 }
2864
2865 Ok(vec![])
2866 }
2867
2868 pub fn list_foundry_cache() -> eyre::Result<Cache> {
2870 if let Some(cache_dir) = Self::foundry_rpc_cache_dir() {
2871 let mut cache = Cache { chains: vec![] };
2872 let Some(entries) = Self::ignore_not_found(cache_dir.read_dir())? else {
2873 return Ok(cache);
2874 };
2875 for entry in entries {
2876 let Some(entry) = Self::ignore_not_found(entry)? else {
2877 continue;
2878 };
2879 let Some(metadata) = Self::ignore_not_found(fs::metadata(entry.path()))? else {
2880 continue;
2881 };
2882 if !metadata.is_dir() {
2883 continue;
2884 }
2885 if let Ok(chain) = Chain::from_str(&entry.file_name().to_string_lossy()) {
2886 cache.chains.push(Self::list_foundry_chain_cache(chain)?);
2887 }
2888 }
2889 Ok(cache)
2890 } else {
2891 eyre::bail!("failed to get foundry_cache_dir");
2892 }
2893 }
2894
2895 pub fn list_foundry_chain_cache(chain: Chain) -> eyre::Result<ChainCache> {
2897 let block_explorer_data_size = match Self::foundry_etherscan_chain_cache_dir(chain) {
2898 Some(cache_dir) => Self::get_cached_block_explorer_data(&cache_dir)?,
2899 None => {
2900 warn!("failed to access foundry_etherscan_chain_cache_dir");
2901 0
2902 }
2903 };
2904
2905 if let Some(cache_dir) = Self::foundry_chain_cache_dir(chain) {
2906 let blocks = Self::get_cached_blocks(&cache_dir)?;
2907 Ok(ChainCache {
2908 name: chain.to_string(),
2909 blocks,
2910 block_explorer: block_explorer_data_size,
2911 })
2912 } else {
2913 eyre::bail!("failed to get foundry_chain_cache_dir");
2914 }
2915 }
2916
2917 fn get_cached_blocks(chain_path: &Path) -> eyre::Result<Vec<(String, u64)>> {
2919 let mut blocks = vec![];
2920 let Some(entries) = Self::ignore_not_found(chain_path.read_dir())? else {
2921 return Ok(blocks);
2922 };
2923 for block in entries {
2924 let Some(block) = Self::ignore_not_found(block)? else {
2925 continue;
2926 };
2927 if let Some(block) = Self::get_cached_block(block)? {
2928 blocks.push(block);
2929 }
2930 }
2931 Ok(blocks)
2932 }
2933
2934 fn get_cached_block(block: fs::DirEntry) -> eyre::Result<Option<(String, u64)>> {
2935 let file_name = block.file_name();
2936 let Some(metadata) = Self::ignore_not_found(fs::symlink_metadata(block.path()))? else {
2937 return Ok(None);
2938 };
2939 let size = if metadata.is_dir() {
2940 let Some(cache_files) = Self::ignore_not_found(block.path().read_dir())? else {
2941 return Ok(None);
2942 };
2943 let mut size = 0;
2944 for cache_file in cache_files {
2945 let Some(cache_file) = Self::ignore_not_found(cache_file)? else {
2946 continue;
2947 };
2948 size += Self::get_cache_file_size(cache_file)?.unwrap_or_default();
2949 }
2950 if size == 0 {
2951 return Ok(None);
2952 }
2953 size
2954 } else if metadata.is_file() && file_name.to_string_lossy().chars().all(char::is_numeric) {
2955 metadata.len()
2956 } else {
2957 return Ok(None);
2958 };
2959 Ok(Some((file_name.to_string_lossy().into_owned(), size)))
2960 }
2961
2962 fn get_cache_file_size(cache_file: fs::DirEntry) -> eyre::Result<Option<u64>> {
2963 let Some(metadata) = Self::ignore_not_found(fs::symlink_metadata(cache_file.path()))?
2964 else {
2965 return Ok(None);
2966 };
2967 let cache_file_name = cache_file.file_name();
2968 let cache_file_name = cache_file_name.to_string_lossy();
2969 if !metadata.is_file()
2970 || (cache_file_name != "storage.json"
2971 && !cache_file_name
2972 .strip_prefix("storage-")
2973 .and_then(|name| name.strip_suffix(".json"))
2974 .is_some_and(|hash| {
2975 hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit())
2976 }))
2977 {
2978 return Ok(None);
2979 }
2980 Ok(Some(metadata.len()))
2981 }
2982
2983 fn get_cached_block_explorer_data(chain_path: &Path) -> eyre::Result<u64> {
2985 let Some(entries) = Self::ignore_not_found(fs::read_dir(chain_path))? else {
2986 return Ok(0);
2987 };
2988 Self::get_cached_dir_size(entries)
2989 }
2990
2991 fn get_cached_dir_size(entries: fs::ReadDir) -> eyre::Result<u64> {
2992 let mut size = 0;
2993 for entry in entries {
2994 let Some(entry) = Self::ignore_not_found(entry)? else {
2995 continue;
2996 };
2997 size += Self::get_cached_entry_size(entry)?.unwrap_or_default();
2998 }
2999 Ok(size)
3000 }
3001
3002 fn get_cached_entry_size(entry: fs::DirEntry) -> eyre::Result<Option<u64>> {
3003 let Some(metadata) = Self::ignore_not_found(fs::symlink_metadata(entry.path()))? else {
3004 return Ok(None);
3005 };
3006 if metadata.is_dir() {
3007 let Some(entries) = Self::ignore_not_found(fs::read_dir(entry.path()))? else {
3008 return Ok(None);
3009 };
3010 Ok(Some(Self::get_cached_dir_size(entries)?))
3011 } else {
3012 Ok(Some(metadata.len()))
3013 }
3014 }
3015
3016 fn ignore_not_found<T>(result: io::Result<T>) -> eyre::Result<Option<T>> {
3018 match result {
3019 Ok(value) => Ok(Some(value)),
3020 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
3021 Err(err) => Err(err.into()),
3022 }
3023 }
3024
3025 fn merge_toml_provider(
3026 mut figment: Figment,
3027 toml_provider: impl Provider,
3028 profile: Profile,
3029 ) -> Figment {
3030 figment = figment.select(profile.clone());
3031
3032 figment = {
3034 let warnings = WarningsProvider::for_figment(&toml_provider, &figment);
3035 figment.merge(warnings)
3036 };
3037
3038 let mut profiles = vec![Self::DEFAULT_PROFILE];
3040 if profile != Self::DEFAULT_PROFILE {
3041 profiles.push(profile.clone());
3042 }
3043 let provider = BackwardsCompatTomlProvider(ForcedSnakeCaseData(toml_provider));
3046 let provider = &provider.strict_select(profiles);
3047 let profile_provider = &IgnoreRootProvider(provider);
3050
3051 if profile != Self::DEFAULT_PROFILE {
3053 figment =
3054 figment.merge(profile_provider.rename(Self::DEFAULT_PROFILE, profile.clone()));
3055 }
3056 for standalone_key in Self::STANDALONE_SECTIONS {
3058 if let Some((_, fallback)) =
3059 STANDALONE_FALLBACK_SECTIONS.iter().find(|(key, _)| standalone_key == key)
3060 {
3061 figment = figment.merge(
3062 provider
3063 .fallback(standalone_key, fallback)
3064 .wrap(profile.clone(), standalone_key),
3065 );
3066 } else {
3067 figment = figment.merge(provider.wrap(profile.clone(), standalone_key));
3068 }
3069 }
3070 figment = figment.merge(profile_provider);
3072 figment
3073 }
3074
3075 fn normalize_defaults(&self, mut figment: Figment) -> Figment {
3081 if figment.contains("evm_version") {
3082 return figment;
3083 }
3084
3085 if let Ok(SolcReq::Version(version)) = figment.extract_inner::<SolcReq>("solc")
3088 && let Some(version) = self.evm_version.normalize_version_solc(&version)
3089 {
3090 let profile = figment.profile().clone();
3091 figment = figment.merge(Serialized::default("evm_version", version).profile(profile));
3092 }
3093
3094 if figment.extract_inner::<bool>("deny_warnings").unwrap_or(false)
3096 && figment.extract_inner("deny") == Ok(DenyLevel::Never)
3097 {
3098 figment = figment.merge(("deny", DenyLevel::Warnings));
3099 }
3100
3101 figment
3102 }
3103}
3104
3105impl From<Config> for Figment {
3106 fn from(c: Config) -> Self {
3107 (&c).into()
3108 }
3109}
3110impl From<&Config> for Figment {
3111 fn from(c: &Config) -> Self {
3112 c.to_figment(FigmentProviders::All)
3113 }
3114}
3115
3116#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3118pub enum FigmentProviders {
3119 #[default]
3121 All,
3122 Cast,
3126 Anvil,
3130 None,
3132}
3133
3134impl FigmentProviders {
3135 pub const fn is_all(&self) -> bool {
3137 matches!(self, Self::All)
3138 }
3139
3140 pub const fn is_cast(&self) -> bool {
3142 matches!(self, Self::Cast)
3143 }
3144
3145 pub const fn is_anvil(&self) -> bool {
3147 matches!(self, Self::Anvil)
3148 }
3149
3150 pub const fn is_none(&self) -> bool {
3152 matches!(self, Self::None)
3153 }
3154}
3155
3156fn figment_value_is_configured(figment: &Figment, key: &str) -> bool {
3157 figment.find_metadata(key).is_some_and(|metadata| metadata.name.as_ref() != "Foundry Config")
3158}
3159
3160#[derive(Clone, Debug, Serialize, Deserialize)]
3162#[serde(transparent)]
3163pub struct RegexWrapper {
3164 #[serde(with = "serde_regex")]
3165 inner: regex::Regex,
3166}
3167
3168impl std::ops::Deref for RegexWrapper {
3169 type Target = regex::Regex;
3170
3171 fn deref(&self) -> &Self::Target {
3172 &self.inner
3173 }
3174}
3175
3176impl std::cmp::PartialEq for RegexWrapper {
3177 fn eq(&self, other: &Self) -> bool {
3178 self.as_str() == other.as_str()
3179 }
3180}
3181
3182impl Eq for RegexWrapper {}
3183
3184impl From<RegexWrapper> for regex::Regex {
3185 fn from(wrapper: RegexWrapper) -> Self {
3186 wrapper.inner
3187 }
3188}
3189
3190impl From<regex::Regex> for RegexWrapper {
3191 fn from(re: Regex) -> Self {
3192 Self { inner: re }
3193 }
3194}
3195
3196mod serde_regex {
3197 use regex::Regex;
3198 use serde::{Deserialize, Deserializer, Serializer};
3199
3200 pub(crate) fn serialize<S>(value: &Regex, serializer: S) -> Result<S::Ok, S::Error>
3201 where
3202 S: Serializer,
3203 {
3204 serializer.serialize_str(value.as_str())
3205 }
3206
3207 pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Regex, D::Error>
3208 where
3209 D: Deserializer<'de>,
3210 {
3211 let s = String::deserialize(deserializer)?;
3212 Regex::new(&s).map_err(serde::de::Error::custom)
3213 }
3214}
3215
3216pub(crate) mod from_opt_glob {
3218 use serde::{Deserialize, Deserializer, Serializer};
3219
3220 pub fn serialize<S>(value: &Option<globset::Glob>, serializer: S) -> Result<S::Ok, S::Error>
3221 where
3222 S: Serializer,
3223 {
3224 match value {
3225 Some(glob) => serializer.serialize_str(glob.glob()),
3226 None => serializer.serialize_none(),
3227 }
3228 }
3229
3230 pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<globset::Glob>, D::Error>
3231 where
3232 D: Deserializer<'de>,
3233 {
3234 let s: Option<String> = Option::deserialize(deserializer)?;
3235 if let Some(s) = s {
3236 return Ok(Some(globset::Glob::new(&s).map_err(serde::de::Error::custom)?));
3237 }
3238 Ok(None)
3239 }
3240}
3241
3242pub fn parse_with_profile<T: serde::de::DeserializeOwned>(
3253 s: &str,
3254) -> Result<Option<(Profile, T)>, Error> {
3255 let figment = Config::merge_toml_provider(
3256 Figment::new(),
3257 Toml::string(s).nested(),
3258 Config::DEFAULT_PROFILE,
3259 );
3260 if figment.profiles().any(|p| p == Config::DEFAULT_PROFILE) {
3261 Ok(Some((Config::DEFAULT_PROFILE, figment.select(Config::DEFAULT_PROFILE).extract()?)))
3262 } else {
3263 Ok(None)
3264 }
3265}
3266
3267impl Provider for Config {
3268 fn metadata(&self) -> Metadata {
3269 Metadata::named("Foundry Config")
3270 }
3271
3272 #[track_caller]
3273 fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
3274 let mut data = Serialized::defaults(self).data()?;
3275 let root = Value::serialize(self.root.clone())?;
3276 let labels = Value::serialize(&self.labels)?;
3277 if let Some(entry) = data.get_mut(&Self::DEFAULT_PROFILE) {
3278 entry.insert("root".to_string(), root.clone());
3279 entry.insert("labels".to_string(), labels.clone());
3280 normalize_legacy_labels_in_profile(entry);
3281 }
3282 if let Some(entry) = data.get_mut(&self.profile) {
3283 entry.insert("root".to_string(), root);
3284 entry.insert("labels".to_string(), labels);
3285 normalize_legacy_labels_in_profile(entry);
3286 }
3287 Ok(data)
3288 }
3289
3290 fn profile(&self) -> Option<Profile> {
3291 Some(self.profile.clone())
3292 }
3293}
3294
3295impl Default for Config {
3296 fn default() -> Self {
3297 Self {
3298 profile: Self::DEFAULT_PROFILE,
3299 profiles: vec![Self::DEFAULT_PROFILE],
3300 fs_permissions: FsPermissions::new([PathPermission::read("out")]),
3301 isolate: true,
3302 root: root_default(),
3303 extends: None,
3304 src: Self::DEFAULT_SRC.into(),
3305 test: "test".into(),
3306 script: "script".into(),
3307 out: "out".into(),
3308 libs: vec!["lib".into()],
3309 cache: true,
3310 dynamic_test_linking: true,
3311 allow_linked_libraries: true,
3312 cache_path: "cache".into(),
3313 broadcast: "broadcast".into(),
3314 snapshots: "snapshots".into(),
3315 gas_snapshot_check: false,
3316 gas_snapshot_emit: true,
3317 allow_paths: vec![],
3318 include_paths: vec![],
3319 force: false,
3320 evm_version: EvmVersion::Osaka,
3321 hardfork: None,
3322 gas_reports: vec!["*".to_string()],
3323 gas_reports_ignore: vec![],
3324 gas_reports_include_tests: false,
3325 solc: None,
3326 vyper: Default::default(),
3327 external_compilers: Default::default(),
3328 auto_detect_solc: true,
3329 offline: false,
3330 optimizer: None,
3331 optimizer_runs: None,
3332 optimizer_details: None,
3333 model_checker: None,
3334 extra_output: Default::default(),
3335 extra_output_files: Default::default(),
3336 names: false,
3337 sizes: false,
3338 test_pattern: None,
3339 test_pattern_inverse: None,
3340 contract_pattern: None,
3341 contract_pattern_inverse: None,
3342 path_pattern: None,
3343 path_pattern_inverse: None,
3344 coverage_pattern_inverse: None,
3345 test_failures_file: "cache/test-failures".into(),
3346 mutation_dir: "cache/mutation".into(),
3347 threads: None,
3348 show_progress: false,
3349 fuzz: FuzzConfig::new("cache/fuzz".into()),
3350 invariant: InvariantConfig::new("cache/invariant".into()),
3351 symbolic: SymbolicConfig::default(),
3352 coverage: CoverageConfig::default(),
3353 mutation: MutationConfig::default(),
3354 tracing: TracingConfig::default(),
3355 always_use_create_2_factory: false,
3356 eip1559_fee_estimate: Eip1559FeeEstimatePreset::default(),
3357 ffi: false,
3358 live_logs: false,
3359 allow_internal_expect_revert: false,
3360 prompt_timeout: 120,
3361 sender: Self::DEFAULT_SENDER,
3362 tx_origin: Self::DEFAULT_SENDER,
3363 initial_balance: U256::from((1u128 << 96) - 1),
3364 block_number: U256::ONE,
3365 fork_block_number: None,
3366 fork_state_by_number: false,
3367 chain: None,
3368 gas_limit: (1u64 << 30).into(), code_size_limit: None,
3370 gas_price: None,
3371 block_base_fee_per_gas: 0,
3372 block_coinbase: Address::ZERO,
3373 block_timestamp: U256::ONE,
3374 block_difficulty: 0,
3375 block_prevrandao: Default::default(),
3376 block_gas_limit: None,
3377 disable_block_gas_limit: false,
3378 enable_tx_gas_limit: false,
3379 memory_limit: 1 << 27, eth_rpc_url: None,
3381 eth_rpc_accept_invalid_certs: false,
3382 eth_rpc_no_proxy: false,
3383 eth_rpc_jwt: None,
3384 eth_rpc_timeout: None,
3385 eth_rpc_headers: None,
3386 eth_rpc_curl: false,
3387 etherscan_api_key: None,
3388 verbosity: 0,
3389 remappings: vec![],
3390 auto_detect_remappings: true,
3391 libraries: vec![],
3392 ignored_error_codes: vec![
3393 SolidityErrorCode::SpdxLicenseNotProvided,
3394 SolidityErrorCode::ContractExceeds24576Bytes,
3395 SolidityErrorCode::ContractInitCodeSizeExceeds49152Bytes,
3396 SolidityErrorCode::TransientStorageUsed,
3397 SolidityErrorCode::TransferDeprecated,
3398 SolidityErrorCode::NatspecMemorySafeAssemblyDeprecated,
3399 SolidityErrorCode::ContractExceeds65536Bytes,
3400 SolidityErrorCode::ContractInitCodeSizeExceeds131072Bytes,
3401 ],
3402 ignored_error_codes_from: vec![],
3403 ignored_file_paths: vec![],
3404 deny: DenyLevel::Never,
3405 deny_warnings: false,
3406 via_ir: false,
3407 via_ssa_cfg: false,
3408 experimental: false,
3409 ast: false,
3410 rpc_storage_caching: Default::default(),
3411 rpc_endpoints: Default::default(),
3412 etherscan: Default::default(),
3413 no_storage_caching: false,
3414 no_fork_bal: false,
3415 fork_prefetch: false,
3416 no_rpc_rate_limit: false,
3417 use_literal_content: false,
3418 bytecode_hash: BytecodeHash::Ipfs,
3419 cbor_metadata: true,
3420 revert_strings: None,
3421 sparse_mode: false,
3422 build_info: false,
3423 build_info_path: None,
3424 build_info_without_ast: false,
3425 fmt: Default::default(),
3426 lint: Default::default(),
3427 doc: Default::default(),
3428 bind_json: Default::default(),
3429 labels: Default::default(),
3430 unchecked_cheatcode_artifacts: false,
3431 decode_external_storage: false,
3432 create2_library_salt: Self::DEFAULT_CREATE2_LIBRARY_SALT,
3433 create2_deployer: Self::DEFAULT_CREATE2_DEPLOYER,
3434 skip: vec![],
3435 dependencies: Default::default(),
3436 soldeer: Default::default(),
3437 assertions_revert: true,
3438 legacy_assertions: false,
3439 warnings: vec![],
3440 extra_args: vec![],
3441 networks: Default::default(),
3442 transaction_timeout: 120,
3443 additional_compiler_profiles: Default::default(),
3444 restrict_inline_config: false,
3445 compilation_restrictions: Default::default(),
3446 script_execution_protection: true,
3447 _non_exhaustive: (),
3448 }
3449 }
3450}
3451
3452#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
3458pub struct GasLimit(#[serde(deserialize_with = "crate::deserialize_u64_or_max")] pub u64);
3459
3460impl From<u64> for GasLimit {
3461 fn from(gas: u64) -> Self {
3462 Self(gas)
3463 }
3464}
3465
3466impl From<GasLimit> for u64 {
3467 fn from(gas: GasLimit) -> Self {
3468 gas.0
3469 }
3470}
3471
3472impl Serialize for GasLimit {
3473 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3474 where
3475 S: Serializer,
3476 {
3477 if self.0 == u64::MAX {
3478 serializer.serialize_str("max")
3479 } else if self.0 > i64::MAX as u64 {
3480 serializer.serialize_str(&self.0.to_string())
3481 } else {
3482 serializer.serialize_u64(self.0)
3483 }
3484 }
3485}
3486
3487#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
3489#[serde(untagged)]
3490pub enum SolcReq {
3491 Version(Version),
3494 Solar(
3499 #[serde(
3500 serialize_with = "serialize_solar_req",
3501 deserialize_with = "deserialize_solar_req"
3502 )]
3503 Version,
3504 ),
3505 Local(PathBuf),
3507}
3508
3509fn serialize_solar_req<S: Serializer>(version: &Version, serializer: S) -> Result<S::Ok, S::Error> {
3510 serializer.collect_str(&format_args!("solar:{version}"))
3511}
3512
3513fn deserialize_solar_req<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Version, D::Error> {
3514 let req = String::deserialize(deserializer)?;
3515 parse_solar_pin(&req).ok_or_else(|| de::Error::custom("not a Solar pin"))
3516}
3517
3518fn parse_solar_pin(req: &str) -> Option<Version> {
3521 let version = Version::parse(req.strip_prefix("solar:")?).ok()?;
3522 (version >= Version::new(0, 2, 0) && version.pre.is_empty() && version.build.is_empty())
3523 .then_some(version)
3524}
3525
3526fn resolve_solc_path(solc: &Path) -> Result<PathBuf, SolcError> {
3527 if solc.is_file() {
3528 Ok(solc.to_path_buf())
3529 } else if solc.to_str().is_some_and(|solc| solc.starts_with("solar:")) {
3530 Err(SolcError::msg(format!(
3531 "invalid Solar pin {solc:?}, expected `solar:<version>` naming a release 0.2.0 or \
3532 later, without pre-release or build metadata"
3533 )))
3534 } else {
3535 which::which(solc).map_err(|_| SolcError::msg(format!("`solc` {solc:?} does not exist")))
3536 }
3537}
3538
3539impl SolcReq {
3540 pub fn try_version(&self) -> Result<Version, SolcError> {
3546 match self {
3547 Self::Version(version) => Ok(version.clone()),
3548 Self::Solar(version) => Solc::find_installed_solar(version)
3549 .map(|solar| solar.version)
3550 .ok_or_else(|| SolcError::msg(format!("solar {version} is not installed"))),
3551 Self::Local(path) => Solc::new(resolve_solc_path(path)?).map(|solc| solc.version),
3552 }
3553 }
3554}
3555
3556impl<T: AsRef<str>> From<T> for SolcReq {
3557 fn from(s: T) -> Self {
3558 let s = s.as_ref();
3559 if let Ok(v) = Version::from_str(s) {
3560 Self::Version(v)
3561 } else if let Some(v) = parse_solar_pin(s) {
3562 Self::Solar(v)
3563 } else {
3564 Self::Local(s.into())
3565 }
3566 }
3567}
3568
3569#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
3581pub struct BasicConfig {
3582 #[serde(skip)]
3584 pub profile: Profile,
3585 pub src: PathBuf,
3587 pub out: PathBuf,
3589 pub libs: Vec<PathBuf>,
3591 #[serde(
3593 default,
3594 skip_serializing_if = "Vec::is_empty",
3595 serialize_with = "remappings_serde::serialize"
3596 )]
3597 pub remappings: Vec<RelativeRemapping>,
3598 #[serde(skip)]
3600 pub network: Option<String>,
3601}
3602
3603impl BasicConfig {
3604 pub fn to_string_pretty(&self) -> Result<String, toml::ser::Error> {
3608 let mut profile_body = toml::Value::try_from(self)?;
3609 if let Some(ref network) = self.network
3610 && let toml::Value::Table(ref mut table) = profile_body
3611 {
3612 table.insert("network".to_string(), toml::Value::String(network.clone()));
3613 }
3614
3615 let mut profile_section = toml::value::Table::new();
3616 profile_section.insert(self.profile.to_string(), profile_body);
3617
3618 let mut document = toml::value::Table::new();
3619 document.insert("profile".to_string(), toml::Value::Table(profile_section));
3620
3621 if self.network.as_deref() == Some("tempo") {
3622 let mut endpoints = toml::value::Table::new();
3623 endpoints.insert(
3624 "tempo".to_string(),
3625 toml::Value::String(crate::endpoints::TEMPO_RPC_URL.to_string()),
3626 );
3627 endpoints.insert(
3628 "moderato".to_string(),
3629 toml::Value::String(crate::endpoints::MODERATO_RPC_URL.to_string()),
3630 );
3631 document.insert("rpc_endpoints".to_string(), toml::Value::Table(endpoints));
3632 }
3633
3634 let body = toml::to_string_pretty(&toml::Value::Table(document))?;
3635 Ok(format!(
3636 "{body}\n# See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options\n"
3637 ))
3638 }
3639}
3640
3641mod remappings_serde {
3642 use foundry_compilers::artifacts::remappings::RelativeRemapping;
3643 use serde::{Serialize, Serializer};
3644
3645 #[cfg(windows)]
3646 use path_slash::PathExt as _;
3647 #[cfg(windows)]
3648 use std::path::Path;
3649
3650 #[cfg(windows)]
3651 fn slash_context(context: &str) -> String {
3652 let has_trailing_separator =
3653 context.as_bytes().last().is_some_and(|c| *c == b'/' || *c == b'\\');
3654 let mut context = Path::new(context).to_slash_lossy().into_owned();
3655 if has_trailing_separator && !context.ends_with('/') {
3656 context.push('/');
3657 }
3658 context
3659 }
3660
3661 pub fn serialize<S>(remappings: &[RelativeRemapping], serializer: S) -> Result<S::Ok, S::Error>
3662 where
3663 S: Serializer,
3664 {
3665 remappings
3666 .iter()
3667 .map(|remapping| {
3668 let Some(context) = &remapping.context else { return remapping.to_string() };
3669 let mut remapping = remapping.clone();
3670 remapping.context = None;
3671 #[cfg(windows)]
3672 let context = slash_context(context);
3673 #[cfg(not(windows))]
3674 let context = context.as_str();
3675 format!("{context}:{remapping}")
3676 })
3677 .collect::<Vec<_>>()
3678 .serialize(serializer)
3679 }
3680}
3681
3682pub(crate) mod from_str_lowercase {
3683 use serde::{Deserialize, Deserializer, Serializer};
3684 use std::str::FromStr;
3685
3686 pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
3687 where
3688 T: std::fmt::Display,
3689 S: Serializer,
3690 {
3691 serializer.collect_str(&value.to_string().to_lowercase())
3692 }
3693
3694 pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
3695 where
3696 D: Deserializer<'de>,
3697 T: FromStr,
3698 T::Err: std::fmt::Display,
3699 {
3700 String::deserialize(deserializer)?.to_lowercase().parse().map_err(serde::de::Error::custom)
3701 }
3702}
3703
3704fn canonic(path: impl Into<PathBuf>) -> PathBuf {
3705 let path = path.into();
3706 foundry_compilers::utils::canonicalize(&path).unwrap_or(path)
3707}
3708
3709fn root_default() -> PathBuf {
3710 ".".into()
3711}
3712
3713#[cfg(test)]
3714mod tests {
3715 use super::*;
3716 use crate::{
3717 cache::{CachedChains, CachedEndpoints},
3718 endpoints::RpcEndpointType,
3719 etherscan::ResolvedEtherscanConfigs,
3720 fmt::IndentStyle,
3721 };
3722 use NamedChain::Moonbeam;
3723 use endpoints::{RpcAuth, RpcEndpointConfig};
3724 use figment::error::Kind::InvalidType;
3725 use foundry_compilers::artifacts::{
3726 ModelCheckerEngine, YulDetails,
3727 vyper::{VyperOptimizationLevel, VyperOptimizationMode, VyperVenomSettings},
3728 };
3729 use foundry_evm_hardforks::{TempoHardfork, latest_active_tempo_hardfork};
3730 use similar_asserts::assert_eq;
3731 use soldeer_core::remappings::RemappingsLocation;
3732 use std::{
3733 fs::File,
3734 io::{self, Write},
3735 num::NonZeroUsize,
3736 };
3737 use tempfile::tempdir;
3738
3739 #[cfg(feature = "base")]
3740 use foundry_evm_hardforks::BaseUpgrade;
3741
3742 fn clear_warning(config: &mut Config) {
3745 config.warnings = vec![];
3746 }
3747
3748 fn mark_serialized_invariant_provenance(config: &mut Config) {
3749 config.invariant.corpus_random_sequence_weight_configured = true;
3750 config.invariant.workers_configured = true;
3751 }
3752
3753 #[test]
3754 fn project_remappings_alias_relative_filesystem_contexts_in_place() {
3755 let root = tempdir().unwrap();
3756 let project = root.path().join("project");
3757 fs::create_dir(&project).unwrap();
3758 let internal_dependency = project.join("dependency");
3759 fs::create_dir(&internal_dependency).unwrap();
3760 let dependency = root.path().join("dependency");
3761 let absolute_dependency = root.path().join("absolute-dependency");
3762 fs::create_dir(&dependency).unwrap();
3763 fs::create_dir(&absolute_dependency).unwrap();
3764
3765 let global_before = Remapping {
3766 context: None,
3767 name: "global-before/".into(),
3768 path: "lib/global-before/".into(),
3769 };
3770 let relative = Remapping {
3771 context: Some(format!("../dependency{}", std::path::MAIN_SEPARATOR)),
3772 name: "relative/".into(),
3773 path: "lib/relative/".into(),
3774 };
3775 let absolute = Remapping {
3776 context: Some(format!(
3777 "{}{}",
3778 absolute_dependency.display(),
3779 std::path::MAIN_SEPARATOR
3780 )),
3781 name: "absolute/".into(),
3782 path: "lib/absolute/".into(),
3783 };
3784 let missing = Remapping {
3785 context: Some(format!("missing{}", std::path::MAIN_SEPARATOR)),
3786 name: "missing/".into(),
3787 path: "lib/missing/".into(),
3788 };
3789 let global_after = Remapping {
3790 context: None,
3791 name: "global-after/".into(),
3792 path: "lib/global-after/".into(),
3793 };
3794 let internal = Remapping {
3795 context: Some(format!("dependency{}", std::path::MAIN_SEPARATOR)),
3796 name: "internal/".into(),
3797 path: "lib/internal/".into(),
3798 };
3799 let mut config = Config::with_root(&project);
3800 config.remappings = [
3801 global_before.clone(),
3802 internal.clone(),
3803 relative.clone(),
3804 absolute.clone(),
3805 missing.clone(),
3806 global_after.clone(),
3807 ]
3808 .map(Into::into)
3809 .into();
3810
3811 let mut absolute_alias = relative.clone();
3812 let absolute_context = config.root.parent().unwrap().join("dependency");
3813 #[cfg(windows)]
3814 let absolute_context = PathBuf::from_slash(absolute_context.to_string_lossy());
3815 let mut absolute_context = absolute_context.display().to_string();
3816 absolute_context.push(std::path::MAIN_SEPARATOR);
3817 absolute_alias.context = Some(absolute_context);
3818 assert_eq!(
3819 config.project_remappings(),
3820 vec![
3821 global_before,
3822 internal,
3823 relative,
3824 absolute_alias,
3825 absolute,
3826 missing,
3827 global_after
3828 ]
3829 );
3830 }
3831
3832 #[test]
3833 fn default_sender() {
3834 assert_eq!(Config::DEFAULT_SENDER, address!("0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38"));
3835 }
3836
3837 #[test]
3838 fn test_caching() {
3839 let mut config = Config::default();
3840 let chain_id = NamedChain::Mainnet;
3841 let url = "https://eth-mainnet.alchemyapi";
3842 assert!(config.enable_caching(url, chain_id));
3843
3844 config.no_storage_caching = true;
3845 assert!(!config.enable_caching(url, chain_id));
3846
3847 config.no_storage_caching = false;
3848 assert!(!config.enable_caching(url, NamedChain::Dev));
3849 }
3850
3851 #[test]
3852 fn test_fork_state_by_number_config() {
3853 figment::Jail::expect_with(|jail| {
3854 assert!(!Config::load().unwrap().fork_state_by_number);
3855 jail.create_file(
3856 "foundry.toml",
3857 r"
3858 [profile.default]
3859 fork_state_by_number = true
3860 no_storage_caching = true
3861
3862 [profile.ci]
3863 fork_state_by_number = false
3864 ",
3865 )?;
3866 let config = Config::load().unwrap();
3867 assert!(config.fork_state_by_number);
3868 assert!(config.no_storage_caching);
3869
3870 jail.set_env("FOUNDRY_PROFILE", "ci");
3871 let config = Config::load().unwrap();
3872 assert!(!config.fork_state_by_number);
3873 assert!(config.no_storage_caching);
3874 Ok(())
3875 });
3876 }
3877
3878 #[test]
3879 fn test_fork_state_by_number_environment() {
3880 figment::Jail::expect_with(|jail| {
3881 jail.create_file("foundry.toml", "[profile.default]\nfork_state_by_number = true\n")?;
3882 jail.set_env("FOUNDRY_FORK_STATE_BY_NUMBER", "false");
3883 assert!(!Config::load().unwrap().fork_state_by_number);
3884 jail.create_file("foundry.toml", "[profile.default]\nfork_state_by_number = false\n")?;
3885 jail.set_env("FOUNDRY_FORK_STATE_BY_NUMBER", "true");
3886 assert!(Config::load().unwrap().fork_state_by_number);
3887 jail.set_env("FOUNDRY_FORK_STATE_BY_NUMBER", "invalid");
3888 assert!(Config::load().is_err());
3889 Ok(())
3890 });
3891 }
3892
3893 #[test]
3894 fn test_fork_bal_config() {
3895 figment::Jail::expect_with(|jail| {
3896 assert!(!Config::load().unwrap().no_fork_bal);
3897 jail.create_file(
3898 "foundry.toml",
3899 r"
3900 [profile.default]
3901 no_fork_bal = true
3902 no_storage_caching = true
3903
3904 [profile.ci]
3905 no_fork_bal = false
3906 ",
3907 )?;
3908 let config = Config::load().unwrap();
3909 assert!(config.no_fork_bal);
3910 assert!(config.no_storage_caching);
3911
3912 jail.set_env("FOUNDRY_PROFILE", "ci");
3913 let config = Config::load().unwrap();
3914 assert!(!config.no_fork_bal);
3915 assert!(config.no_storage_caching);
3916 Ok(())
3917 });
3918 }
3919
3920 #[test]
3921 fn test_fork_prefetch_config() {
3922 figment::Jail::expect_with(|jail| {
3923 assert!(!Config::load().unwrap().fork_prefetch);
3924 jail.create_file(
3925 "foundry.toml",
3926 r"
3927 [profile.default]
3928 fork_prefetch = true
3929
3930 [profile.ci]
3931 fork_prefetch = false
3932 ",
3933 )?;
3934 assert!(Config::load().unwrap().fork_prefetch);
3935 jail.set_env("FOUNDRY_PROFILE", "ci");
3936 assert!(!Config::load().unwrap().fork_prefetch);
3937 jail.set_env("FOUNDRY_FORK_PREFETCH", "true");
3938 assert!(Config::load().unwrap().fork_prefetch);
3939 jail.set_env("FOUNDRY_FORK_PREFETCH", "invalid");
3940 assert!(Config::load().is_err());
3941 Ok(())
3942 });
3943 }
3944
3945 #[test]
3946 fn test_fork_bal_environment() {
3947 figment::Jail::expect_with(|jail| {
3948 jail.create_file("foundry.toml", "[profile.default]\nno_fork_bal = true\n")?;
3949 jail.set_env("FOUNDRY_NO_FORK_BAL", "false");
3950 assert!(!Config::load().unwrap().no_fork_bal);
3951 jail.create_file("foundry.toml", "[profile.default]\nno_fork_bal = false\n")?;
3952 jail.set_env("FOUNDRY_NO_FORK_BAL", "true");
3953 assert!(Config::load().unwrap().no_fork_bal);
3954 jail.set_env("FOUNDRY_NO_FORK_BAL", "invalid");
3955 assert!(Config::load().is_err());
3956 Ok(())
3957 });
3958 }
3959
3960 #[test]
3961 fn test_install_dir() {
3962 figment::Jail::expect_with(|jail| {
3963 let config = Config::load().unwrap();
3964 assert_eq!(config.install_lib_dir(), PathBuf::from("lib"));
3965 jail.create_file(
3966 "foundry.toml",
3967 r"
3968 [profile.default]
3969 libs = ['node_modules', 'lib']
3970 ",
3971 )?;
3972 let config = Config::load().unwrap();
3973 assert_eq!(config.install_lib_dir(), PathBuf::from("lib"));
3974
3975 jail.create_file(
3976 "foundry.toml",
3977 r"
3978 [profile.default]
3979 libs = ['custom', 'node_modules', 'lib']
3980 ",
3981 )?;
3982 let config = Config::load().unwrap();
3983 assert_eq!(config.install_lib_dir(), PathBuf::from("custom"));
3984
3985 Ok(())
3986 });
3987 }
3988
3989 #[test]
3990 fn test_figment_is_default() {
3991 figment::Jail::expect_with(|_| {
3992 let mut default: Config = Config::figment().extract()?;
3993 let default2 = Config::default();
3994 default.profile = default2.profile.clone();
3995 default.profiles = default2.profiles.clone();
3996 assert_eq!(default, default2);
3997 Ok(())
3998 });
3999 }
4000
4001 #[test]
4002 fn figment_profiles() {
4003 figment::Jail::expect_with(|jail| {
4004 jail.create_file(
4005 "foundry.toml",
4006 r"
4007 [foo.baz]
4008 libs = ['node_modules', 'lib']
4009
4010 [profile.default]
4011 libs = ['node_modules', 'lib']
4012
4013 [profile.ci]
4014 libs = ['node_modules', 'lib']
4015
4016 [profile.local]
4017 libs = ['node_modules', 'lib']
4018 ",
4019 )?;
4020
4021 let config = crate::Config::load().unwrap();
4022 let expected: &[figment::Profile] = &["ci".into(), "default".into(), "local".into()];
4023 assert_eq!(config.profiles, expected);
4024
4025 Ok(())
4026 });
4027 }
4028
4029 #[test]
4030 fn test_default_round_trip() {
4031 figment::Jail::expect_with(|_| {
4032 let original = Config::figment();
4033 let roundtrip = Figment::from(Config::from_provider(&original).unwrap());
4034 for figment in &[original, roundtrip] {
4035 let config = Config::from_provider(figment).unwrap();
4036 assert_eq!(config, Config::default().normalized_optimizer_settings());
4037 }
4038 Ok(())
4039 });
4040 }
4041
4042 #[test]
4043 fn ffi_env_disallowed() {
4044 figment::Jail::expect_with(|jail| {
4045 jail.set_env("FOUNDRY_FFI", "true");
4046 jail.set_env("FFI", "true");
4047 jail.set_env("DAPP_FFI", "true");
4048 let config = Config::load().unwrap();
4049 assert!(!config.ffi);
4050
4051 Ok(())
4052 });
4053 }
4054
4055 #[test]
4056 fn test_profile_env() {
4057 figment::Jail::expect_with(|jail| {
4058 jail.set_env("FOUNDRY_PROFILE", "default");
4059 let figment = Config::figment();
4060 assert_eq!(figment.profile(), "default");
4061
4062 jail.set_env("FOUNDRY_PROFILE", "hardhat");
4063 let figment: Figment = Config::hardhat().into();
4064 assert_eq!(figment.profile(), "hardhat");
4065
4066 jail.create_file(
4067 "foundry.toml",
4068 r"
4069 [profile.default]
4070 libs = ['lib']
4071 [profile.local]
4072 libs = ['modules']
4073 ",
4074 )?;
4075 jail.set_env("FOUNDRY_PROFILE", "local");
4076 let config = Config::load().unwrap();
4077 assert_eq!(config.libs, vec![PathBuf::from("modules")]);
4078
4079 Ok(())
4080 });
4081 }
4082
4083 #[test]
4084 fn test_default_test_path() {
4085 figment::Jail::expect_with(|_| {
4086 let config = Config::default();
4087 let paths_config = config.project_paths::<Solc>();
4088 assert_eq!(paths_config.tests, PathBuf::from(r"test"));
4089 Ok(())
4090 });
4091 }
4092
4093 #[test]
4094 fn test_custom_src_skips_directory_auto_detection() {
4095 figment::Jail::expect_with(|jail| {
4096 fs::create_dir(jail.directory().join("contracts")).unwrap();
4097
4098 let config = Config { root: jail.directory().into(), ..Default::default() };
4099 let figment: Figment = config.into();
4100 let config = figment.extract::<Config>().unwrap();
4101 assert_eq!(config.src, PathBuf::from("contracts"));
4102
4103 let config = Config {
4104 root: jail.directory().into(),
4105 src: "custom-src".into(),
4106 ..Default::default()
4107 };
4108 let figment: Figment = config.into();
4109 let config = figment.extract::<Config>().unwrap();
4110 assert_eq!(config.src, PathBuf::from("custom-src"));
4111
4112 Ok(())
4113 });
4114 }
4115
4116 #[test]
4117 fn test_default_libs() {
4118 figment::Jail::expect_with(|jail| {
4119 let config = Config::load().unwrap();
4120 assert_eq!(config.libs, vec![PathBuf::from("lib")]);
4121
4122 fs::create_dir_all(jail.directory().join("node_modules")).unwrap();
4123 let config = Config::load().unwrap();
4124 assert_eq!(config.libs, vec![PathBuf::from("node_modules")]);
4125
4126 fs::create_dir_all(jail.directory().join("lib")).unwrap();
4127 let config = Config::load().unwrap();
4128 assert_eq!(config.libs, vec![PathBuf::from("lib"), PathBuf::from("node_modules")]);
4129
4130 Ok(())
4131 });
4132 }
4133
4134 #[test]
4135 fn test_inheritance_from_default_test_path() {
4136 figment::Jail::expect_with(|jail| {
4137 jail.create_file(
4138 "foundry.toml",
4139 r#"
4140 [profile.default]
4141 test = "defaulttest"
4142 src = "defaultsrc"
4143 libs = ['lib', 'node_modules']
4144
4145 [profile.custom]
4146 src = "customsrc"
4147 "#,
4148 )?;
4149
4150 let config = Config::load().unwrap();
4151 assert_eq!(config.src, PathBuf::from("defaultsrc"));
4152 assert_eq!(config.libs, vec![PathBuf::from("lib"), PathBuf::from("node_modules")]);
4153
4154 jail.set_env("FOUNDRY_PROFILE", "custom");
4155 let config = Config::load().unwrap();
4156 assert_eq!(config.src, PathBuf::from("customsrc"));
4157 assert_eq!(config.test, PathBuf::from("defaulttest"));
4158 assert_eq!(config.libs, vec![PathBuf::from("lib"), PathBuf::from("node_modules")]);
4159
4160 Ok(())
4161 });
4162 }
4163
4164 #[test]
4165 fn test_custom_test_path() {
4166 figment::Jail::expect_with(|jail| {
4167 jail.create_file(
4168 "foundry.toml",
4169 r#"
4170 [profile.default]
4171 test = "mytest"
4172 "#,
4173 )?;
4174
4175 let config = Config::load().unwrap();
4176 let paths_config = config.project_paths::<Solc>();
4177 assert_eq!(paths_config.tests, PathBuf::from(r"mytest"));
4178 Ok(())
4179 });
4180 }
4181
4182 #[test]
4183 fn test_remappings() {
4184 figment::Jail::expect_with(|jail| {
4185 jail.create_file(
4186 "foundry.toml",
4187 r#"
4188 [profile.default]
4189 src = "some-source"
4190 out = "some-out"
4191 cache = true
4192 "#,
4193 )?;
4194 let config = Config::load().unwrap();
4195 assert!(config.remappings.is_empty());
4196
4197 jail.create_file(
4198 "remappings.txt",
4199 r"
4200 file-ds-test/=lib/ds-test/
4201 file-other/=lib/other/
4202 ",
4203 )?;
4204
4205 let config = Config::load().unwrap();
4206 assert_eq!(
4207 config.remappings,
4208 vec![
4209 Remapping::from_str("file-ds-test/=lib/ds-test/").unwrap().into(),
4210 Remapping::from_str("file-other/=lib/other/").unwrap().into(),
4211 ],
4212 );
4213
4214 jail.set_env("DAPP_REMAPPINGS", "ds-test=lib/ds-test/\nother/=lib/other/");
4215 let config = Config::load().unwrap();
4216
4217 assert_eq!(
4218 config.remappings,
4219 vec![
4220 Remapping::from_str("ds-test=lib/ds-test/").unwrap().into(),
4222 Remapping::from_str("other/=lib/other/").unwrap().into(),
4223 Remapping::from_str("file-ds-test/=lib/ds-test/").unwrap().into(),
4225 Remapping::from_str("file-other/=lib/other/").unwrap().into(),
4226 ],
4227 );
4228
4229 Ok(())
4230 });
4231 }
4232
4233 #[test]
4234 fn test_remappings_override() {
4235 figment::Jail::expect_with(|jail| {
4236 jail.create_file(
4237 "foundry.toml",
4238 r#"
4239 [profile.default]
4240 src = "some-source"
4241 out = "some-out"
4242 cache = true
4243 "#,
4244 )?;
4245 let config = Config::load().unwrap();
4246 assert!(config.remappings.is_empty());
4247
4248 jail.create_file(
4249 "remappings.txt",
4250 r"
4251 ds-test/=lib/ds-test/
4252 other/=lib/other/
4253 ",
4254 )?;
4255
4256 let config = Config::load().unwrap();
4257 assert_eq!(
4258 config.remappings,
4259 vec![
4260 Remapping::from_str("ds-test/=lib/ds-test/").unwrap().into(),
4261 Remapping::from_str("other/=lib/other/").unwrap().into(),
4262 ],
4263 );
4264
4265 jail.set_env("DAPP_REMAPPINGS", "ds-test/=lib/ds-test/src/\nenv-lib/=lib/env-lib/");
4266 let config = Config::load().unwrap();
4267
4268 assert_eq!(
4273 config.remappings,
4274 vec![
4275 Remapping::from_str("ds-test/=lib/ds-test/src/").unwrap().into(),
4276 Remapping::from_str("env-lib/=lib/env-lib/").unwrap().into(),
4277 Remapping::from_str("other/=lib/other/").unwrap().into(),
4278 ],
4279 );
4280
4281 assert_eq!(
4283 config.get_all_remappings().collect::<Vec<_>>(),
4284 vec![
4285 Remapping::from_str("ds-test/=lib/ds-test/src/").unwrap(),
4286 Remapping::from_str("env-lib/=lib/env-lib/").unwrap(),
4287 Remapping::from_str("other/=lib/other/").unwrap(),
4288 ],
4289 );
4290
4291 Ok(())
4292 });
4293 }
4294
4295 #[test]
4296 fn test_can_update_libs() {
4297 figment::Jail::expect_with(|jail| {
4298 jail.create_file(
4299 "foundry.toml",
4300 r#"
4301 [profile.default]
4302 libs = ["node_modules"]
4303 "#,
4304 )?;
4305
4306 let mut config = Config::load().unwrap();
4307 config.libs.push("libs".into());
4308 config.update_libs().unwrap();
4309
4310 let config = Config::load().unwrap();
4311 assert_eq!(config.libs, vec![PathBuf::from("node_modules"), PathBuf::from("libs"),]);
4312 Ok(())
4313 });
4314 }
4315
4316 #[test]
4317 fn test_large_gas_limit() {
4318 figment::Jail::expect_with(|jail| {
4319 let gas = u64::MAX;
4320 jail.create_file(
4321 "foundry.toml",
4322 &format!(
4323 r#"
4324 [profile.default]
4325 gas_limit = "{gas}"
4326 "#
4327 ),
4328 )?;
4329
4330 let config = Config::load().unwrap();
4331 assert_eq!(
4332 config,
4333 Config {
4334 gas_limit: gas.into(),
4335 ..Config::default().normalized_optimizer_settings()
4336 }
4337 );
4338
4339 Ok(())
4340 });
4341 }
4342
4343 #[test]
4344 #[should_panic]
4345 fn test_toml_file_parse_failure() {
4346 figment::Jail::expect_with(|jail| {
4347 jail.create_file(
4348 "foundry.toml",
4349 r#"
4350 [profile.default]
4351 eth_rpc_url = "https://example.com/
4352 "#,
4353 )?;
4354
4355 let _config = Config::load().unwrap();
4356
4357 Ok(())
4358 });
4359 }
4360
4361 #[test]
4362 #[should_panic]
4363 fn test_toml_file_non_existing_config_var_failure() {
4364 figment::Jail::expect_with(|jail| {
4365 jail.set_env("FOUNDRY_CONFIG", "this config does not exist");
4366
4367 let _config = Config::load().unwrap();
4368
4369 Ok(())
4370 });
4371 }
4372
4373 #[test]
4374 fn test_resolve_etherscan_with_chain() {
4375 figment::Jail::expect_with(|jail| {
4376 let env_key = "__BSC_ETHERSCAN_API_KEY";
4377 let env_value = "env value";
4378 jail.create_file(
4379 "foundry.toml",
4380 r#"
4381 [profile.default]
4382
4383 [etherscan]
4384 bsc = { key = "${__BSC_ETHERSCAN_API_KEY}", url = "https://api.bscscan.com/api" }
4385 "#,
4386 )?;
4387
4388 let config = Config::load().unwrap();
4389 assert!(
4390 config
4391 .get_etherscan_config_with_chain(Some(NamedChain::BinanceSmartChain.into()))
4392 .is_err()
4393 );
4394
4395 unsafe {
4396 std::env::set_var(env_key, env_value);
4397 }
4398
4399 assert_eq!(
4400 config
4401 .get_etherscan_config_with_chain(Some(NamedChain::BinanceSmartChain.into()))
4402 .unwrap()
4403 .unwrap()
4404 .key,
4405 env_value
4406 );
4407
4408 let mut with_key = config;
4409 with_key.etherscan_api_key = Some("via etherscan_api_key".to_string());
4410
4411 assert_eq!(
4412 with_key
4413 .get_etherscan_config_with_chain(Some(NamedChain::BinanceSmartChain.into()))
4414 .unwrap()
4415 .unwrap()
4416 .key,
4417 "via etherscan_api_key"
4418 );
4419
4420 unsafe {
4421 std::env::remove_var(env_key);
4422 }
4423 Ok(())
4424 });
4425 }
4426
4427 #[test]
4428 fn test_resolve_etherscan() {
4429 figment::Jail::expect_with(|jail| {
4430 jail.create_file(
4431 "foundry.toml",
4432 r#"
4433 [profile.default]
4434
4435 [etherscan]
4436 mainnet = { key = "FX42Z3BBJJEWXWGYV2X1CIPRSCN" }
4437 moonbeam = { key = "${_CONFIG_ETHERSCAN_MOONBEAM}" }
4438 "#,
4439 )?;
4440
4441 let config = Config::load().unwrap();
4442
4443 assert!(config.etherscan.clone().resolved().has_unresolved());
4444
4445 jail.set_env("_CONFIG_ETHERSCAN_MOONBEAM", "123456789");
4446
4447 let configs = config.etherscan.resolved();
4448 assert!(!configs.has_unresolved());
4449
4450 let mb_urls = Moonbeam.etherscan_urls().unwrap();
4451 let mainnet_urls = NamedChain::Mainnet.etherscan_urls().unwrap();
4452 assert_eq!(
4453 configs,
4454 ResolvedEtherscanConfigs::new([
4455 (
4456 "mainnet",
4457 ResolvedEtherscanConfig {
4458 api_url: mainnet_urls.0.to_string(),
4459 chain: Some(NamedChain::Mainnet.into()),
4460 browser_url: Some(mainnet_urls.1.to_string()),
4461 key: "FX42Z3BBJJEWXWGYV2X1CIPRSCN".to_string(),
4462 }
4463 ),
4464 (
4465 "moonbeam",
4466 ResolvedEtherscanConfig {
4467 api_url: mb_urls.0.to_string(),
4468 chain: Some(Moonbeam.into()),
4469 browser_url: Some(mb_urls.1.to_string()),
4470 key: "123456789".to_string(),
4471 }
4472 ),
4473 ])
4474 );
4475
4476 Ok(())
4477 });
4478 }
4479
4480 #[test]
4481 fn test_resolve_etherscan_with_versions() {
4482 figment::Jail::expect_with(|jail| {
4483 jail.create_file(
4484 "foundry.toml",
4485 r#"
4486 [profile.default]
4487
4488 [etherscan]
4489 mainnet = { key = "FX42Z3BBJJEWXWGYV2X1CIPRSCN", api_version = "v2" }
4490 moonbeam = { key = "${_CONFIG_ETHERSCAN_MOONBEAM}", api_version = "v1" }
4491 "#,
4492 )?;
4493
4494 let config = Config::load().unwrap();
4495
4496 assert!(config.etherscan.clone().resolved().has_unresolved());
4497
4498 jail.set_env("_CONFIG_ETHERSCAN_MOONBEAM", "123456789");
4499
4500 let configs = config.etherscan.resolved();
4501 assert!(!configs.has_unresolved());
4502
4503 let mb_urls = Moonbeam.etherscan_urls().unwrap();
4504 let mainnet_urls = NamedChain::Mainnet.etherscan_urls().unwrap();
4505 assert_eq!(
4506 configs,
4507 ResolvedEtherscanConfigs::new([
4508 (
4509 "mainnet",
4510 ResolvedEtherscanConfig {
4511 api_url: mainnet_urls.0.to_string(),
4512 chain: Some(NamedChain::Mainnet.into()),
4513 browser_url: Some(mainnet_urls.1.to_string()),
4514 key: "FX42Z3BBJJEWXWGYV2X1CIPRSCN".to_string(),
4515 }
4516 ),
4517 (
4518 "moonbeam",
4519 ResolvedEtherscanConfig {
4520 api_url: mb_urls.0.to_string(),
4521 chain: Some(Moonbeam.into()),
4522 browser_url: Some(mb_urls.1.to_string()),
4523 key: "123456789".to_string(),
4524 }
4525 ),
4526 ])
4527 );
4528
4529 Ok(())
4530 });
4531 }
4532
4533 #[test]
4534 fn test_resolve_etherscan_chain_id() {
4535 figment::Jail::expect_with(|jail| {
4536 jail.create_file(
4537 "foundry.toml",
4538 r#"
4539 [profile.default]
4540 chain_id = "sepolia"
4541
4542 [etherscan]
4543 sepolia = { key = "FX42Z3BBJJEWXWGYV2X1CIPRSCN" }
4544 "#,
4545 )?;
4546
4547 let config = Config::load().unwrap();
4548 let etherscan = config.get_etherscan_config().unwrap().unwrap();
4549 assert_eq!(etherscan.chain, Some(NamedChain::Sepolia.into()));
4550 assert_eq!(etherscan.key, "FX42Z3BBJJEWXWGYV2X1CIPRSCN");
4551
4552 Ok(())
4553 });
4554 }
4555
4556 #[test]
4558 fn test_resolve_etherscan_with_invalid_name() {
4559 figment::Jail::expect_with(|jail| {
4560 jail.create_file(
4561 "foundry.toml",
4562 r#"
4563 [etherscan]
4564 mainnet = { key = "FX42Z3BBJJEWXWGYV2X1CIPRSCN" }
4565 an_invalid_name = { key = "FX42Z3BBJJEWXWGYV2X1CIPRSCN" }
4566 "#,
4567 )?;
4568
4569 let config = Config::load().unwrap();
4570 let etherscan_config = config.get_etherscan_config();
4571 assert!(etherscan_config.is_none());
4572
4573 Ok(())
4574 });
4575 }
4576
4577 #[test]
4578 fn test_resolve_rpc_url() {
4579 figment::Jail::expect_with(|jail| {
4580 jail.create_file(
4581 "foundry.toml",
4582 r#"
4583 [profile.default]
4584 [rpc_endpoints]
4585 optimism = "https://example.com/"
4586 mainnet = "${_CONFIG_MAINNET}"
4587 "#,
4588 )?;
4589 jail.set_env("_CONFIG_MAINNET", "https://eth-mainnet.alchemyapi.io/v2/123455");
4590
4591 let mut config = Config::load().unwrap();
4592 assert_eq!("http://localhost:8545", config.get_rpc_url_or_localhost_http().unwrap());
4593
4594 config.eth_rpc_url = Some("mainnet".to_string());
4595 assert_eq!(
4596 "https://eth-mainnet.alchemyapi.io/v2/123455",
4597 config.get_rpc_url_or_localhost_http().unwrap()
4598 );
4599
4600 config.eth_rpc_url = Some("optimism".to_string());
4601 assert_eq!("https://example.com/", config.get_rpc_url_or_localhost_http().unwrap());
4602
4603 Ok(())
4604 })
4605 }
4606
4607 #[test]
4608 fn test_resolve_rpc_url_if_etherscan_set() {
4609 figment::Jail::expect_with(|jail| {
4610 jail.create_file(
4611 "foundry.toml",
4612 r#"
4613 [profile.default]
4614 etherscan_api_key = "dummy"
4615 [rpc_endpoints]
4616 optimism = "https://example.com/"
4617 "#,
4618 )?;
4619
4620 let config = Config::load().unwrap();
4621 assert_eq!("http://localhost:8545", config.get_rpc_url_or_localhost_http().unwrap());
4622
4623 Ok(())
4624 })
4625 }
4626
4627 #[test]
4628 fn test_resolve_rpc_url_alias() {
4629 figment::Jail::expect_with(|jail| {
4630 jail.create_file(
4631 "foundry.toml",
4632 r#"
4633 [profile.default]
4634 [rpc_endpoints]
4635 polygonAmoy = "https://polygon-amoy.g.alchemy.com/v2/${_RESOLVE_RPC_ALIAS}"
4636 "#,
4637 )?;
4638 let mut config = Config::load().unwrap();
4639 config.eth_rpc_url = Some("polygonAmoy".to_string());
4640 assert!(config.get_rpc_url().unwrap().is_err());
4641
4642 jail.set_env("_RESOLVE_RPC_ALIAS", "123455");
4643
4644 let mut config = Config::load().unwrap();
4645 config.eth_rpc_url = Some("polygonAmoy".to_string());
4646 assert_eq!(
4647 "https://polygon-amoy.g.alchemy.com/v2/123455",
4648 config.get_rpc_url().unwrap().unwrap()
4649 );
4650
4651 Ok(())
4652 })
4653 }
4654
4655 #[test]
4656 fn test_resolve_rpc_aliases() {
4657 figment::Jail::expect_with(|jail| {
4658 jail.create_file(
4659 "foundry.toml",
4660 r#"
4661 [profile.default]
4662 [etherscan]
4663 arbitrum_alias = { key = "${TEST_RESOLVE_RPC_ALIAS_ARBISCAN}" }
4664 [rpc_endpoints]
4665 arbitrum_alias = "https://arb-mainnet.g.alchemy.com/v2/${TEST_RESOLVE_RPC_ALIAS_ARB_ONE}"
4666 "#,
4667 )?;
4668
4669 jail.set_env("TEST_RESOLVE_RPC_ALIAS_ARB_ONE", "123455");
4670 jail.set_env("TEST_RESOLVE_RPC_ALIAS_ARBISCAN", "123455");
4671
4672 let config = Config::load().unwrap();
4673
4674 let config = config.get_etherscan_config_with_chain(Some(NamedChain::Arbitrum.into()));
4675 assert!(config.is_err());
4676 assert_eq!(
4677 config.unwrap_err().to_string(),
4678 "At least one of `url` or `chain` must be present for Etherscan config with unknown alias `arbitrum_alias`"
4679 );
4680
4681 Ok(())
4682 });
4683 }
4684
4685 #[test]
4686 fn test_resolve_rpc_config() {
4687 figment::Jail::expect_with(|jail| {
4688 jail.create_file(
4689 "foundry.toml",
4690 r#"
4691 [rpc_endpoints]
4692 optimism = "https://example.com/"
4693 mainnet = { endpoint = "${_CONFIG_MAINNET}", retries = 3, retry_backoff = 1000, compute_units_per_second = 1000 }
4694 "#,
4695 )?;
4696 jail.set_env("_CONFIG_MAINNET", "https://eth-mainnet.alchemyapi.io/v2/123455");
4697
4698 let config = Config::load().unwrap();
4699 assert_eq!(
4700 RpcEndpoints::new([
4701 (
4702 "optimism",
4703 RpcEndpointType::String(RpcEndpointUrl::Url(
4704 "https://example.com/".to_string()
4705 ))
4706 ),
4707 (
4708 "mainnet",
4709 RpcEndpointType::Config(RpcEndpoint {
4710 endpoint: RpcEndpointUrl::Env("${_CONFIG_MAINNET}".to_string()),
4711 extra_endpoints: vec![],
4712 config: RpcEndpointConfig {
4713 retries: Some(3),
4714 retry_backoff: Some(1000),
4715 compute_units_per_second: Some(1000),
4716 },
4717 auth: None,
4718 })
4719 ),
4720 ]),
4721 config.rpc_endpoints
4722 );
4723
4724 let resolved = config.rpc_endpoints.resolved();
4725 assert_eq!(
4726 RpcEndpoints::new([
4727 (
4728 "optimism",
4729 RpcEndpointType::String(RpcEndpointUrl::Url(
4730 "https://example.com/".to_string()
4731 ))
4732 ),
4733 (
4734 "mainnet",
4735 RpcEndpointType::Config(RpcEndpoint {
4736 endpoint: RpcEndpointUrl::Env("${_CONFIG_MAINNET}".to_string()),
4737 extra_endpoints: vec![],
4738 config: RpcEndpointConfig {
4739 retries: Some(3),
4740 retry_backoff: Some(1000),
4741 compute_units_per_second: Some(1000),
4742 },
4743 auth: None,
4744 })
4745 ),
4746 ])
4747 .resolved(),
4748 resolved
4749 );
4750 Ok(())
4751 })
4752 }
4753
4754 #[test]
4755 fn test_resolve_auth() {
4756 figment::Jail::expect_with(|jail| {
4757 jail.create_file(
4758 "foundry.toml",
4759 r#"
4760 [profile.default]
4761 eth_rpc_url = "optimism"
4762 [rpc_endpoints]
4763 optimism = "https://example.com/"
4764 mainnet = { endpoint = "${_CONFIG_MAINNET}", retries = 3, retry_backoff = 1000, compute_units_per_second = 1000, auth = "Bearer ${_CONFIG_AUTH}" }
4765 "#,
4766 )?;
4767
4768 let config = Config::load().unwrap();
4769
4770 jail.set_env("_CONFIG_AUTH", "123456");
4771 jail.set_env("_CONFIG_MAINNET", "https://eth-mainnet.alchemyapi.io/v2/123455");
4772
4773 assert_eq!(
4774 RpcEndpoints::new([
4775 (
4776 "optimism",
4777 RpcEndpointType::String(RpcEndpointUrl::Url(
4778 "https://example.com/".to_string()
4779 ))
4780 ),
4781 (
4782 "mainnet",
4783 RpcEndpointType::Config(RpcEndpoint {
4784 endpoint: RpcEndpointUrl::Env("${_CONFIG_MAINNET}".to_string()),
4785 extra_endpoints: vec![],
4786 config: RpcEndpointConfig {
4787 retries: Some(3),
4788 retry_backoff: Some(1000),
4789 compute_units_per_second: Some(1000)
4790 },
4791 auth: Some(RpcAuth::Env("Bearer ${_CONFIG_AUTH}".to_string())),
4792 })
4793 ),
4794 ]),
4795 config.rpc_endpoints
4796 );
4797 let resolved = config.rpc_endpoints.resolved();
4798 assert_eq!(
4799 RpcEndpoints::new([
4800 (
4801 "optimism",
4802 RpcEndpointType::String(RpcEndpointUrl::Url(
4803 "https://example.com/".to_string()
4804 ))
4805 ),
4806 (
4807 "mainnet",
4808 RpcEndpointType::Config(RpcEndpoint {
4809 endpoint: RpcEndpointUrl::Url(
4810 "https://eth-mainnet.alchemyapi.io/v2/123455".to_string()
4811 ),
4812 extra_endpoints: vec![],
4813 config: RpcEndpointConfig {
4814 retries: Some(3),
4815 retry_backoff: Some(1000),
4816 compute_units_per_second: Some(1000)
4817 },
4818 auth: Some(RpcAuth::Raw("Bearer 123456".to_string())),
4819 })
4820 ),
4821 ])
4822 .resolved(),
4823 resolved
4824 );
4825
4826 Ok(())
4827 });
4828 }
4829
4830 #[test]
4831 fn test_resolve_endpoints() {
4832 figment::Jail::expect_with(|jail| {
4833 jail.create_file(
4834 "foundry.toml",
4835 r#"
4836 [profile.default]
4837 eth_rpc_url = "optimism"
4838 [rpc_endpoints]
4839 optimism = "https://example.com/"
4840 mainnet = "${_CONFIG_MAINNET}"
4841 mainnet_2 = "https://eth-mainnet.alchemyapi.io/v2/${_CONFIG_API_KEY1}"
4842 mainnet_3 = "https://eth-mainnet.alchemyapi.io/v2/${_CONFIG_API_KEY1}/${_CONFIG_API_KEY2}"
4843 "#,
4844 )?;
4845
4846 let config = Config::load().unwrap();
4847
4848 assert_eq!(config.get_rpc_url().unwrap().unwrap(), "https://example.com/");
4849
4850 assert!(config.rpc_endpoints.clone().resolved().has_unresolved());
4851
4852 jail.set_env("_CONFIG_MAINNET", "https://eth-mainnet.alchemyapi.io/v2/123455");
4853 jail.set_env("_CONFIG_API_KEY1", "123456");
4854 jail.set_env("_CONFIG_API_KEY2", "98765");
4855
4856 let endpoints = config.rpc_endpoints.resolved();
4857
4858 assert!(!endpoints.has_unresolved());
4859
4860 assert_eq!(
4861 endpoints,
4862 RpcEndpoints::new([
4863 ("optimism", RpcEndpointUrl::Url("https://example.com/".to_string())),
4864 (
4865 "mainnet",
4866 RpcEndpointUrl::Url(
4867 "https://eth-mainnet.alchemyapi.io/v2/123455".to_string()
4868 )
4869 ),
4870 (
4871 "mainnet_2",
4872 RpcEndpointUrl::Url(
4873 "https://eth-mainnet.alchemyapi.io/v2/123456".to_string()
4874 )
4875 ),
4876 (
4877 "mainnet_3",
4878 RpcEndpointUrl::Url(
4879 "https://eth-mainnet.alchemyapi.io/v2/123456/98765".to_string()
4880 )
4881 ),
4882 ])
4883 .resolved()
4884 );
4885
4886 Ok(())
4887 });
4888 }
4889
4890 #[test]
4891 fn test_extract_etherscan_config() {
4892 figment::Jail::expect_with(|jail| {
4893 jail.create_file(
4894 "foundry.toml",
4895 r#"
4896 [profile.default]
4897 etherscan_api_key = "optimism"
4898
4899 [etherscan]
4900 optimism = { key = "https://etherscan-optimism.com/" }
4901 amoy = { key = "https://etherscan-amoy.com/" }
4902 "#,
4903 )?;
4904
4905 let mut config = Config::load().unwrap();
4906
4907 let optimism = config.get_etherscan_api_key(Some(NamedChain::Optimism.into()));
4908 assert_eq!(optimism, Some("https://etherscan-optimism.com/".to_string()));
4909
4910 config.etherscan_api_key = Some("amoy".to_string());
4911
4912 let amoy = config.get_etherscan_api_key(Some(NamedChain::PolygonAmoy.into()));
4913 assert_eq!(amoy, Some("https://etherscan-amoy.com/".to_string()));
4914
4915 Ok(())
4916 });
4917 }
4918
4919 #[test]
4920 fn test_extract_etherscan_config_by_chain() {
4921 figment::Jail::expect_with(|jail| {
4922 jail.create_file(
4923 "foundry.toml",
4924 r#"
4925 [profile.default]
4926
4927 [etherscan]
4928 amoy = { key = "https://etherscan-amoy.com/", chain = 80002 }
4929 "#,
4930 )?;
4931
4932 let config = Config::load().unwrap();
4933
4934 let amoy = config
4935 .get_etherscan_config_with_chain(Some(NamedChain::PolygonAmoy.into()))
4936 .unwrap()
4937 .unwrap();
4938 assert_eq!(amoy.key, "https://etherscan-amoy.com/".to_string());
4939
4940 Ok(())
4941 });
4942 }
4943
4944 #[test]
4945 fn test_extract_etherscan_config_by_chain_with_url() {
4946 figment::Jail::expect_with(|jail| {
4947 jail.create_file(
4948 "foundry.toml",
4949 r#"
4950 [profile.default]
4951
4952 [etherscan]
4953 amoy = { key = "https://etherscan-amoy.com/", chain = 80002 , url = "https://verifier-url.com/"}
4954 "#,
4955 )?;
4956
4957 let config = Config::load().unwrap();
4958
4959 let amoy = config
4960 .get_etherscan_config_with_chain(Some(NamedChain::PolygonAmoy.into()))
4961 .unwrap()
4962 .unwrap();
4963 assert_eq!(amoy.key, "https://etherscan-amoy.com/".to_string());
4964 assert_eq!(amoy.api_url, "https://verifier-url.com/".to_string());
4965
4966 Ok(())
4967 });
4968 }
4969
4970 #[test]
4971 fn test_extract_etherscan_config_by_chain_and_alias() {
4972 figment::Jail::expect_with(|jail| {
4973 jail.create_file(
4974 "foundry.toml",
4975 r#"
4976 [profile.default]
4977 eth_rpc_url = "amoy"
4978
4979 [etherscan]
4980 amoy = { key = "https://etherscan-amoy.com/" }
4981
4982 [rpc_endpoints]
4983 amoy = "https://polygon-amoy.g.alchemy.com/v2/amoy"
4984 "#,
4985 )?;
4986
4987 let config = Config::load().unwrap();
4988
4989 let amoy = config.get_etherscan_config_with_chain(None).unwrap().unwrap();
4990 assert_eq!(amoy.key, "https://etherscan-amoy.com/".to_string());
4991
4992 let amoy_rpc = config.get_rpc_url().unwrap().unwrap();
4993 assert_eq!(amoy_rpc, "https://polygon-amoy.g.alchemy.com/v2/amoy");
4994 Ok(())
4995 });
4996 }
4997
4998 #[test]
4999 fn test_toml_file() {
5000 figment::Jail::expect_with(|jail| {
5001 jail.create_file(
5002 "foundry.toml",
5003 r#"
5004 [profile.default]
5005 src = "some-source"
5006 out = "some-out"
5007 cache = true
5008 eth_rpc_url = "https://example.com/"
5009 verbosity = 3
5010 remappings = ["ds-test=lib/ds-test/"]
5011 via_ir = true
5012 rpc_storage_caching = { chains = [1, "optimism", 999999], endpoints = "all"}
5013 use_literal_content = false
5014 bytecode_hash = "ipfs"
5015 cbor_metadata = true
5016 revert_strings = "strip"
5017 allow_paths = ["allow", "paths"]
5018 build_info_path = "build-info"
5019 always_use_create_2_factory = true
5020
5021 [rpc_endpoints]
5022 optimism = "https://example.com/"
5023 mainnet = "${RPC_MAINNET}"
5024 mainnet_2 = "https://eth-mainnet.alchemyapi.io/v2/${API_KEY}"
5025 mainnet_3 = "https://eth-mainnet.alchemyapi.io/v2/${API_KEY}/${ANOTHER_KEY}"
5026 "#,
5027 )?;
5028
5029 let config = Config::load().unwrap();
5030 assert_eq!(
5031 config,
5032 Config {
5033 src: "some-source".into(),
5034 out: "some-out".into(),
5035 cache: true,
5036 eth_rpc_url: Some("https://example.com/".to_string()),
5037 remappings: vec![Remapping::from_str("ds-test=lib/ds-test/").unwrap().into()],
5038 verbosity: 3,
5039 via_ir: true,
5040 rpc_storage_caching: StorageCachingConfig {
5041 chains: CachedChains::Chains(vec![
5042 Chain::mainnet(),
5043 Chain::optimism_mainnet(),
5044 Chain::from_id(999999)
5045 ]),
5046 endpoints: CachedEndpoints::All,
5047 },
5048 use_literal_content: false,
5049 bytecode_hash: BytecodeHash::Ipfs,
5050 cbor_metadata: true,
5051 revert_strings: Some(RevertStrings::Strip),
5052 allow_paths: vec![PathBuf::from("allow"), PathBuf::from("paths")],
5053 rpc_endpoints: RpcEndpoints::new([
5054 ("optimism", RpcEndpointUrl::Url("https://example.com/".to_string())),
5055 ("mainnet", RpcEndpointUrl::Env("${RPC_MAINNET}".to_string())),
5056 (
5057 "mainnet_2",
5058 RpcEndpointUrl::Env(
5059 "https://eth-mainnet.alchemyapi.io/v2/${API_KEY}".to_string()
5060 )
5061 ),
5062 (
5063 "mainnet_3",
5064 RpcEndpointUrl::Env(
5065 "https://eth-mainnet.alchemyapi.io/v2/${API_KEY}/${ANOTHER_KEY}"
5066 .to_string()
5067 )
5068 ),
5069 ]),
5070 build_info_path: Some("build-info".into()),
5071 always_use_create_2_factory: true,
5072 ..Config::default().normalized_optimizer_settings()
5073 }
5074 );
5075
5076 Ok(())
5077 });
5078 }
5079
5080 #[test]
5081 fn test_load_remappings() {
5082 figment::Jail::expect_with(|jail| {
5083 jail.create_file(
5084 "foundry.toml",
5085 r"
5086 [profile.default]
5087 remappings = ['nested/=lib/nested/']
5088 ",
5089 )?;
5090
5091 let config = Config::load_with_root(jail.directory()).unwrap();
5092 assert_eq!(
5093 config.remappings,
5094 vec![Remapping::from_str("nested/=lib/nested/").unwrap().into()]
5095 );
5096
5097 Ok(())
5098 });
5099 }
5100
5101 #[test]
5102 fn test_load_full_toml() {
5103 figment::Jail::expect_with(|jail| {
5104 jail.create_file(
5105 "foundry.toml",
5106 r#"
5107 [profile.default]
5108 auto_detect_solc = true
5109 block_base_fee_per_gas = 0
5110 block_coinbase = '0x0000000000000000000000000000000000000000'
5111 block_difficulty = 0
5112 block_prevrandao = '0x0000000000000000000000000000000000000000000000000000000000000000'
5113 block_number = 1
5114 fork_state_by_number = false
5115 block_timestamp = 1
5116 use_literal_content = false
5117 bytecode_hash = 'ipfs'
5118 cbor_metadata = true
5119 cache = true
5120 cache_path = 'cache'
5121 evm_version = 'london'
5122 extra_output = []
5123 extra_output_files = []
5124 always_use_create_2_factory = false
5125 ffi = false
5126 force = false
5127 gas_limit = 9223372036854775807
5128 gas_price = 0
5129 gas_reports = ['*']
5130 ignored_error_codes = [1878]
5131 ignored_warnings_from = ["something"]
5132 deny = "never"
5133 initial_balance = '0xffffffffffffffffffffffff'
5134 libraries = []
5135 libs = ['lib']
5136 memory_limit = 134217728
5137 names = false
5138 no_storage_caching = false
5139 no_fork_bal = false
5140 fork_prefetch = false
5141 no_rpc_rate_limit = false
5142 offline = false
5143 optimizer = true
5144 optimizer_runs = 200
5145 out = 'out'
5146 remappings = ['nested/=lib/nested/']
5147 sender = '0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38'
5148 sizes = false
5149 sparse_mode = false
5150 src = 'src'
5151 test = 'test'
5152 tx_origin = '0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38'
5153 verbosity = 0
5154 via_ir = false
5155
5156 [profile.default.rpc_storage_caching]
5157 chains = 'all'
5158 endpoints = 'all'
5159
5160 [rpc_endpoints]
5161 optimism = "https://example.com/"
5162 mainnet = "${RPC_MAINNET}"
5163 mainnet_2 = "https://eth-mainnet.alchemyapi.io/v2/${API_KEY}"
5164
5165 [fuzz]
5166 runs = 256
5167 seed = '0x3e8'
5168 max_test_rejects = 65536
5169
5170 [invariant]
5171 runs = 256
5172 depth = 500
5173 workers = 1
5174 fail_on_revert = false
5175 call_override = false
5176 shrink_run_limit = 5000
5177 "#,
5178 )?;
5179
5180 let config = Config::load_with_root(jail.directory()).unwrap();
5181
5182 assert_eq!(config.ignored_file_paths, vec![PathBuf::from("something")]);
5183 assert_eq!(config.fuzz.seed, Some(U256::from(1000)));
5184 assert_eq!(
5185 config.remappings,
5186 vec![Remapping::from_str("nested/=lib/nested/").unwrap().into()]
5187 );
5188
5189 assert_eq!(
5190 config.rpc_endpoints,
5191 RpcEndpoints::new([
5192 ("optimism", RpcEndpointUrl::Url("https://example.com/".to_string())),
5193 ("mainnet", RpcEndpointUrl::Env("${RPC_MAINNET}".to_string())),
5194 (
5195 "mainnet_2",
5196 RpcEndpointUrl::Env(
5197 "https://eth-mainnet.alchemyapi.io/v2/${API_KEY}".to_string()
5198 )
5199 ),
5200 ]),
5201 );
5202
5203 Ok(())
5204 });
5205 }
5206
5207 #[test]
5208 fn test_solc_req() {
5209 figment::Jail::expect_with(|jail| {
5210 jail.create_file(
5211 "foundry.toml",
5212 r#"
5213 [profile.default]
5214 solc_version = "0.8.12"
5215 "#,
5216 )?;
5217
5218 let config = Config::load().unwrap();
5219 assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 8, 12))));
5220
5221 jail.create_file(
5222 "foundry.toml",
5223 r#"
5224 [profile.default]
5225 solc = "0.8.12"
5226 "#,
5227 )?;
5228
5229 let config = Config::load().unwrap();
5230 assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 8, 12))));
5231
5232 jail.create_file(
5233 "foundry.toml",
5234 r#"
5235 [profile.default]
5236 solc = "path/to/local/solc"
5237 "#,
5238 )?;
5239
5240 let config = Config::load().unwrap();
5241 assert_eq!(config.solc, Some(SolcReq::Local("path/to/local/solc".into())));
5242
5243 for (solc, expected) in [
5246 ("solar:0.3.0", SolcReq::Solar(Version::new(0, 3, 0))),
5247 ("solar:0.3.0-dev", SolcReq::Local("solar:0.3.0-dev".into())),
5248 ("solar:0.1.8", SolcReq::Local("solar:0.1.8".into())),
5249 ("solar", SolcReq::Local("solar".into())),
5250 ("solar:0.3", SolcReq::Local("solar:0.3".into())),
5251 ] {
5252 jail.create_file("foundry.toml", &format!("[profile.default]\nsolc = {solc:?}"))?;
5253 let config = Config::load().unwrap();
5254 assert_eq!(config.solc, Some(expected.clone()));
5255 assert_eq!(SolcReq::from(solc), expected);
5256 assert_eq!(Config::from_provider(&config).unwrap().solc, Some(expected));
5257 }
5258 jail.set_env("FOUNDRY_SOLC_VERSION", "solar:0.3.0");
5259 let config = Config::load().unwrap();
5260 assert_eq!(config.solc, Some(SolcReq::Solar(Version::new(0, 3, 0))));
5261
5262 jail.set_env("FOUNDRY_SOLC_VERSION", "0.6.6");
5263 let config = Config::load().unwrap();
5264 assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 6, 6))));
5265 Ok(())
5266 });
5267 }
5268
5269 #[test]
5270 fn test_solc_env_preserves_standalone_sections() {
5271 for env in ["FOUNDRY_SOLC_VERSION", "DAPP_SOLC_VERSION"] {
5272 figment::Jail::expect_with(|jail| {
5273 jail.create_file(
5274 "foundry.toml",
5275 r#"
5276 [profile.default]
5277 solc_version = "0.8.12"
5278
5279 [profile.ci]
5280 solc = "0.8.20"
5281
5282 [etherscan]
5283 mainnet = { key = "test-key" }
5284
5285 [labels]
5286 0x0000000000000000000000000000000000000001 = "test-label"
5287
5288 [rpc_endpoints]
5289 mainnet = "https://example.com"
5290 "#,
5291 )?;
5292
5293 for (profile, version) in [("default", 12), ("ci", 20)] {
5294 jail.clear_env();
5295 jail.set_env("FOUNDRY_PROFILE", profile);
5296 let config = Config::load().unwrap();
5297 assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 8, version))));
5298
5299 jail.set_env(env, "0.6.6");
5300 let overridden = Config::load().unwrap();
5301 assert_eq!(overridden.solc, Some(SolcReq::Version(Version::new(0, 6, 6))));
5302 assert_eq!(overridden.rpc_endpoints, config.rpc_endpoints);
5303 assert_eq!(overridden.etherscan, config.etherscan);
5304 assert_eq!(overridden.labels, config.labels);
5305 assert_eq!(overridden.tracing.labels, config.tracing.labels);
5306 }
5307
5308 jail.set_env("DAPP_SOLC_VERSION", "0.7.6");
5309 jail.set_env("FOUNDRY_SOLC_VERSION", "0.6.6");
5310 assert_eq!(
5311 Config::load().unwrap().solc,
5312 Some(SolcReq::Version(Version::new(0, 6, 6))),
5313 );
5314 Ok(())
5315 });
5316 }
5317 }
5318
5319 #[test]
5320 fn test_legacy_keys_in_standalone_named_profiles() {
5321 for profile in ["coverage", "fuzz", "lint", "symbolic"] {
5322 figment::Jail::expect_with(|jail| {
5323 jail.create_file(
5324 "foundry.toml",
5325 &format!(
5326 r#"
5327 [profile.default]
5328 solc = "0.8.12"
5329
5330 [profile.{profile}]
5331 solc_version = "0.8.20"
5332 deny_warnings = true
5333 labels = {{ "0x0000000000000000000000000000000000000001" = "test-label" }}
5334 "#,
5335 ),
5336 )?;
5337 jail.set_env("FOUNDRY_PROFILE", profile);
5338 let config = Config::load().unwrap();
5339 assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 8, 20))));
5340 assert_eq!(config.deny, DenyLevel::Warnings);
5341 assert_eq!(config.tracing.labels, config.labels);
5342 assert_eq!(config.labels.len(), 1);
5343
5344 for env in ["FOUNDRY_SOLC_VERSION", "DAPP_SOLC_VERSION"] {
5345 jail.set_env(env, "0.6.6");
5346 let overridden = Config::load().unwrap();
5347 assert_eq!(overridden.solc, Some(SolcReq::Version(Version::new(0, 6, 6))));
5348 jail.clear_env();
5349 jail.set_env("FOUNDRY_PROFILE", profile);
5350 }
5351 Ok(())
5352 });
5353 }
5354 }
5355
5356 #[test]
5357 fn test_legacy_keys_preserve_rpc_aliases() {
5358 figment::Jail::expect_with(|jail| {
5359 jail.create_file(
5360 "foundry.toml",
5361 r#"
5362 [rpc_endpoints]
5363 solc_version = "https://compiler.example.com"
5364 deny_warnings = "https://warnings.example.com"
5365 "#,
5366 )?;
5367
5368 let config = Config::load().unwrap();
5369 assert_eq!(
5370 config.rpc_endpoints,
5371 RpcEndpoints::new([
5372 ("solc_version", RpcEndpointUrl::Url("https://compiler.example.com".into())),
5373 ("deny_warnings", RpcEndpointUrl::Url("https://warnings.example.com".into())),
5374 ]),
5375 );
5376 Ok(())
5377 });
5378 }
5379
5380 #[test]
5382 fn test_backwards_solc_version() {
5383 figment::Jail::expect_with(|jail| {
5384 jail.create_file(
5385 "foundry.toml",
5386 r#"
5387 [default]
5388 solc = "0.8.12"
5389 solc_version = "0.8.20"
5390 "#,
5391 )?;
5392
5393 let config = Config::load().unwrap();
5394 assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 8, 12))));
5395
5396 Ok(())
5397 });
5398
5399 figment::Jail::expect_with(|jail| {
5400 jail.create_file(
5401 "foundry.toml",
5402 r#"
5403 [default]
5404 solc_version = "0.8.20"
5405 "#,
5406 )?;
5407
5408 let config = Config::load().unwrap();
5409 assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 8, 20))));
5410
5411 Ok(())
5412 });
5413 }
5414
5415 #[test]
5416 fn test_toml_casing_file() {
5417 figment::Jail::expect_with(|jail| {
5418 jail.create_file(
5419 "foundry.toml",
5420 r#"
5421 [profile.default]
5422 src = "some-source"
5423 out = "some-out"
5424 cache = true
5425 eth-rpc-url = "https://example.com/"
5426 evm-version = "berlin"
5427 auto-detect-solc = false
5428 "#,
5429 )?;
5430
5431 let config = Config::load().unwrap();
5432 assert_eq!(
5433 config,
5434 Config {
5435 src: "some-source".into(),
5436 out: "some-out".into(),
5437 cache: true,
5438 eth_rpc_url: Some("https://example.com/".to_string()),
5439 auto_detect_solc: false,
5440 evm_version: EvmVersion::Berlin,
5441 ..Config::default().normalized_optimizer_settings()
5442 }
5443 );
5444
5445 Ok(())
5446 });
5447 }
5448
5449 #[test]
5450 fn test_output_selection() {
5451 figment::Jail::expect_with(|jail| {
5452 jail.create_file(
5453 "foundry.toml",
5454 r#"
5455 [profile.default]
5456 extra_output = ["metadata", "ir-optimized"]
5457 extra_output_files = ["metadata"]
5458 "#,
5459 )?;
5460
5461 let config = Config::load().unwrap();
5462
5463 assert_eq!(
5464 config.extra_output,
5465 vec![ContractOutputSelection::Metadata, ContractOutputSelection::IrOptimized]
5466 );
5467 assert_eq!(config.extra_output_files, vec![ContractOutputSelection::Metadata]);
5468
5469 Ok(())
5470 });
5471 }
5472
5473 #[test]
5474 fn test_precedence() {
5475 figment::Jail::expect_with(|jail| {
5476 jail.create_file(
5477 "foundry.toml",
5478 r#"
5479 [profile.default]
5480 src = "mysrc"
5481 out = "myout"
5482 verbosity = 3
5483 "#,
5484 )?;
5485
5486 let config = Config::load().unwrap();
5487 assert_eq!(
5488 config,
5489 Config {
5490 src: "mysrc".into(),
5491 out: "myout".into(),
5492 verbosity: 3,
5493 ..Config::default().normalized_optimizer_settings()
5494 }
5495 );
5496
5497 jail.set_env("FOUNDRY_SRC", r"other-src");
5498 let config = Config::load().unwrap();
5499 assert_eq!(
5500 config,
5501 Config {
5502 src: "other-src".into(),
5503 out: "myout".into(),
5504 verbosity: 3,
5505 ..Config::default().normalized_optimizer_settings()
5506 }
5507 );
5508
5509 jail.set_env("FOUNDRY_PROFILE", "foo");
5510 let val: Result<String, _> = Config::figment().extract_inner("profile");
5511 assert!(val.is_err());
5512
5513 Ok(())
5514 });
5515 }
5516
5517 #[test]
5518 fn test_extract_basic() {
5519 figment::Jail::expect_with(|jail| {
5520 jail.create_file(
5521 "foundry.toml",
5522 r#"
5523 [profile.default]
5524 src = "mysrc"
5525 out = "myout"
5526 verbosity = 3
5527 evm_version = 'berlin'
5528
5529 [profile.other]
5530 src = "other-src"
5531 "#,
5532 )?;
5533 let loaded = Config::load().unwrap();
5534 assert_eq!(loaded.evm_version, EvmVersion::Berlin);
5535 let base = loaded.into_basic();
5536 let default = Config::default();
5537 assert_eq!(
5538 base,
5539 BasicConfig {
5540 profile: Config::DEFAULT_PROFILE,
5541 src: "mysrc".into(),
5542 out: "myout".into(),
5543 libs: default.libs.clone(),
5544 remappings: default.remappings.clone(),
5545 network: None,
5546 }
5547 );
5548 jail.set_env("FOUNDRY_PROFILE", r"other");
5549 let base = Config::figment().extract::<BasicConfig>().unwrap();
5550 assert_eq!(
5551 base,
5552 BasicConfig {
5553 profile: Config::DEFAULT_PROFILE,
5554 src: "other-src".into(),
5555 out: "myout".into(),
5556 libs: default.libs.clone(),
5557 remappings: default.remappings,
5558 network: None,
5559 }
5560 );
5561 Ok(())
5562 });
5563 }
5564
5565 #[test]
5566 #[should_panic]
5567 fn test_parse_invalid_fuzz_weight() {
5568 figment::Jail::expect_with(|jail| {
5569 jail.create_file(
5570 "foundry.toml",
5571 r"
5572 [fuzz]
5573 dictionary_weight = 101
5574 ",
5575 )?;
5576 let _config = Config::load().unwrap();
5577 Ok(())
5578 });
5579 }
5580
5581 #[test]
5582 fn test_fallback_provider() {
5583 figment::Jail::expect_with(|jail| {
5584 jail.create_file(
5585 "foundry.toml",
5586 r"
5587 [fuzz]
5588 runs = 1
5589 include_storage = false
5590 dictionary_weight = 99
5591
5592 [invariant]
5593 runs = 420
5594
5595 [profile.ci.fuzz]
5596 dictionary_weight = 5
5597
5598 [profile.ci.invariant]
5599 runs = 400
5600 ",
5601 )?;
5602
5603 let invariant_default = InvariantConfig::default();
5604 let config = Config::load().unwrap();
5605
5606 assert_ne!(config.invariant.runs, config.fuzz.runs);
5607 assert_eq!(config.invariant.runs, 420);
5608
5609 assert_ne!(
5610 config.fuzz.dictionary.include_storage,
5611 invariant_default.dictionary.include_storage
5612 );
5613 assert_eq!(
5614 config.invariant.dictionary.include_storage,
5615 config.fuzz.dictionary.include_storage
5616 );
5617
5618 assert_ne!(
5619 config.fuzz.dictionary.dictionary_weight,
5620 invariant_default.dictionary.dictionary_weight
5621 );
5622 assert_eq!(
5623 config.invariant.dictionary.dictionary_weight,
5624 config.fuzz.dictionary.dictionary_weight
5625 );
5626
5627 jail.set_env("FOUNDRY_PROFILE", "ci");
5628 let ci_config = Config::load().unwrap();
5629 assert_eq!(ci_config.fuzz.runs, 1);
5630 assert_eq!(ci_config.invariant.runs, 400);
5631 assert_eq!(ci_config.fuzz.dictionary.dictionary_weight, 5);
5632 assert_eq!(
5633 ci_config.invariant.dictionary.dictionary_weight,
5634 config.fuzz.dictionary.dictionary_weight
5635 );
5636
5637 Ok(())
5638 })
5639 }
5640
5641 #[test]
5642 fn test_standalone_profile_sections() {
5643 figment::Jail::expect_with(|jail| {
5644 jail.create_file(
5645 "foundry.toml",
5646 r#"
5647 [fuzz]
5648 runs = 100
5649
5650 [invariant]
5651 runs = 120
5652
5653 [symbolic]
5654 enabled = true
5655 max_paths = 12
5656 storage_layout = "generic"
5657
5658 [profile.ci.fuzz]
5659 runs = 420
5660
5661 [profile.ci.invariant]
5662 runs = 500
5663
5664 [profile.ci.symbolic]
5665 max_paths = 34
5666 dump_smt = true
5667 "#,
5668 )?;
5669
5670 let config = Config::load().unwrap();
5671 assert_eq!(config.fuzz.runs, 100);
5672 assert_eq!(config.invariant.runs, 120);
5673 assert!(config.symbolic.enabled);
5674 assert_eq!(config.symbolic.max_paths, 12);
5675 assert_eq!(config.symbolic.storage_layout, SymbolicStorageLayout::Generic);
5676 assert!(!config.symbolic.dump_smt);
5677
5678 jail.set_env("FOUNDRY_PROFILE", "ci");
5679 let config = Config::load().unwrap();
5680 assert_eq!(config.fuzz.runs, 420);
5681 assert_eq!(config.invariant.runs, 500);
5682 assert!(config.symbolic.enabled);
5683 assert_eq!(config.symbolic.max_paths, 34);
5684 assert_eq!(config.symbolic.storage_layout, SymbolicStorageLayout::Generic);
5685 assert!(config.symbolic.dump_smt);
5686
5687 Ok(())
5688 });
5689 }
5690
5691 #[test]
5692 fn can_handle_deviating_dapp_aliases() {
5693 figment::Jail::expect_with(|jail| {
5694 let addr = Address::ZERO;
5695 jail.set_env("DAPP_TEST_NUMBER", 1337);
5696 jail.set_env("DAPP_TEST_ADDRESS", format!("{addr:?}"));
5697 jail.set_env("DAPP_TEST_FUZZ_RUNS", 420);
5698 jail.set_env("DAPP_TEST_DEPTH", 20);
5699 jail.set_env("DAPP_FORK_BLOCK", 100);
5700 jail.set_env("DAPP_BUILD_OPTIMIZE_RUNS", 999);
5701 jail.set_env("DAPP_BUILD_OPTIMIZE", 0);
5702
5703 let config = Config::load().unwrap();
5704
5705 assert_eq!(config.block_number, U256::from(1337));
5706 assert_eq!(config.sender, addr);
5707 assert_eq!(config.fuzz.runs, 420);
5708 assert_eq!(config.invariant.depth, 20);
5709 assert_eq!(config.fork_block_number, Some(100));
5710 assert_eq!(config.optimizer_runs, Some(999));
5711 assert!(!config.optimizer.unwrap());
5712
5713 Ok(())
5714 });
5715 }
5716
5717 #[test]
5718 fn can_parse_libraries() {
5719 figment::Jail::expect_with(|jail| {
5720 jail.set_env(
5721 "DAPP_LIBRARIES",
5722 "[src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6]",
5723 );
5724 let config = Config::load().unwrap();
5725 assert_eq!(
5726 config.libraries,
5727 vec![
5728 "src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6"
5729 .to_string()
5730 ]
5731 );
5732
5733 jail.set_env(
5734 "DAPP_LIBRARIES",
5735 "src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6",
5736 );
5737 let config = Config::load().unwrap();
5738 assert_eq!(
5739 config.libraries,
5740 vec![
5741 "src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6"
5742 .to_string(),
5743 ]
5744 );
5745
5746 jail.set_env(
5747 "DAPP_LIBRARIES",
5748 "src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6,src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6",
5749 );
5750 let config = Config::load().unwrap();
5751 assert_eq!(
5752 config.libraries,
5753 vec![
5754 "src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6"
5755 .to_string(),
5756 "src/DssSpell.sol:DssExecLib:0x8De6DDbCd5053d32292AAA0D2105A32d108484a6"
5757 .to_string()
5758 ]
5759 );
5760
5761 Ok(())
5762 });
5763 }
5764
5765 #[test]
5766 fn can_parse_libraries_with_whitespace() {
5767 figment::Jail::expect_with(|jail| {
5768 jail.set_env(
5769 "FOUNDRY_LIBRARIES",
5770 " [src/A.sol:A:0x1111111111111111111111111111111111111111, src/B.sol:B:0x2222222222222222222222222222222222222222,]\n",
5771 );
5772 let config = Config::load().unwrap();
5773
5774 similar_asserts::assert_eq!(
5775 config.parsed_libraries().unwrap().libs,
5776 BTreeMap::from([
5777 (
5778 PathBuf::from("src/A.sol"),
5779 BTreeMap::from([(
5780 "A".to_string(),
5781 "0x1111111111111111111111111111111111111111".to_string(),
5782 )]),
5783 ),
5784 (
5785 PathBuf::from("src/B.sol"),
5786 BTreeMap::from([(
5787 "B".to_string(),
5788 "0x2222222222222222222222222222222222222222".to_string(),
5789 )]),
5790 ),
5791 ])
5792 );
5793
5794 Ok(())
5795 });
5796 }
5797
5798 #[test]
5799 fn can_parse_empty_libraries() {
5800 for env_var in ["DAPP_LIBRARIES", "FOUNDRY_LIBRARIES"] {
5801 for value in ["", "[]", "[ ]", "[\t\n]", " [,]\n"] {
5802 figment::Jail::expect_with(|jail| {
5803 jail.create_file(
5804 "foundry.toml",
5805 r#"
5806 [profile.default]
5807 libraries = ["src/A.sol:A:0x1111111111111111111111111111111111111111"]
5808 "#,
5809 )?;
5810 assert_eq!(Config::load().unwrap().libraries.len(), 1);
5811
5812 jail.set_env(env_var, value);
5813 let config = Config::load().unwrap();
5814 assert!(config.libraries.is_empty(), "{env_var}={value:?}");
5815 assert!(config.parsed_libraries().unwrap().libs.is_empty());
5816
5817 Ok(())
5818 });
5819 }
5820 }
5821 }
5822
5823 #[test]
5824 fn test_parse_many_libraries() {
5825 figment::Jail::expect_with(|jail| {
5826 jail.create_file(
5827 "foundry.toml",
5828 r"
5829 [profile.default]
5830 libraries= [
5831 './src/SizeAuctionDiscount.sol:Chainlink:0xffedba5e171c4f15abaaabc86e8bd01f9b54dae5',
5832 './src/SizeAuction.sol:ChainlinkTWAP:0xffedba5e171c4f15abaaabc86e8bd01f9b54dae5',
5833 './src/SizeAuction.sol:Math:0x902f6cf364b8d9470d5793a9b2b2e86bddd21e0c',
5834 './src/test/ChainlinkTWAP.t.sol:ChainlinkTWAP:0xffedba5e171c4f15abaaabc86e8bd01f9b54dae5',
5835 './src/SizeAuctionDiscount.sol:Math:0x902f6cf364b8d9470d5793a9b2b2e86bddd21e0c',
5836 ]
5837 ",
5838 )?;
5839 let config = Config::load().unwrap();
5840
5841 let libs = config.parsed_libraries().unwrap().libs;
5842
5843 similar_asserts::assert_eq!(
5844 libs,
5845 BTreeMap::from([
5846 (
5847 PathBuf::from("./src/SizeAuctionDiscount.sol"),
5848 BTreeMap::from([
5849 (
5850 "Chainlink".to_string(),
5851 "0xffedba5e171c4f15abaaabc86e8bd01f9b54dae5".to_string()
5852 ),
5853 (
5854 "Math".to_string(),
5855 "0x902f6cf364b8d9470d5793a9b2b2e86bddd21e0c".to_string()
5856 )
5857 ])
5858 ),
5859 (
5860 PathBuf::from("./src/SizeAuction.sol"),
5861 BTreeMap::from([
5862 (
5863 "ChainlinkTWAP".to_string(),
5864 "0xffedba5e171c4f15abaaabc86e8bd01f9b54dae5".to_string()
5865 ),
5866 (
5867 "Math".to_string(),
5868 "0x902f6cf364b8d9470d5793a9b2b2e86bddd21e0c".to_string()
5869 )
5870 ])
5871 ),
5872 (
5873 PathBuf::from("./src/test/ChainlinkTWAP.t.sol"),
5874 BTreeMap::from([(
5875 "ChainlinkTWAP".to_string(),
5876 "0xffedba5e171c4f15abaaabc86e8bd01f9b54dae5".to_string()
5877 )])
5878 ),
5879 ])
5880 );
5881
5882 Ok(())
5883 });
5884 }
5885
5886 #[test]
5887 fn config_roundtrip() {
5888 figment::Jail::expect_with(|jail| {
5889 let default = Config::default().normalized_optimizer_settings();
5890 let basic = default.clone().into_basic();
5891 jail.create_file("foundry.toml", &basic.to_string_pretty().unwrap())?;
5892
5893 let mut other = Config::load().unwrap();
5894 clear_warning(&mut other);
5895 assert_eq!(default, other);
5896
5897 let other = other.into_basic();
5898 assert_eq!(basic, other);
5899
5900 jail.create_file("foundry.toml", &default.to_string_pretty().unwrap())?;
5901 let mut other = Config::load().unwrap();
5902 clear_warning(&mut other);
5903 let mut serialized_default = default;
5904 mark_serialized_invariant_provenance(&mut serialized_default);
5905 assert_eq!(serialized_default, other);
5906
5907 Ok(())
5908 });
5909 }
5910
5911 #[test]
5912 fn config_serialization_preserves_context_directory_boundary() {
5913 let remapping = "lib/outer/:inner/=lib/outer/lib/inner/";
5914 let config = Config {
5915 remappings: vec![Remapping::from_str(remapping).unwrap().into()],
5916 ..Default::default()
5917 };
5918
5919 let serialized = toml::Value::try_from(&config).unwrap();
5920 assert_eq!(serialized["remappings"][0].as_str(), Some(remapping));
5921
5922 let serialized = toml::Value::try_from(config.into_basic()).unwrap();
5923 assert_eq!(serialized["remappings"][0].as_str(), Some(remapping));
5924 }
5925
5926 #[cfg(windows)]
5927 #[test]
5928 fn config_serialization_preserves_verbatim_unc_context() {
5929 let remapping = r"\\?\UNC\server\share\project\:inner/=lib/inner/";
5930 let expected = r"\\?\UNC\server\share/project/:inner/=lib/inner/";
5931 let config = Config {
5932 remappings: vec![Remapping::from_str(remapping).unwrap().into()],
5933 ..Default::default()
5934 };
5935
5936 let serialized = toml::Value::try_from(&config).unwrap();
5937 assert_eq!(serialized["remappings"][0].as_str(), Some(expected));
5938
5939 let serialized = toml::Value::try_from(config.into_basic()).unwrap();
5940 assert_eq!(serialized["remappings"][0].as_str(), Some(expected));
5941 }
5942
5943 #[test]
5944 fn test_fs_permissions() {
5945 figment::Jail::expect_with(|jail| {
5946 jail.create_file(
5947 "foundry.toml",
5948 r#"
5949 [profile.default]
5950 fs_permissions = [{ access = "read-write", path = "./"}]
5951 "#,
5952 )?;
5953 let loaded = Config::load().unwrap();
5954
5955 assert_eq!(
5956 loaded.fs_permissions,
5957 FsPermissions::new(vec![PathPermission::read_write("./")])
5958 );
5959
5960 jail.create_file(
5961 "foundry.toml",
5962 r#"
5963 [profile.default]
5964 fs_permissions = [{ access = "none", path = "./"}]
5965 "#,
5966 )?;
5967 let loaded = Config::load().unwrap();
5968 assert_eq!(loaded.fs_permissions, FsPermissions::new(vec![PathPermission::none("./")]));
5969
5970 Ok(())
5971 });
5972 }
5973
5974 #[test]
5975 fn test_optimizer_settings_basic() {
5976 figment::Jail::expect_with(|jail| {
5977 jail.create_file(
5978 "foundry.toml",
5979 r"
5980 [profile.default]
5981 optimizer = true
5982
5983 [profile.default.optimizer_details]
5984 yul = false
5985
5986 [profile.default.optimizer_details.yulDetails]
5987 stackAllocation = true
5988 ",
5989 )?;
5990 let mut loaded = Config::load().unwrap();
5991 clear_warning(&mut loaded);
5992 assert_eq!(
5993 loaded.optimizer_details,
5994 Some(OptimizerDetails {
5995 yul: Some(false),
5996 yul_details: Some(YulDetails {
5997 stack_allocation: Some(true),
5998 ..Default::default()
5999 }),
6000 ..Default::default()
6001 })
6002 );
6003
6004 let s = loaded.to_string_pretty().unwrap();
6005 jail.create_file("foundry.toml", &s)?;
6006 mark_serialized_invariant_provenance(&mut loaded);
6007
6008 let mut reloaded = Config::load().unwrap();
6009 clear_warning(&mut reloaded);
6010 assert_eq!(loaded, reloaded);
6011
6012 Ok(())
6013 });
6014 }
6015
6016 #[test]
6017 fn test_model_checker_settings_basic() {
6018 figment::Jail::expect_with(|jail| {
6019 jail.create_file(
6020 "foundry.toml",
6021 r"
6022 [profile.default]
6023
6024 [profile.default.model_checker]
6025 contracts = { 'a.sol' = [ 'A1', 'A2' ], 'b.sol' = [ 'B1', 'B2' ] }
6026 engine = 'chc'
6027 targets = [ 'assert', 'outOfBounds' ]
6028 timeout = 10000
6029 ",
6030 )?;
6031 let mut loaded = Config::load().unwrap();
6032 clear_warning(&mut loaded);
6033 assert_eq!(
6034 loaded.model_checker,
6035 Some(ModelCheckerSettings {
6036 contracts: BTreeMap::from([
6037 ("a.sol".to_string(), vec!["A1".to_string(), "A2".to_string()]),
6038 ("b.sol".to_string(), vec!["B1".to_string(), "B2".to_string()]),
6039 ]),
6040 engine: Some(ModelCheckerEngine::CHC),
6041 targets: Some(vec![
6042 ModelCheckerTarget::Assert,
6043 ModelCheckerTarget::OutOfBounds
6044 ]),
6045 timeout: Some(10000),
6046 invariants: None,
6047 show_unproved: None,
6048 div_mod_with_slacks: None,
6049 solvers: None,
6050 show_unsupported: None,
6051 show_proved_safe: None,
6052 })
6053 );
6054
6055 let s = loaded.to_string_pretty().unwrap();
6056 jail.create_file("foundry.toml", &s)?;
6057 mark_serialized_invariant_provenance(&mut loaded);
6058
6059 let mut reloaded = Config::load().unwrap();
6060 clear_warning(&mut reloaded);
6061 assert_eq!(loaded, reloaded);
6062
6063 Ok(())
6064 });
6065 }
6066
6067 #[test]
6068 fn test_model_checker_settings_with_bool_flags() {
6069 figment::Jail::expect_with(|jail| {
6070 jail.create_file(
6071 "foundry.toml",
6072 r"
6073 [profile.default]
6074
6075 [profile.default.model_checker]
6076 engine = 'chc'
6077 show_unproved = true
6078 show_unsupported = true
6079 show_proved_safe = false
6080 div_mod_with_slacks = true
6081 ",
6082 )?;
6083 let mut loaded = Config::load().unwrap();
6084 clear_warning(&mut loaded);
6085
6086 let mc = loaded.model_checker.as_ref().unwrap();
6087 assert_eq!(mc.show_unproved, Some(true));
6088 assert_eq!(mc.show_unsupported, Some(true));
6089 assert_eq!(mc.show_proved_safe, Some(false));
6090 assert_eq!(mc.div_mod_with_slacks, Some(true));
6091
6092 let s = loaded.to_string_pretty().unwrap();
6094 jail.create_file("foundry.toml", &s)?;
6095
6096 let mut reloaded = Config::load().unwrap();
6097 clear_warning(&mut reloaded);
6098
6099 let mc_reloaded = reloaded.model_checker.as_ref().unwrap();
6100 assert_eq!(mc_reloaded.show_unproved, Some(true));
6101 assert_eq!(mc_reloaded.show_unsupported, Some(true));
6102 assert_eq!(mc_reloaded.show_proved_safe, Some(false));
6103 assert_eq!(mc_reloaded.div_mod_with_slacks, Some(true));
6104
6105 Ok(())
6106 });
6107 }
6108
6109 #[test]
6110 fn test_model_checker_settings_relative_paths() {
6111 figment::Jail::expect_with(|jail| {
6112 jail.create_file(
6113 "foundry.toml",
6114 r"
6115 [profile.default]
6116
6117 [profile.default.model_checker]
6118 contracts = { 'a.sol' = [ 'A1', 'A2' ], 'b.sol' = [ 'B1', 'B2' ] }
6119 engine = 'chc'
6120 targets = [ 'assert', 'outOfBounds' ]
6121 timeout = 10000
6122 ",
6123 )?;
6124 let loaded = Config::load().unwrap().sanitized();
6125
6126 let dir = foundry_compilers::utils::canonicalize(jail.directory())
6131 .expect("Could not canonicalize jail path");
6132 assert_eq!(
6133 loaded.model_checker,
6134 Some(ModelCheckerSettings {
6135 contracts: BTreeMap::from([
6136 (
6137 format!("{}", dir.join("a.sol").display()),
6138 vec!["A1".to_string(), "A2".to_string()]
6139 ),
6140 (
6141 format!("{}", dir.join("b.sol").display()),
6142 vec!["B1".to_string(), "B2".to_string()]
6143 ),
6144 ]),
6145 engine: Some(ModelCheckerEngine::CHC),
6146 targets: Some(vec![
6147 ModelCheckerTarget::Assert,
6148 ModelCheckerTarget::OutOfBounds
6149 ]),
6150 timeout: Some(10000),
6151 invariants: None,
6152 show_unproved: None,
6153 div_mod_with_slacks: None,
6154 solvers: None,
6155 show_unsupported: None,
6156 show_proved_safe: None,
6157 })
6158 );
6159
6160 Ok(())
6161 });
6162 }
6163
6164 #[test]
6165 fn test_fmt_config() {
6166 figment::Jail::expect_with(|jail| {
6167 jail.create_file(
6168 "foundry.toml",
6169 r#"
6170 [fmt]
6171 line_length = 100
6172 tab_width = 2
6173 bracket_spacing = true
6174 style = "space"
6175 "#,
6176 )?;
6177 let loaded = Config::load().unwrap().sanitized();
6178 assert_eq!(
6179 loaded.fmt,
6180 FormatterConfig {
6181 line_length: 100,
6182 tab_width: 2,
6183 bracket_spacing: true,
6184 style: IndentStyle::Space,
6185 ..Default::default()
6186 }
6187 );
6188
6189 Ok(())
6190 });
6191 }
6192
6193 #[test]
6194 fn test_lint_config() {
6195 figment::Jail::expect_with(|jail| {
6196 jail.create_file(
6197 "foundry.toml",
6198 r"
6199 [lint]
6200 severity = ['high', 'medium']
6201 exclude_lints = ['incorrect-shift']
6202 ",
6203 )?;
6204 let loaded = Config::load().unwrap().sanitized();
6205 assert_eq!(
6206 loaded.lint,
6207 LinterConfig {
6208 severity: vec![LintSeverity::High, LintSeverity::Med],
6209 exclude_lints: vec!["incorrect-shift".into()],
6210 ..Default::default()
6211 }
6212 );
6213
6214 Ok(())
6215 });
6216 }
6217
6218 #[test]
6219 fn test_invariant_config() {
6220 figment::Jail::expect_with(|jail| {
6221 jail.create_file(
6222 "foundry.toml",
6223 r#"
6224 [invariant]
6225 runs = 512
6226 depth = 10
6227 min_depth = 2
6228 depth_mode = "random"
6229 workers = 4
6230 corpus_random_sequence_weight = 30
6231 payable_value_weight = 12
6232 mutation_weight_cmp = 7
6233 "#,
6234 )?;
6235
6236 let loaded = Config::load().unwrap().sanitized();
6237 assert_eq!(
6238 loaded.invariant,
6239 InvariantConfig {
6240 runs: 512,
6241 depth: 10,
6242 min_depth: 2,
6243 depth_mode: InvariantDepthMode::Random,
6244 workers: InvariantWorkers::Fixed(NonZeroUsize::new(4).unwrap()),
6245 corpus: FuzzCorpusConfig {
6246 corpus_random_sequence_weight: 30,
6247 payable_value_weight: 12,
6248 mutation_weights: FuzzCorpusMutationWeights {
6249 mutation_weight_cmp: 7,
6250 ..Default::default()
6251 },
6252 ..Default::default()
6253 },
6254 corpus_random_sequence_weight_configured: true,
6255 workers_configured: true,
6256 failure_persist_dir: Some(PathBuf::from("cache/invariant")),
6257 ..Default::default()
6258 }
6259 );
6260 assert!(loaded.invariant.corpus_random_sequence_weight_configured);
6261
6262 Ok(())
6263 });
6264 }
6265
6266 #[test]
6267 fn test_invariant_corpus_random_sequence_weight_provenance() {
6268 figment::Jail::expect_with(|jail| {
6269 jail.create_file(
6270 "foundry.toml",
6271 r#"
6272 [invariant]
6273 depth = 10
6274 "#,
6275 )?;
6276
6277 let loaded = Config::load().unwrap();
6278 assert_eq!(
6279 loaded.invariant.corpus.corpus_random_sequence_weight,
6280 FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
6281 );
6282 assert!(!loaded.invariant.corpus_random_sequence_weight_configured);
6283 assert!(!loaded.invariant.workers_configured);
6284
6285 jail.create_file(
6286 "foundry.toml",
6287 r#"
6288 [invariant]
6289 corpus_random_sequence_weight = 10
6290 workers = 4
6291 "#,
6292 )?;
6293
6294 let loaded = Config::load().unwrap();
6295 assert_eq!(
6296 loaded.invariant.corpus.corpus_random_sequence_weight,
6297 FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
6298 );
6299 assert!(loaded.invariant.corpus_random_sequence_weight_configured);
6300 assert_eq!(
6301 loaded.invariant.workers,
6302 InvariantWorkers::Fixed(NonZeroUsize::new(4).unwrap())
6303 );
6304 assert!(loaded.invariant.workers_configured);
6305
6306 Ok(())
6307 });
6308 }
6309
6310 #[test]
6311 fn test_fuzz_corpus_random_sequence_weight_fallback_does_not_mark_invariant_configured() {
6312 figment::Jail::expect_with(|jail| {
6313 jail.create_file(
6314 "foundry.toml",
6315 r#"
6316 [fuzz]
6317 corpus_random_sequence_weight = 10
6318 "#,
6319 )?;
6320
6321 let loaded = Config::load().unwrap();
6322 assert_eq!(
6323 loaded.invariant.corpus.corpus_random_sequence_weight,
6324 FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
6325 );
6326 assert!(!loaded.invariant.corpus_random_sequence_weight_configured);
6327
6328 Ok(())
6329 });
6330 }
6331
6332 #[test]
6333 fn test_standalone_sections_env() {
6334 figment::Jail::expect_with(|jail| {
6335 jail.create_file(
6336 "foundry.toml",
6337 r"
6338 [fuzz]
6339 runs = 100
6340
6341 [invariant]
6342 depth = 1
6343 ",
6344 )?;
6345
6346 jail.set_env("FOUNDRY_FMT_LINE_LENGTH", "95");
6347 jail.set_env("FOUNDRY_FUZZ_DICTIONARY_WEIGHT", "99");
6348 jail.set_env("FOUNDRY_FUZZ_MAX_FUZZ_DICTIONARY_VALUES", "max");
6349 jail.set_env("FOUNDRY_INVARIANT_DEPTH", "5");
6350 jail.set_env("FOUNDRY_INVARIANT_MIN_DEPTH", "2");
6351 jail.set_env("FOUNDRY_INVARIANT_DEPTH_MODE", "random");
6352 jail.set_env("FOUNDRY_INVARIANT_WORKERS", "3");
6353 jail.set_env("FOUNDRY_INVARIANT_CORPUS_RANDOM_SEQUENCE_WEIGHT", "30");
6354 jail.set_env("FOUNDRY_INVARIANT_PAYABLE_VALUE_WEIGHT", "12");
6355 jail.set_env("FOUNDRY_INVARIANT_MUTATION_WEIGHT_CMP", "7");
6356 jail.set_env("FOUNDRY_SYMBOLIC_MAX_PATHS", "64");
6357 jail.set_env("FOUNDRY_SYMBOLIC_DUMP_SMT", "true");
6358
6359 let config = Config::load().unwrap();
6360 assert_eq!(config.fmt.line_length, 95);
6361 assert_eq!(config.fuzz.dictionary.dictionary_weight, 99);
6362 assert_eq!(config.fuzz.dictionary.max_fuzz_dictionary_values, usize::MAX);
6363 assert_eq!(config.invariant.depth, 5);
6364 assert_eq!(config.invariant.min_depth, 2);
6365 assert_eq!(config.invariant.depth_mode, InvariantDepthMode::Random);
6366 assert_eq!(
6367 config.invariant.workers,
6368 InvariantWorkers::Fixed(NonZeroUsize::new(3).unwrap())
6369 );
6370 assert_eq!(config.invariant.corpus.corpus_random_sequence_weight, 30);
6371 assert!(config.invariant.corpus_random_sequence_weight_configured);
6372 assert_eq!(config.invariant.corpus.payable_value_weight, 12);
6373 assert_eq!(config.invariant.corpus.mutation_weights.mutation_weight_cmp, 7);
6374 assert_eq!(config.symbolic.max_paths, 64);
6375 assert!(config.symbolic.dump_smt);
6376
6377 Ok(())
6378 });
6379 }
6380
6381 #[test]
6382 fn test_invariant_workers_env_accepts_auto() {
6383 figment::Jail::expect_with(|jail| {
6384 jail.create_file(
6385 "foundry.toml",
6386 r"
6387 [invariant]
6388 workers = 3
6389 ",
6390 )?;
6391
6392 jail.set_env("FOUNDRY_INVARIANT_WORKERS", "auto");
6393
6394 let config = Config::load().unwrap();
6395 assert_eq!(config.invariant.workers, InvariantWorkers::Auto);
6396
6397 Ok(())
6398 });
6399 }
6400
6401 #[test]
6402 fn test_parse_with_profile() {
6403 let foundry_str = r"
6404 [profile.default]
6405 src = 'src'
6406 out = 'out'
6407 libs = ['lib']
6408
6409 # See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options
6410 ";
6411 assert_eq!(
6412 parse_with_profile::<BasicConfig>(foundry_str).unwrap().unwrap(),
6413 (
6414 Config::DEFAULT_PROFILE,
6415 BasicConfig {
6416 profile: Config::DEFAULT_PROFILE,
6417 src: "src".into(),
6418 out: "out".into(),
6419 libs: vec!["lib".into()],
6420 remappings: vec![],
6421 network: None,
6422 }
6423 )
6424 );
6425 }
6426
6427 #[test]
6428 fn test_implicit_profile_loads() {
6429 figment::Jail::expect_with(|jail| {
6430 jail.create_file(
6431 "foundry.toml",
6432 r"
6433 [default]
6434 src = 'my-src'
6435 out = 'my-out'
6436 ",
6437 )?;
6438 let loaded = Config::load().unwrap().sanitized();
6439 assert_eq!(loaded.src.file_name().unwrap(), "my-src");
6440 assert_eq!(loaded.out.file_name().unwrap(), "my-out");
6441 assert_eq!(
6442 loaded.warnings,
6443 vec![Warning::UnknownSection {
6444 unknown_section: Profile::new("default"),
6445 source: Some("foundry.toml".into())
6446 }]
6447 );
6448
6449 Ok(())
6450 });
6451 }
6452
6453 #[test]
6454 fn hardfork_overrides_spec_id() {
6455 let config = Config {
6456 hardfork: Some(FoundryHardfork::Tempo(TempoHardfork::T3)),
6457 ..Config::default()
6458 };
6459
6460 assert_eq!(config.evm_spec_id::<TempoHardfork>(), TempoHardfork::T3);
6461 }
6462
6463 #[test]
6464 fn solc_settings_include_experimental_setting() {
6465 let config = Config { experimental: true, ..Config::default() };
6466 let settings = config.solc_settings().unwrap();
6467 assert_eq!(settings.settings.experimental, Some(true));
6468 assert!(settings.cli_settings.extra_args.is_empty());
6469
6470 let config = Config {
6471 experimental: false,
6472 extra_args: vec!["--experimental".to_string()],
6473 ..Config::default()
6474 };
6475 let settings = config.solc_settings().unwrap();
6476 assert_eq!(settings.settings.experimental, Some(false));
6477 assert_eq!(settings.cli_settings.extra_args, vec!["--experimental".to_string()]);
6478 }
6479
6480 #[test]
6481 fn solc_settings_include_via_ssa_cfg_setting() {
6482 let config = Config { via_ssa_cfg: true, ..Config::default() };
6483 let settings = config.solc_settings().unwrap();
6484 assert_eq!(settings.settings.via_ssa_cfg, Some(true));
6485 assert!(settings.cli_settings.extra_args.is_empty());
6486
6487 let config = Config {
6488 via_ssa_cfg: false,
6489 extra_args: vec!["--via-ssa-cfg".to_string()],
6490 ..Config::default()
6491 };
6492 let settings = config.solc_settings().unwrap();
6493 assert_eq!(settings.settings.via_ssa_cfg, Some(false));
6494 assert_eq!(settings.cli_settings.extra_args, vec!["--via-ssa-cfg".to_string()]);
6495 }
6496
6497 #[test]
6498 fn debug_build_info_leaves_out_the_ast_unless_build_info_is_on() {
6499 let requests_ast = |config: &Config| {
6500 config.solc_settings().unwrap().settings.output_selection.as_ref()["*"]
6501 .get("")
6502 .is_some_and(|outputs| outputs.contains(&"ast".to_string()))
6503 };
6504
6505 let mut config = Config::default();
6506 config.enable_debug_build_info().unwrap();
6507 assert!(config.build_info);
6508 assert!(!requests_ast(&config));
6509
6510 let mut config = Config { build_info: true, ..Config::default() };
6511 config.enable_debug_build_info().unwrap();
6512 assert!(requests_ast(&config));
6513 }
6514
6515 #[test]
6516 fn tempo_network_defaults_to_latest_tempo_hardfork() {
6517 figment::Jail::expect_with(|jail| {
6518 jail.create_file(
6519 "foundry.toml",
6520 r#"
6521 [profile.default]
6522 network = "tempo"
6523 "#,
6524 )?;
6525
6526 let config = Config::load().unwrap();
6527 assert!(config.networks.is_tempo());
6528 assert_eq!(config.evm_spec_id::<TempoHardfork>(), latest_active_tempo_hardfork());
6529
6530 Ok(())
6531 });
6532 }
6533
6534 #[test]
6535 fn tempo_hardfork_infers_tempo_network() {
6536 figment::Jail::expect_with(|jail| {
6537 jail.create_file(
6538 "foundry.toml",
6539 r#"
6540 [profile.default]
6541 hardfork = "tempo:T3"
6542 "#,
6543 )?;
6544
6545 let config = Config::load().unwrap();
6546 assert_eq!(config.hardfork, Some(FoundryHardfork::Tempo(TempoHardfork::T3)));
6547 assert!(config.networks.is_tempo());
6548
6549 Ok(())
6550 });
6551 }
6552
6553 #[cfg(feature = "base")]
6554 #[test]
6555 fn base_upgrade_infers_base_network() {
6556 figment::Jail::expect_with(|jail| {
6557 jail.create_file(
6558 "foundry.toml",
6559 r#"
6560 [profile.default]
6561 hardfork = "base:Beryl"
6562 "#,
6563 )?;
6564
6565 let config = Config::load().unwrap();
6566 assert_eq!(config.hardfork, Some(FoundryHardfork::Base(BaseUpgrade::Beryl)));
6567 assert!(config.networks.is_base());
6568
6569 Ok(())
6570 });
6571 }
6572
6573 #[test]
6574 #[cfg(feature = "monad")]
6575 fn namespaced_hardfork_infers_monad_network() {
6576 figment::Jail::expect_with(|jail| {
6577 jail.create_file(
6578 "foundry.toml",
6579 r#"
6580 [profile.default]
6581 hardfork = "monad:MonadNine"
6582 "#,
6583 )?;
6584
6585 let config = Config::load().unwrap();
6586 assert_eq!(
6587 config.hardfork,
6588 Some(FoundryHardfork::Monad(foundry_evm_hardforks::MonadHardfork::MonadNine))
6589 );
6590 assert_eq!(
6591 config.evm_spec_id::<foundry_evm_hardforks::MonadHardfork>(),
6592 foundry_evm_hardforks::MonadHardfork::MonadNine
6593 );
6594 assert_eq!(
6595 config.hardfork.as_ref().and_then(FoundryHardfork::namespace),
6596 Some("monad")
6597 );
6598 assert_eq!(
6599 config.hardfork.as_ref().map(FoundryHardfork::name).as_deref(),
6600 Some("MonadNine")
6601 );
6602 assert!(config.networks.is_monad());
6603
6604 Ok(())
6605 });
6606 }
6607
6608 #[test]
6609 #[cfg(feature = "monad")]
6610 fn network_selectors_reject_profile_merged_hybrid() {
6611 figment::Jail::expect_with(|jail| {
6612 jail.create_file(
6613 "foundry.toml",
6614 r#"
6615 [profile.default]
6616 monad = true
6617
6618 [profile.ci]
6619 celo = true
6620 "#,
6621 )?;
6622 jail.set_env("FOUNDRY_PROFILE", "ci");
6623
6624 let err = Config::load().unwrap_err().to_string();
6625 assert!(err.contains(
6626 "network selectors `celo = true` and `monad = true` conflict; select only one \
6627 network"
6628 ));
6629
6630 Ok(())
6631 });
6632 }
6633
6634 #[test]
6635 #[cfg(feature = "monad")]
6636 fn network_selectors_reject_canonical_environment_conflict() {
6637 figment::Jail::expect_with(|jail| {
6638 jail.create_file(
6639 "foundry.toml",
6640 r#"
6641 [profile.default]
6642 tempo = true
6643 "#,
6644 )?;
6645 jail.set_env("FOUNDRY_NETWORK", "monad");
6646
6647 let err = Config::load().unwrap_err().to_string();
6648 assert!(err.contains(
6649 "network selectors `network = \"monad\"` and `tempo = true` conflict; select only \
6650 one network"
6651 ));
6652
6653 Ok(())
6654 });
6655 }
6656
6657 #[test]
6658 #[cfg(feature = "monad")]
6659 fn matching_canonical_and_legacy_network_selectors_remain_valid() {
6660 figment::Jail::expect_with(|jail| {
6661 jail.create_file(
6662 "foundry.toml",
6663 r#"
6664 [profile.default]
6665 network = "monad"
6666 monad = true
6667 "#,
6668 )?;
6669
6670 let config = Config::load().unwrap();
6671 assert!(config.networks.is_monad());
6672 assert_eq!(
6673 config.networks.resolved_network(),
6674 Some(foundry_evm_networks::NetworkVariant::Monad)
6675 );
6676
6677 Ok(())
6678 });
6679 }
6680
6681 #[test]
6682 fn celo_network_accepts_ethereum_hardfork() {
6683 figment::Jail::expect_with(|jail| {
6684 jail.create_file(
6685 "foundry.toml",
6686 r#"
6687 [profile.default]
6688 celo = true
6689 hardfork = "prague"
6690 "#,
6691 )?;
6692
6693 let config = Config::load().unwrap();
6694 assert!(config.networks.is_celo());
6695 assert_eq!(
6696 config.hardfork,
6697 Some(FoundryHardfork::Ethereum(foundry_evm_hardforks::EthereumHardfork::Prague))
6698 );
6699
6700 Ok(())
6701 });
6702 }
6703
6704 #[test]
6705 fn hardfork_rejects_conflicting_network() {
6706 figment::Jail::expect_with(|jail| {
6707 jail.create_file(
6708 "foundry.toml",
6709 r#"
6710 [profile.default]
6711 tempo = true
6712 hardfork = "shanghai"
6713 "#,
6714 )?;
6715
6716 let err = Config::load().unwrap_err();
6717 assert!(
6718 err.to_string()
6719 .to_lowercase()
6720 .contains("hardfork `shanghai` conflicts with network config `tempo`")
6721 );
6722
6723 Ok(())
6724 });
6725 }
6726
6727 #[test]
6728 fn test_etherscan_api_key() {
6729 figment::Jail::expect_with(|jail| {
6730 jail.create_file(
6731 "foundry.toml",
6732 r"
6733 [default]
6734 ",
6735 )?;
6736 jail.set_env("ETHERSCAN_API_KEY", "");
6737 let loaded = Config::load().unwrap().sanitized();
6738 assert!(loaded.etherscan_api_key.is_none());
6739
6740 jail.set_env("ETHERSCAN_API_KEY", "DUMMY");
6741 let loaded = Config::load().unwrap().sanitized();
6742 assert_eq!(loaded.etherscan_api_key, Some("DUMMY".into()));
6743
6744 Ok(())
6745 });
6746 }
6747
6748 #[test]
6749 fn test_etherscan_api_key_figment() {
6750 figment::Jail::expect_with(|jail| {
6751 jail.create_file(
6752 "foundry.toml",
6753 r"
6754 [default]
6755 etherscan_api_key = 'DUMMY'
6756 ",
6757 )?;
6758 jail.set_env("ETHERSCAN_API_KEY", "ETHER");
6759
6760 let figment = Config::figment_with_root(jail.directory())
6761 .merge(("etherscan_api_key", "USER_KEY"));
6762
6763 let loaded = Config::from_provider(figment).unwrap();
6764 assert_eq!(loaded.etherscan_api_key, Some("USER_KEY".into()));
6765
6766 Ok(())
6767 });
6768 }
6769
6770 #[test]
6771 fn test_normalize_defaults() {
6772 figment::Jail::expect_with(|jail| {
6773 jail.create_file(
6774 "foundry.toml",
6775 r"
6776 [default]
6777 solc = '0.8.13'
6778 ",
6779 )?;
6780
6781 let loaded = Config::load().unwrap().sanitized();
6782 assert_eq!(loaded.evm_version, EvmVersion::London);
6783
6784 let figment = Config::figment_with_root(jail.directory()).merge(
6785 Serialized::default("evm_version", EvmVersion::Amsterdam)
6786 .profile(Config::selected_profile()),
6787 );
6788 let loaded = Config::from_provider(figment).unwrap().sanitized();
6789 assert_eq!(loaded.evm_version, EvmVersion::Amsterdam);
6790 Ok(())
6791 });
6792 }
6793
6794 #[expect(clippy::disallowed_macros)]
6796 #[test]
6797 #[ignore]
6798 fn print_config() {
6799 let config = Config {
6800 optimizer_details: Some(OptimizerDetails {
6801 peephole: None,
6802 inliner: None,
6803 jumpdest_remover: None,
6804 order_literals: None,
6805 deduplicate: None,
6806 cse: None,
6807 constant_optimizer: Some(true),
6808 yul: Some(true),
6809 yul_details: Some(YulDetails {
6810 stack_allocation: None,
6811 optimizer_steps: Some("dhfoDgvulfnTUtnIf".to_string()),
6812 }),
6813 simple_counter_for_loop_unchecked_increment: None,
6814 }),
6815 ..Default::default()
6816 };
6817 println!("{}", config.to_string_pretty().unwrap());
6818 }
6819
6820 #[test]
6821 fn can_use_impl_figment_macro() {
6822 #[derive(Default, Serialize)]
6823 struct MyArgs {
6824 #[serde(skip_serializing_if = "Option::is_none")]
6825 root: Option<PathBuf>,
6826 }
6827 impl_figment_convert!(MyArgs);
6828
6829 impl Provider for MyArgs {
6830 fn metadata(&self) -> Metadata {
6831 Metadata::default()
6832 }
6833
6834 fn data(&self) -> Result<Map<Profile, Dict>, Error> {
6835 let value = Value::serialize(self)?;
6836 let error = InvalidType(value.to_actual(), "map".into());
6837 let dict = value.into_dict().ok_or(error)?;
6838 Ok(Map::from([(Config::selected_profile(), dict)]))
6839 }
6840 }
6841
6842 let _figment: Figment = From::from(&MyArgs::default());
6843
6844 #[derive(Default)]
6845 struct Outer {
6846 start: MyArgs,
6847 other: MyArgs,
6848 another: MyArgs,
6849 }
6850 impl_figment_convert!(Outer, start, other, another);
6851
6852 let _figment: Figment = From::from(&Outer::default());
6853 }
6854
6855 #[test]
6856 fn list_cached_blocks() -> eyre::Result<()> {
6857 fn fake_block_cache(chain_path: &Path, block_number: &str, size_bytes: usize) {
6858 let block_path = chain_path.join(block_number);
6859 fs::create_dir(block_path.as_path()).unwrap();
6860 let file_path = block_path.join("storage.json");
6861 let mut file = File::create(file_path).unwrap();
6862 writeln!(file, "{}", vec![' '; size_bytes - 1].iter().collect::<String>()).unwrap();
6863 }
6864
6865 fn fake_endpoint_block_cache(
6866 chain_path: &Path,
6867 block_number: &str,
6868 endpoint: &str,
6869 size_bytes: usize,
6870 ) {
6871 let block_path = chain_path.join(block_number);
6872 let file_path = block_path.join(format!("storage-{endpoint}.json"));
6873 let mut file = File::create(file_path).unwrap();
6874 writeln!(file, "{}", vec![' '; size_bytes - 1].iter().collect::<String>()).unwrap();
6875 }
6876
6877 fn fake_block_cache_block_path_as_file(
6878 chain_path: &Path,
6879 block_number: &str,
6880 size_bytes: usize,
6881 ) {
6882 let block_path = chain_path.join(block_number);
6883 let mut file = File::create(block_path).unwrap();
6884 writeln!(file, "{}", vec![' '; size_bytes - 1].iter().collect::<String>()).unwrap();
6885 }
6886
6887 let chain_dir = tempdir()?;
6888
6889 fake_block_cache(chain_dir.path(), "1", 100);
6890 fake_endpoint_block_cache(
6891 chain_dir.path(),
6892 "1",
6893 "0000000000000000000000000000000000000000000000000000000000000000",
6894 50,
6895 );
6896 fake_endpoint_block_cache(chain_dir.path(), "1", "backup", 75);
6897 fake_block_cache(chain_dir.path(), "2", 500);
6898 fake_block_cache_block_path_as_file(chain_dir.path(), "3", 900);
6899 let mut pol_file = File::create(chain_dir.path().join("pol.txt")).unwrap();
6901 writeln!(pol_file, "{}", [' '; 10].iter().collect::<String>()).unwrap();
6902
6903 let result = Config::get_cached_blocks(chain_dir.path())?;
6904
6905 assert_eq!(result.len(), 3);
6906 let block1 = &result.iter().find(|x| x.0 == "1").unwrap();
6907 let block2 = &result.iter().find(|x| x.0 == "2").unwrap();
6908 let block3 = &result.iter().find(|x| x.0 == "3").unwrap();
6909
6910 assert_eq!(block1.0, "1");
6911 assert_eq!(block1.1, 150);
6912 assert_eq!(block2.0, "2");
6913 assert_eq!(block2.1, 500);
6914 assert_eq!(block3.0, "3");
6915 assert_eq!(block3.1, 900);
6916
6917 chain_dir.close()?;
6918 Ok(())
6919 }
6920
6921 #[test]
6922 fn list_cached_blocks_ignores_removed_entries() -> eyre::Result<()> {
6923 let chain_dir = tempdir()?;
6924 let block_path = chain_dir.path().join("1");
6925 fs::create_dir(&block_path)?;
6926 File::create(block_path.join("storage.json"))?;
6927
6928 let block = fs::read_dir(chain_dir.path())?.next().unwrap()?;
6929 let cache_file = fs::read_dir(&block_path)?.next().unwrap()?;
6930 fs::remove_dir_all(block_path)?;
6931
6932 assert!(Config::get_cached_block(block)?.is_none());
6933 assert!(Config::get_cache_file_size(cache_file)?.is_none());
6934 Ok(())
6935 }
6936
6937 #[test]
6938 fn ignore_not_found_propagates_other_errors() {
6939 assert!(
6940 Config::ignore_not_found::<()>(Err(io::Error::from(io::ErrorKind::NotFound)))
6941 .unwrap()
6942 .is_none()
6943 );
6944
6945 let err =
6946 Config::ignore_not_found::<()>(Err(io::Error::from(io::ErrorKind::PermissionDenied)))
6947 .unwrap_err();
6948 assert_eq!(
6949 err.downcast_ref::<io::Error>().unwrap().kind(),
6950 io::ErrorKind::PermissionDenied
6951 );
6952 }
6953
6954 #[test]
6955 fn cache_listing_propagates_not_a_directory() -> eyre::Result<()> {
6956 let cache_file = tempfile::NamedTempFile::new()?;
6957
6958 let err = Config::get_cached_blocks(cache_file.path()).unwrap_err();
6959 assert_eq!(err.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::NotADirectory);
6960
6961 let err = Config::get_cached_block_explorer_data(cache_file.path()).unwrap_err();
6962 assert_eq!(err.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::NotADirectory);
6963 Ok(())
6964 }
6965
6966 #[test]
6967 fn list_cached_blocks_uses_replaced_entry_type() -> eyre::Result<()> {
6968 let chain_dir = tempdir()?;
6969 let block_path = chain_dir.path().join("1");
6970 File::create(&block_path)?;
6971 let block = fs::read_dir(chain_dir.path())?.next().unwrap()?;
6972
6973 fs::remove_file(&block_path)?;
6974 fs::create_dir(&block_path)?;
6975 fs::write(block_path.join("storage.json"), [0; 10])?;
6976
6977 assert_eq!(Config::get_cached_block(block)?, Some(("1".to_string(), 10)));
6978 Ok(())
6979 }
6980
6981 #[cfg(unix)]
6982 #[test]
6983 fn list_cached_blocks_ignores_symlinks() -> eyre::Result<()> {
6984 let chain_dir = tempdir()?;
6985 let target_dir = tempdir()?;
6986 fs::write(target_dir.path().join("storage.json"), [0; 10])?;
6987 std::os::unix::fs::symlink(target_dir.path(), chain_dir.path().join("1"))?;
6988
6989 let block_path = chain_dir.path().join("2");
6990 fs::create_dir(&block_path)?;
6991 let target_file = tempfile::NamedTempFile::new()?;
6992 fs::write(target_file.path(), [0; 10])?;
6993 std::os::unix::fs::symlink(target_file.path(), block_path.join("storage.json"))?;
6994
6995 assert!(Config::get_cached_blocks(chain_dir.path())?.is_empty());
6996 Ok(())
6997 }
6998
6999 #[test]
7000 fn list_etherscan_cache_ignores_removed_entries() -> eyre::Result<()> {
7001 let cache_dir = tempdir()?;
7002 let sources_path = cache_dir.path().join("sources");
7003 fs::create_dir(&sources_path)?;
7004 File::create(sources_path.join("metadata.json"))?;
7005
7006 let sources = fs::read_dir(cache_dir.path())?.next().unwrap()?;
7007 let metadata = fs::read_dir(&sources_path)?.next().unwrap()?;
7008 fs::remove_dir_all(sources_path)?;
7009
7010 assert!(Config::get_cached_entry_size(sources)?.is_none());
7011 assert!(Config::get_cached_entry_size(metadata)?.is_none());
7012 Ok(())
7013 }
7014
7015 #[test]
7016 fn list_etherscan_cache() -> eyre::Result<()> {
7017 fn fake_etherscan_cache(chain_path: &Path, address: &str, size_bytes: usize) {
7018 let metadata_path = chain_path.join("sources");
7019 let abi_path = chain_path.join("abi");
7020 let _ = fs::create_dir(metadata_path.as_path());
7021 let _ = fs::create_dir(abi_path.as_path());
7022
7023 let metadata_file_path = metadata_path.join(address);
7024 let mut metadata_file = File::create(metadata_file_path).unwrap();
7025 writeln!(metadata_file, "{}", vec![' '; size_bytes / 2 - 1].iter().collect::<String>())
7026 .unwrap();
7027
7028 let abi_file_path = abi_path.join(address);
7029 let mut abi_file = File::create(abi_file_path).unwrap();
7030 writeln!(abi_file, "{}", vec![' '; size_bytes / 2 - 1].iter().collect::<String>())
7031 .unwrap();
7032 }
7033
7034 let chain_dir = tempdir()?;
7035
7036 fake_etherscan_cache(chain_dir.path(), "1", 100);
7037 fake_etherscan_cache(chain_dir.path(), "2", 500);
7038
7039 let result = Config::get_cached_block_explorer_data(chain_dir.path())?;
7040
7041 assert_eq!(result, 600);
7042
7043 chain_dir.close()?;
7044 Ok(())
7045 }
7046
7047 #[test]
7048 fn test_parse_error_codes() {
7049 figment::Jail::expect_with(|jail| {
7050 jail.create_file(
7051 "foundry.toml",
7052 r#"
7053 [default]
7054 ignored_error_codes = ["license", "unreachable", 1337]
7055 "#,
7056 )?;
7057
7058 let config = Config::load().unwrap();
7059 assert_eq!(
7060 config.ignored_error_codes,
7061 vec![
7062 SolidityErrorCode::SpdxLicenseNotProvided,
7063 SolidityErrorCode::Unreachable,
7064 SolidityErrorCode::Other(1337)
7065 ]
7066 );
7067
7068 Ok(())
7069 });
7070 }
7071
7072 #[test]
7073 fn test_parse_file_paths() {
7074 figment::Jail::expect_with(|jail| {
7075 jail.create_file(
7076 "foundry.toml",
7077 r#"
7078 [default]
7079 ignored_warnings_from = ["something"]
7080 "#,
7081 )?;
7082
7083 let config = Config::load().unwrap();
7084 assert_eq!(config.ignored_file_paths, vec![Path::new("something").to_path_buf()]);
7085
7086 Ok(())
7087 });
7088 }
7089
7090 #[test]
7091 fn test_parse_optimizer_settings() {
7092 figment::Jail::expect_with(|jail| {
7093 jail.create_file(
7094 "foundry.toml",
7095 r"
7096 [default]
7097 [profile.default.optimizer_details]
7098 ",
7099 )?;
7100
7101 let config = Config::load().unwrap();
7102 assert_eq!(config.optimizer_details, Some(OptimizerDetails::default()));
7103
7104 Ok(())
7105 });
7106 }
7107
7108 #[test]
7109 fn test_parse_labels() {
7110 figment::Jail::expect_with(|jail| {
7111 jail.create_file(
7112 "foundry.toml",
7113 r#"
7114 [labels]
7115 0x1F98431c8aD98523631AE4a59f267346ea31F984 = "Uniswap V3: Factory"
7116 0xC36442b4a4522E871399CD717aBDD847Ab11FE88 = "Uniswap V3: Positions NFT"
7117 "#,
7118 )?;
7119
7120 let config = Config::load().unwrap();
7121 assert_eq!(
7122 config.labels,
7123 AddressHashMap::from_iter(vec![
7124 (
7125 address!("0x1F98431c8aD98523631AE4a59f267346ea31F984"),
7126 "Uniswap V3: Factory".to_string()
7127 ),
7128 (
7129 address!("0xC36442b4a4522E871399CD717aBDD847Ab11FE88"),
7130 "Uniswap V3: Positions NFT".to_string()
7131 ),
7132 ])
7133 );
7134 assert_eq!(config.tracing.labels, config.labels);
7135 assert_eq!(
7136 config.warnings,
7137 vec![Warning::DeprecatedKey {
7138 old: "[labels]".to_string(),
7139 new: "[tracing.labels]".to_string(),
7140 }]
7141 );
7142
7143 Ok(())
7144 });
7145 }
7146
7147 #[test]
7148 fn test_parse_deprecated_profile_labels() {
7149 figment::Jail::expect_with(|jail| {
7150 jail.create_file(
7151 "foundry.toml",
7152 r#"
7153 [profile.default.labels]
7154 0x0000000000000000000000000000000000000001 = "Alice"
7155 "#,
7156 )?;
7157
7158 let config = Config::load().unwrap();
7159 let labels =
7160 AddressHashMap::from_iter(vec![(Address::with_last_byte(1), "Alice".to_string())]);
7161 assert_eq!(config.labels, labels);
7162 assert_eq!(config.tracing.labels, labels);
7163 assert_eq!(
7164 config.warnings,
7165 vec![Warning::DeprecatedKey {
7166 old: "labels".to_string(),
7167 new: "tracing.labels".to_string(),
7168 }]
7169 );
7170
7171 Ok(())
7172 });
7173 }
7174
7175 #[test]
7176 fn test_deprecated_env_labels_use_tracing_section() {
7177 figment::Jail::expect_with(|jail| {
7178 jail.set_env(
7179 "FOUNDRY_LABELS",
7180 r#"{ "0x0000000000000000000000000000000000000001" = "Alice" }"#,
7181 );
7182 jail.set_env(
7183 "FOUNDRY_TRACING_LABELS",
7184 r#"{ "0x0000000000000000000000000000000000000001" = "Bob" }"#,
7185 );
7186
7187 let config = Config::load().unwrap();
7188 assert_eq!(
7189 config.labels,
7190 AddressHashMap::from_iter([(Address::with_last_byte(1), "Alice".to_string(),)])
7191 );
7192 assert_eq!(
7193 config.tracing.labels,
7194 AddressHashMap::from_iter([(Address::with_last_byte(1), "Bob".to_string(),)])
7195 );
7196
7197 Ok(())
7198 });
7199 }
7200
7201 #[test]
7202 fn test_deprecated_labels_warn_for_inactive_profiles() {
7203 figment::Jail::expect_with(|jail| {
7204 jail.create_file(
7205 "foundry.toml",
7206 r#"
7207 [profile.ci.labels]
7208 0x0000000000000000000000000000000000000001 = "Alice"
7209 "#,
7210 )?;
7211
7212 let config = Config::load().unwrap();
7213 assert_eq!(
7214 config.warnings,
7215 vec![Warning::DeprecatedKey {
7216 old: "labels".to_string(),
7217 new: "tracing.labels".to_string(),
7218 }]
7219 );
7220
7221 Ok(())
7222 });
7223 }
7224
7225 #[test]
7226 fn test_tracing_serialization_keeps_global_verbosity() {
7227 let address = Address::with_last_byte(1);
7228 let labels = AddressHashMap::from_iter([(address, "Alice".to_string())]);
7229 let config = Config {
7230 tracing: TracingConfig { verbosity: 4, labels: labels.clone(), ..Default::default() },
7231 ..Default::default()
7232 };
7233
7234 let serialized = toml::Value::try_from(&config).unwrap();
7235 let table = serialized.as_table().unwrap();
7236 assert_eq!(table["verbosity"].as_integer(), Some(0));
7237 assert!(!table.contains_key("labels"));
7238 assert_eq!(table["tracing"]["verbosity"].as_integer(), Some(4));
7239
7240 let provided = Figment::from(&config).extract::<Config>().unwrap();
7241 assert_eq!(provided.verbosity, 0);
7242 assert!(provided.labels.is_empty());
7243 assert_eq!(provided.tracing.labels, labels);
7244
7245 let merged = config.merge_inline_provider(("ffi", true)).unwrap();
7246 assert_eq!(merged.tracing.verbosity, 4);
7247 assert_eq!(merged.tracing.labels, config.tracing.labels);
7248 }
7249
7250 #[test]
7251 fn test_legacy_programmatic_labels_survive_serialization() {
7252 let address = Address::with_last_byte(1);
7253 let labels = AddressHashMap::from_iter([(address, "Alice".to_string())]);
7254 let config = Config { labels: labels.clone(), ..Default::default() };
7255
7256 let serialized = toml::Value::try_from(&config).unwrap();
7257 assert_eq!(
7258 serialized["labels"].as_table().unwrap().values().next().and_then(|v| v.as_str()),
7259 Some("Alice")
7260 );
7261
7262 let provided = Config::from_provider(&config).unwrap();
7263 assert_eq!(provided.labels, labels);
7264 assert_eq!(provided.tracing.labels, labels);
7265
7266 let merged = config.merge_inline_provider(("ffi", true)).unwrap();
7267 assert_eq!(merged.labels, labels);
7268 assert_eq!(merged.tracing.labels, labels);
7269 }
7270
7271 #[test]
7272 fn test_parse_tracing_section() {
7273 figment::Jail::expect_with(|jail| {
7274 jail.create_file(
7275 "foundry.toml",
7276 r#"
7277 [profile.default]
7278 verbosity = 2
7279
7280 [tracing]
7281 verbosity = 4
7282 disable_labels = true
7283 compact_labels = true
7284 trace_depth = 3
7285 decode_internal = true
7286 external_identification_timeout = 9
7287
7288 [tracing.labels]
7289 0x0000000000000000000000000000000000000002 = "Bob"
7290 "#,
7291 )?;
7292
7293 let config = Config::load().unwrap();
7294 assert_eq!(config.verbosity, 2);
7295 assert_eq!(config.tracing.verbosity, 4);
7296 assert!(config.tracing.disable_labels);
7297 assert_eq!(config.tracing.trace_depth, Some(3));
7298 assert!(config.tracing.decode_internal);
7299 assert!(config.tracing.compact_labels);
7300 assert_eq!(config.tracing.external_identification_timeout, 9);
7301 let labels =
7302 AddressHashMap::from_iter(vec![(Address::with_last_byte(2), "Bob".to_string())]);
7303 assert!(config.labels.is_empty());
7304 assert_eq!(config.tracing.labels, labels);
7305 assert!(config.warnings.is_empty());
7306
7307 let serialized = config.to_string_pretty().unwrap();
7308 assert!(!serialized.contains("[labels]"));
7309 assert!(serialized.contains("[tracing.labels]"));
7310
7311 jail.create_file("foundry.toml", &serialized)?;
7312 let reloaded = Config::load().unwrap();
7313 assert!(reloaded.labels.is_empty());
7314 assert_eq!(reloaded.tracing.labels, labels);
7315 assert!(reloaded.warnings.is_empty());
7316
7317 Ok(())
7318 });
7319 }
7320
7321 #[test]
7322 fn test_external_identification_timeout_env() {
7323 figment::Jail::expect_with(|jail| {
7324 jail.set_env("FOUNDRY_TRACING_EXTERNAL_IDENTIFICATION_TIMEOUT", "0");
7325
7326 let config = Config::load().unwrap();
7327
7328 assert_eq!(config.tracing.external_identification_timeout, 0);
7329 Ok(())
7330 });
7331 }
7332
7333 #[test]
7334 fn test_global_and_tracing_verbosity_are_independent() {
7335 figment::Jail::expect_with(|jail| {
7336 jail.create_file(
7337 "foundry.toml",
7338 r#"
7339 [profile.default]
7340 verbosity = 4
7341
7342 [tracing]
7343 disable_labels = true
7344 "#,
7345 )?;
7346
7347 let config = Config::load().unwrap();
7348 assert_eq!(config.verbosity, 4);
7349 assert_eq!(config.tracing.verbosity, 0);
7350 assert!(config.tracing.disable_labels);
7351 assert_eq!(config.tracing.external_identification_timeout, 5);
7352
7353 Ok(())
7354 });
7355 }
7356
7357 #[test]
7358 fn test_label_aliases_preserve_provider_precedence() {
7359 let address = Address::with_last_byte(1);
7360 let labels = |label: &str| AddressHashMap::from_iter([(address, label.to_string())]);
7361 let provider = |global: &str, local: &str| {
7362 let figment = Config::merge_toml_provider(
7363 Figment::from(Config::default()),
7364 Toml::string(global).nested(),
7365 Config::DEFAULT_PROFILE,
7366 );
7367 Config::merge_toml_provider(
7368 figment,
7369 Toml::string(local).nested(),
7370 Config::DEFAULT_PROFILE,
7371 )
7372 };
7373
7374 let config = Config::from_provider(provider(
7375 r#"[tracing.labels]
7376 0x0000000000000000000000000000000000000001 = "global""#,
7377 r#"[labels]
7378 0x0000000000000000000000000000000000000001 = "local""#,
7379 ))
7380 .unwrap();
7381 assert_eq!(config.tracing.labels, labels("local"));
7382
7383 let config = Config::from_provider(provider(
7384 r#"[labels]
7385 0x0000000000000000000000000000000000000001 = "global""#,
7386 r#"[tracing.labels]
7387 0x0000000000000000000000000000000000000001 = "local""#,
7388 ))
7389 .unwrap();
7390 assert_eq!(config.tracing.labels, labels("local"));
7391 }
7392
7393 #[test]
7394 fn test_malformed_tracing_labels_are_not_replaced() {
7395 let provider = Toml::string(
7396 r#"
7397 [profile.default.labels]
7398 0x0000000000000000000000000000000000000001 = "legacy"
7399
7400 [profile.default.tracing]
7401 labels = "invalid"
7402 "#,
7403 )
7404 .nested();
7405
7406 assert!(Config::from_provider(provider).is_err());
7407 }
7408
7409 #[test]
7410 fn test_parse_vyper() {
7411 figment::Jail::expect_with(|jail| {
7412 jail.create_file(
7413 "foundry.toml",
7414 r#"
7415 [vyper]
7416 optimize = "O1"
7417 path = "/path/to/vyper"
7418 experimental_codegen = true
7419 venom_experimental = false
7420 debug = true
7421 enable_decimals = true
7422
7423 [vyper.venom]
7424 disable_inlining = true
7425 disable_cse = true
7426 disable_sccp = false
7427 disable_load_elimination = true
7428 disable_dead_store_elimination = false
7429 disable_algebraic_optimization = true
7430 disable_branch_optimization = false
7431 disable_assert_elimination = true
7432 disable_mem2var = false
7433 disable_simplify_cfg = true
7434 disable_remove_unused_variables = false
7435 inline_threshold = 15
7436 "#,
7437 )?;
7438
7439 let config = Config::load().unwrap();
7440 assert_eq!(
7441 config.vyper,
7442 VyperConfig {
7443 optimize: Some(VyperOptimizationMode::O1),
7444 opt_level: None,
7445 path: Some("/path/to/vyper".into()),
7446 experimental_codegen: Some(true),
7447 venom_experimental: Some(false),
7448 debug: Some(true),
7449 enable_decimals: Some(true),
7450 venom: Some(VyperVenomSettings {
7451 disable_inlining: Some(true),
7452 disable_cse: Some(true),
7453 disable_sccp: Some(false),
7454 disable_load_elimination: Some(true),
7455 disable_dead_store_elimination: Some(false),
7456 disable_algebraic_optimization: Some(true),
7457 disable_branch_optimization: Some(false),
7458 disable_assert_elimination: Some(true),
7459 disable_mem2var: Some(false),
7460 disable_simplify_cfg: Some(true),
7461 disable_remove_unused_variables: Some(false),
7462 inline_threshold: Some(15),
7463 }),
7464 }
7465 );
7466
7467 Ok(())
7468 });
7469 }
7470
7471 #[test]
7472 fn test_vyper_settings_include_extended_config() {
7473 let config = Config {
7474 vyper: VyperConfig {
7475 opt_level: Some(VyperOptimizationLevel::O3),
7476 experimental_codegen: Some(true),
7477 venom_experimental: Some(false),
7478 debug: Some(true),
7479 enable_decimals: Some(true),
7480 venom: Some(VyperVenomSettings {
7481 disable_cse: Some(true),
7482 inline_threshold: Some(15),
7483 ..Default::default()
7484 }),
7485 ..Default::default()
7486 },
7487 ..Config::default().normalized_optimizer_settings()
7488 };
7489
7490 let settings = config.vyper_settings().unwrap();
7491 assert_eq!(settings.optimize, None);
7492 assert_eq!(settings.opt_level, Some(VyperOptimizationLevel::O3));
7493 assert_eq!(settings.experimental_codegen, Some(true));
7494 assert_eq!(settings.venom_experimental, Some(false));
7495 assert_eq!(settings.debug, Some(true));
7496 assert_eq!(settings.enable_decimals, Some(true));
7497 assert_eq!(
7498 settings.venom,
7499 Some(VyperVenomSettings {
7500 disable_cse: Some(true),
7501 inline_threshold: Some(15),
7502 ..Default::default()
7503 })
7504 );
7505 }
7506
7507 #[test]
7508 fn vyper_opt_level_overrides_optimize() {
7509 let config = Config {
7510 vyper: VyperConfig {
7511 optimize: Some(VyperOptimizationMode::Gas),
7512 opt_level: Some(VyperOptimizationLevel::O3),
7513 ..Default::default()
7514 },
7515 ..Config::default().normalized_optimizer_settings()
7516 };
7517
7518 let settings = config.vyper_settings().unwrap();
7519 assert_eq!(settings.optimize, None);
7520 assert_eq!(settings.opt_level, Some(VyperOptimizationLevel::O3));
7521 }
7522
7523 #[test]
7524 fn test_parse_soldeer() {
7525 figment::Jail::expect_with(|jail| {
7526 jail.create_file(
7527 "foundry.toml",
7528 r#"
7529 [soldeer]
7530 remappings_generate = true
7531 remappings_regenerate = false
7532 remappings_version = true
7533 remappings_prefix = "@"
7534 remappings_location = "txt"
7535 recursive_deps = true
7536 "#,
7537 )?;
7538
7539 let config = Config::load().unwrap();
7540
7541 assert_eq!(
7542 config.soldeer,
7543 Some(SoldeerConfig {
7544 remappings_generate: true,
7545 remappings_regenerate: false,
7546 remappings_version: true,
7547 remappings_prefix: "@".to_string(),
7548 remappings_location: RemappingsLocation::Txt,
7549 recursive_deps: true,
7550 })
7551 );
7552
7553 Ok(())
7554 });
7555 }
7556
7557 #[test]
7559 fn test_resolve_mesc_by_chain_id() {
7560 let s = r#"{
7561 "mesc_version": "0.2.1",
7562 "default_endpoint": null,
7563 "endpoints": {
7564 "sophon_50104": {
7565 "name": "sophon_50104",
7566 "url": "https://rpc.sophon.xyz",
7567 "chain_id": "50104",
7568 "endpoint_metadata": {}
7569 }
7570 },
7571 "network_defaults": {
7572 },
7573 "network_names": {},
7574 "profiles": {
7575 "foundry": {
7576 "name": "foundry",
7577 "default_endpoint": "local_ethereum",
7578 "network_defaults": {
7579 "50104": "sophon_50104"
7580 },
7581 "profile_metadata": {},
7582 "use_mesc": true
7583 }
7584 },
7585 "global_metadata": {}
7586}"#;
7587
7588 let config = serde_json::from_str(s).unwrap();
7589 let endpoint = mesc::query::get_endpoint_by_network(&config, "50104", Some("foundry"))
7590 .unwrap()
7591 .unwrap();
7592 assert_eq!(endpoint.url, "https://rpc.sophon.xyz");
7593
7594 let s = r#"{
7595 "mesc_version": "0.2.1",
7596 "default_endpoint": null,
7597 "endpoints": {
7598 "sophon_50104": {
7599 "name": "sophon_50104",
7600 "url": "https://rpc.sophon.xyz",
7601 "chain_id": "50104",
7602 "endpoint_metadata": {}
7603 }
7604 },
7605 "network_defaults": {
7606 "50104": "sophon_50104"
7607 },
7608 "network_names": {},
7609 "profiles": {},
7610 "global_metadata": {}
7611}"#;
7612
7613 let config = serde_json::from_str(s).unwrap();
7614 let endpoint = mesc::query::get_endpoint_by_network(&config, "50104", Some("foundry"))
7615 .unwrap()
7616 .unwrap();
7617 assert_eq!(endpoint.url, "https://rpc.sophon.xyz");
7618 }
7619
7620 #[test]
7621 fn test_get_etherscan_config_with_unknown_chain() {
7622 figment::Jail::expect_with(|jail| {
7623 jail.create_file(
7624 "foundry.toml",
7625 r#"
7626 [etherscan]
7627 mainnet = { chain = 3658348, key = "api-key"}
7628 "#,
7629 )?;
7630 let config = Config::load().unwrap();
7631 let unknown_chain = Chain::from_id(3658348);
7632 let result = config.get_etherscan_config_with_chain(Some(unknown_chain));
7633 assert!(result.is_err());
7634 let error_msg = result.unwrap_err().to_string();
7635 assert!(error_msg.contains("No known Etherscan API URL for chain `3658348`"));
7636 assert!(error_msg.contains("Specify a `url`"));
7637 assert!(error_msg.contains("Verify the chain `3658348` is correct"));
7638
7639 Ok(())
7640 });
7641 }
7642
7643 #[test]
7644 fn test_get_etherscan_config_with_existing_chain_and_url() {
7645 figment::Jail::expect_with(|jail| {
7646 jail.create_file(
7647 "foundry.toml",
7648 r#"
7649 [etherscan]
7650 mainnet = { chain = 1, key = "api-key" }
7651 "#,
7652 )?;
7653 let config = Config::load().unwrap();
7654 let unknown_chain = Chain::from_id(1);
7655 let result = config.get_etherscan_config_with_chain(Some(unknown_chain));
7656 assert!(result.is_ok());
7657 Ok(())
7658 });
7659 }
7660
7661 #[test]
7662 fn test_can_inherit_a_base_toml() {
7663 figment::Jail::expect_with(|jail| {
7664 jail.create_file(
7666 "base-config.toml",
7667 r#"
7668 [profile.default]
7669 optimizer_runs = 800
7670
7671 [invariant]
7672 runs = 1000
7673
7674 [rpc_endpoints]
7675 mainnet = "https://example.com"
7676 optimism = "https://example-2.com/"
7677 "#,
7678 )?;
7679
7680 jail.create_file(
7682 "foundry.toml",
7683 r#"
7684 [profile.default]
7685 extends = "base-config.toml"
7686
7687 [invariant]
7688 runs = 333
7689 depth = 15
7690
7691 [rpc_endpoints]
7692 mainnet = "https://test.xyz/rpc"
7693 "#,
7694 )?;
7695
7696 let config = Config::load().unwrap();
7697 assert_eq!(config.extends, Some(Extends::Path("base-config.toml".to_string())));
7698
7699 assert_eq!(config.optimizer_runs, Some(800));
7701
7702 assert_eq!(config.invariant.runs, 333);
7704 assert_eq!(config.invariant.depth, 15);
7705
7706 let endpoints = config.rpc_endpoints.resolved();
7709 assert!(
7710 endpoints.get("mainnet").unwrap().url().unwrap().contains("https://test.xyz/rpc")
7711 );
7712 assert!(endpoints.get("optimism").unwrap().url().unwrap().contains("example-2.com"));
7713
7714 Ok(())
7715 });
7716 }
7717
7718 #[test]
7719 fn inherited_symbolic_sections_preserve_source_precedence() {
7720 figment::Jail::expect_with(|jail| {
7721 jail.create_file(
7722 "base.toml",
7723 r#"
7724 [profile.default.symbolic]
7725 max_paths = 10
7726 depth = 100
7727 "#,
7728 )?;
7729 jail.create_file(
7730 "foundry.toml",
7731 r#"
7732 [profile.default]
7733 extends = "base.toml"
7734
7735 [symbolic]
7736 max_paths = 20
7737 "#,
7738 )?;
7739
7740 let config = Config::load().unwrap();
7741 assert_eq!(config.symbolic.max_paths, 20);
7742 assert_eq!(config.symbolic.depth, Some(100));
7743
7744 jail.create_file(
7745 "base.toml",
7746 r#"
7747 [symbolic]
7748 max_paths = 30
7749 depth = 200
7750 "#,
7751 )?;
7752 jail.create_file(
7753 "foundry.toml",
7754 r#"
7755 [profile.default]
7756 extends = "base.toml"
7757
7758 [profile.default.symbolic]
7759 max_paths = 40
7760 "#,
7761 )?;
7762
7763 let config = Config::load().unwrap();
7764 assert_eq!(config.symbolic.max_paths, 40);
7765 assert_eq!(config.symbolic.depth, Some(200));
7766
7767 Ok(())
7768 });
7769 }
7770
7771 #[test]
7772 fn inherited_symbolic_sections_detect_effective_collisions() {
7773 figment::Jail::expect_with(|jail| {
7774 jail.create_file(
7775 "base.toml",
7776 r#"
7777 [profile.default.symbolic]
7778 max_paths = 10
7779 "#,
7780 )?;
7781 jail.create_file(
7782 "foundry.toml",
7783 r#"
7784 [profile.default]
7785 extends = { path = "base.toml", strategy = "no-collision" }
7786
7787 [symbolic]
7788 max_paths = 20
7789 "#,
7790 )?;
7791
7792 let err = Config::load().unwrap_err().to_string();
7793 assert!(err.contains("Key collision detected"), "unexpected error: {err}");
7794 assert!(err.contains("symbolic"), "unexpected error: {err}");
7795
7796 Ok(())
7797 });
7798 }
7799
7800 #[test]
7801 fn inherited_label_aliases_preserve_source_precedence() {
7802 figment::Jail::expect_with(|jail| {
7803 let address = Address::with_last_byte(1);
7804
7805 jail.create_file(
7806 "base.toml",
7807 r#"
7808 [profile.default.tracing.labels]
7809 0x0000000000000000000000000000000000000001 = "base"
7810 "#,
7811 )?;
7812 jail.create_file(
7813 "foundry.toml",
7814 r#"
7815 [profile.default]
7816 extends = "base.toml"
7817
7818 [profile.default.labels]
7819 0x0000000000000000000000000000000000000001 = "local"
7820 "#,
7821 )?;
7822
7823 let config = Config::load().unwrap();
7824 assert_eq!(config.tracing.labels.get(&address).map(String::as_str), Some("local"));
7825
7826 jail.create_file(
7827 "base.toml",
7828 r#"
7829 [profile.default.labels]
7830 0x0000000000000000000000000000000000000001 = "base"
7831 "#,
7832 )?;
7833 jail.create_file(
7834 "foundry.toml",
7835 r#"
7836 [profile.default]
7837 extends = "base.toml"
7838
7839 [profile.default.tracing.labels]
7840 0x0000000000000000000000000000000000000001 = "local"
7841 "#,
7842 )?;
7843
7844 let config = Config::load().unwrap();
7845 assert_eq!(config.tracing.labels.get(&address).map(String::as_str), Some("local"));
7846
7847 jail.create_file(
7848 "base.toml",
7849 r#"
7850 [profile.default.tracing.labels]
7851 0x0000000000000000000000000000000000000001 = "base"
7852 "#,
7853 )?;
7854 jail.create_file(
7855 "foundry.toml",
7856 r#"
7857 [profile.default]
7858 extends = "base.toml"
7859
7860 [labels]
7861 0x0000000000000000000000000000000000000001 = "local"
7862 "#,
7863 )?;
7864
7865 let config = Config::load().unwrap();
7866 assert_eq!(config.tracing.labels.get(&address).map(String::as_str), Some("local"));
7867 assert_eq!(
7868 config.warnings,
7869 vec![Warning::DeprecatedKey {
7870 old: "[labels]".to_string(),
7871 new: "[tracing.labels]".to_string(),
7872 }]
7873 );
7874
7875 jail.create_file(
7876 "base.toml",
7877 r#"
7878 [labels]
7879 0x0000000000000000000000000000000000000001 = "base"
7880 "#,
7881 )?;
7882 jail.create_file(
7883 "foundry.toml",
7884 r#"
7885 [profile.default]
7886 extends = "base.toml"
7887
7888 [profile.default.tracing.labels]
7889 0x0000000000000000000000000000000000000001 = "local"
7890 "#,
7891 )?;
7892
7893 let config = Config::load().unwrap();
7894 assert_eq!(config.tracing.labels.get(&address).map(String::as_str), Some("local"));
7895
7896 Ok(())
7897 });
7898 }
7899
7900 #[test]
7901 fn inherited_label_aliases_detect_effective_collisions() {
7902 figment::Jail::expect_with(|jail| {
7903 jail.create_file(
7904 "base.toml",
7905 r#"
7906 [profile.default.tracing.labels]
7907 0x0000000000000000000000000000000000000001 = "base"
7908 "#,
7909 )?;
7910 jail.create_file(
7911 "foundry.toml",
7912 r#"
7913 [profile.default]
7914 extends = { path = "base.toml", strategy = "no-collision" }
7915
7916 [labels]
7917 0x0000000000000000000000000000000000000001 = "local"
7918 "#,
7919 )?;
7920
7921 let err = Config::load().unwrap_err().to_string();
7922 assert_eq!(
7923 err,
7924 "failed to extract foundry config:\n\
7925 foundry config error: Key collision detected in profile 'default' when extending \
7926 'base.toml'. Conflicting keys: [\"tracing\"]. Use 'extends.strategy' or \
7927 'extends_strategy' to specify how to handle conflicts.\n"
7928 );
7929
7930 Ok(())
7931 });
7932 }
7933
7934 #[test]
7935 fn inherited_fuzz_section_remains_invariant_fallback() {
7936 figment::Jail::expect_with(|jail| {
7937 jail.create_file(
7938 "base.toml",
7939 r#"
7940 [fuzz]
7941 include_storage = false
7942 dictionary_weight = 99
7943 "#,
7944 )?;
7945 jail.create_file(
7946 "foundry.toml",
7947 r#"
7948 [profile.default]
7949 extends = "base.toml"
7950
7951 [invariant]
7952 runs = 420
7953 "#,
7954 )?;
7955
7956 let config = Config::load().unwrap();
7957 assert_eq!(config.invariant.runs, 420);
7958 assert!(!config.invariant.dictionary.include_storage);
7959 assert_eq!(config.invariant.dictionary.dictionary_weight, 99);
7960
7961 Ok(())
7962 });
7963 }
7964
7965 #[test]
7966 fn test_inheritance_validation() {
7967 figment::Jail::expect_with(|jail| {
7968 jail.create_file(
7970 "base-with-inherit.toml",
7971 r#"
7972 [profile.default]
7973 extends = "another.toml"
7974 optimizer_runs = 800
7975 "#,
7976 )?;
7977
7978 jail.create_file(
7979 "foundry.toml",
7980 r#"
7981 [profile.default]
7982 extends = "base-with-inherit.toml"
7983 "#,
7984 )?;
7985
7986 let result = Config::load();
7988 assert!(result.is_err());
7989 assert!(result.unwrap_err().to_string().contains("Nested inheritance is not allowed"));
7990
7991 jail.create_file(
7993 "foundry.toml",
7994 r#"
7995 [profile.default]
7996 extends = "foundry.toml"
7997 "#,
7998 )?;
7999
8000 let result = Config::load();
8001 assert!(result.is_err());
8002 assert!(result.unwrap_err().to_string().contains("cannot inherit from itself"));
8003
8004 jail.create_file(
8006 "foundry.toml",
8007 r#"
8008 [profile.default]
8009 extends = "non-existent.toml"
8010 "#,
8011 )?;
8012
8013 let result = Config::load();
8014 assert!(result.is_err());
8015 let err_msg = result.unwrap_err().to_string();
8016 assert!(
8017 err_msg.contains("does not exist")
8018 || err_msg.contains("Failed to resolve inherited config path"),
8019 "Error message: {err_msg}"
8020 );
8021
8022 Ok(())
8023 });
8024 }
8025
8026 #[test]
8027 fn test_inheritance_from_profile_name_hints_at_default() {
8028 figment::Jail::expect_with(|jail| {
8029 jail.create_file(
8030 "foundry.toml",
8031 r#"
8032 [profile.default]
8033 optimizer_runs = 200
8034
8035 [profile.ci]
8036 extends = "default"
8037 "#,
8038 )?;
8039 jail.set_env("FOUNDRY_PROFILE", "ci");
8040
8041 let err_msg = Config::load().unwrap_err().to_string();
8042 assert!(
8043 err_msg.contains("every profile already inherits from `[profile.default]`"),
8044 "Error message: {err_msg}"
8045 );
8046
8047 Ok(())
8048 });
8049 }
8050
8051 #[test]
8052 fn test_complex_inheritance_merging() {
8053 figment::Jail::expect_with(|jail| {
8054 jail.create_file(
8056 "base.toml",
8057 r#"
8058 [profile.default]
8059 optimizer = true
8060 optimizer_runs = 1000
8061 via_ir = false
8062 solc = "0.8.19"
8063
8064 [invariant]
8065 runs = 500
8066 depth = 100
8067
8068 [fuzz]
8069 runs = 256
8070 seed = "0x123"
8071
8072 [rpc_endpoints]
8073 mainnet = "https://base-mainnet.com"
8074 optimism = "https://base-optimism.com"
8075 arbitrum = "https://base-arbitrum.com"
8076 "#,
8077 )?;
8078
8079 jail.create_file(
8081 "foundry.toml",
8082 r#"
8083 [profile.default]
8084 extends = "base.toml"
8085 optimizer_runs = 200 # Override
8086 via_ir = true # Override
8087 # optimizer and solc are inherited
8088
8089 [invariant]
8090 runs = 333 # Override
8091 # depth is inherited
8092
8093 # fuzz section is fully inherited
8094
8095 [rpc_endpoints]
8096 mainnet = "https://local-mainnet.com" # Override
8097 # optimism and arbitrum are inherited
8098 polygon = "https://local-polygon.com" # New
8099 "#,
8100 )?;
8101
8102 let config = Config::load().unwrap();
8103
8104 assert_eq!(config.optimizer, Some(true));
8106 assert_eq!(config.optimizer_runs, Some(200));
8107 assert_eq!(config.via_ir, true);
8108 assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 8, 19))));
8109
8110 assert_eq!(config.invariant.runs, 333);
8112 assert_eq!(config.invariant.depth, 100);
8113
8114 assert_eq!(config.fuzz.runs, 256);
8116 assert_eq!(config.fuzz.seed, Some(U256::from(0x123)));
8117
8118 let endpoints = config.rpc_endpoints.resolved();
8120 assert!(endpoints.get("mainnet").unwrap().url().unwrap().contains("local-mainnet"));
8121 assert!(endpoints.get("optimism").unwrap().url().unwrap().contains("base-optimism"));
8122 assert!(endpoints.get("arbitrum").unwrap().url().unwrap().contains("base-arbitrum"));
8123 assert!(endpoints.get("polygon").unwrap().url().unwrap().contains("local-polygon"));
8124
8125 Ok(())
8126 });
8127 }
8128
8129 #[test]
8130 fn test_inheritance_with_different_profiles() {
8131 figment::Jail::expect_with(|jail| {
8132 jail.create_file(
8134 "base.toml",
8135 r#"
8136 [profile.default]
8137 optimizer = true
8138 optimizer_runs = 200
8139
8140 [profile.ci]
8141 optimizer = true
8142 optimizer_runs = 10000
8143 via_ir = true
8144
8145 [profile.dev]
8146 optimizer = false
8147 "#,
8148 )?;
8149
8150 jail.create_file(
8152 "foundry.toml",
8153 r#"
8154 [profile.default]
8155 extends = "base.toml"
8156 verbosity = 3
8157
8158 [profile.ci]
8159 optimizer_runs = 5000 # This doesn't inherit from base.toml's ci profile
8160 "#,
8161 )?;
8162
8163 let config = Config::load().unwrap();
8165 assert_eq!(config.optimizer, Some(true));
8166 assert_eq!(config.optimizer_runs, Some(200));
8167 assert_eq!(config.verbosity, 3);
8168
8169 jail.set_env("FOUNDRY_PROFILE", "ci");
8171 let config = Config::load().unwrap();
8172 assert_eq!(config.optimizer_runs, Some(5000));
8173 assert_eq!(config.optimizer, Some(true));
8174 assert_eq!(config.via_ir, false);
8176
8177 Ok(())
8178 });
8179 }
8180
8181 #[test]
8182 fn test_inheritance_with_env_vars() {
8183 figment::Jail::expect_with(|jail| {
8184 jail.create_file(
8185 "base.toml",
8186 r#"
8187 [profile.default]
8188 optimizer_runs = 500
8189 sender = "0x0000000000000000000000000000000000000001"
8190 verbosity = 1
8191 "#,
8192 )?;
8193
8194 jail.create_file(
8195 "foundry.toml",
8196 r#"
8197 [profile.default]
8198 extends = "base.toml"
8199 verbosity = 2
8200 "#,
8201 )?;
8202
8203 jail.set_env("FOUNDRY_OPTIMIZER_RUNS", "999");
8205 jail.set_env("FOUNDRY_VERBOSITY", "4");
8206
8207 let config = Config::load().unwrap();
8208 assert_eq!(config.optimizer_runs, Some(999));
8209 assert_eq!(config.verbosity, 4);
8210 assert_eq!(config.sender, Address::with_last_byte(1));
8211
8212 Ok(())
8213 });
8214 }
8215
8216 #[test]
8217 fn test_inheritance_with_subdirectories() {
8218 figment::Jail::expect_with(|jail| {
8219 jail.create_dir("configs")?;
8221 jail.create_file(
8222 "configs/base.toml",
8223 r#"
8224 [profile.default]
8225 optimizer_runs = 800
8226 src = "contracts"
8227 "#,
8228 )?;
8229
8230 jail.create_file(
8232 "foundry.toml",
8233 r#"
8234 [profile.default]
8235 extends = "configs/base.toml"
8236 test = "tests"
8237 "#,
8238 )?;
8239
8240 let config = Config::load().unwrap();
8241 assert_eq!(config.optimizer_runs, Some(800));
8242 assert_eq!(config.src, PathBuf::from("contracts"));
8243 assert_eq!(config.test, PathBuf::from("tests"));
8244
8245 jail.create_dir("project")?;
8247 jail.create_file(
8248 "shared-base.toml",
8249 r#"
8250 [profile.default]
8251 optimizer_runs = 1500
8252 "#,
8253 )?;
8254
8255 jail.create_file(
8256 "project/foundry.toml",
8257 r#"
8258 [profile.default]
8259 extends = "../shared-base.toml"
8260 "#,
8261 )?;
8262
8263 std::env::set_current_dir(jail.directory().join("project")).unwrap();
8264 let config = Config::load().unwrap();
8265 assert_eq!(config.optimizer_runs, Some(1500));
8266
8267 Ok(())
8268 });
8269 }
8270
8271 #[test]
8272 fn test_inheritance_with_empty_files() {
8273 figment::Jail::expect_with(|jail| {
8274 jail.create_file(
8276 "base.toml",
8277 r#"
8278 [profile.default]
8279 "#,
8280 )?;
8281
8282 jail.create_file(
8283 "foundry.toml",
8284 r#"
8285 [profile.default]
8286 extends = "base.toml"
8287 optimizer_runs = 300
8288 "#,
8289 )?;
8290
8291 let config = Config::load().unwrap();
8292 assert_eq!(config.optimizer_runs, Some(300));
8293
8294 jail.create_file(
8296 "base2.toml",
8297 r#"
8298 [profile.default]
8299 optimizer_runs = 400
8300 via_ir = true
8301 "#,
8302 )?;
8303
8304 jail.create_file(
8305 "foundry.toml",
8306 r#"
8307 [profile.default]
8308 extends = "base2.toml"
8309 "#,
8310 )?;
8311
8312 let config = Config::load().unwrap();
8313 assert_eq!(config.optimizer_runs, Some(400));
8314 assert!(config.via_ir);
8315
8316 Ok(())
8317 });
8318 }
8319
8320 #[test]
8321 fn test_inheritance_array_and_table_merging() {
8322 figment::Jail::expect_with(|jail| {
8323 jail.create_file(
8324 "base.toml",
8325 r#"
8326 [profile.default]
8327 libs = ["lib", "node_modules"]
8328 ignored_error_codes = [5667, 1878]
8329 extra_output = ["metadata", "ir"]
8330
8331 [profile.default.model_checker]
8332 engine = "chc"
8333 timeout = 10000
8334 targets = ["assert"]
8335
8336 [profile.default.optimizer_details]
8337 peephole = true
8338 inliner = true
8339 "#,
8340 )?;
8341
8342 jail.create_file(
8343 "foundry.toml",
8344 r#"
8345 [profile.default]
8346 extends = "base.toml"
8347 libs = ["custom-lib"] # Concatenates with base array
8348 ignored_error_codes = [2018] # Concatenates with base array
8349
8350 [profile.default.model_checker]
8351 timeout = 5000 # Overrides base value
8352 # engine and targets are inherited
8353
8354 [profile.default.optimizer_details]
8355 jumpdest_remover = true # Adds new field
8356 # peephole and inliner are inherited
8357 "#,
8358 )?;
8359
8360 let config = Config::load().unwrap();
8361
8362 assert_eq!(
8364 config.libs,
8365 vec![
8366 PathBuf::from("lib"),
8367 PathBuf::from("node_modules"),
8368 PathBuf::from("custom-lib")
8369 ]
8370 );
8371 assert_eq!(
8372 config.ignored_error_codes,
8373 vec![
8374 SolidityErrorCode::UnusedFunctionParameter, SolidityErrorCode::SpdxLicenseNotProvided, SolidityErrorCode::FunctionStateMutabilityCanBeRestricted ]
8378 );
8379
8380 assert_eq!(config.model_checker.as_ref().unwrap().timeout, Some(5000));
8382 assert_eq!(
8383 config.model_checker.as_ref().unwrap().engine,
8384 Some(ModelCheckerEngine::CHC)
8385 );
8386 assert_eq!(
8387 config.model_checker.as_ref().unwrap().targets,
8388 Some(vec![ModelCheckerTarget::Assert])
8389 );
8390
8391 assert_eq!(config.optimizer_details.as_ref().unwrap().peephole, Some(true));
8393 assert_eq!(config.optimizer_details.as_ref().unwrap().inliner, Some(true));
8394 assert_eq!(config.optimizer_details.as_ref().unwrap().jumpdest_remover, None);
8395
8396 Ok(())
8397 });
8398 }
8399
8400 #[test]
8401 fn test_inheritance_with_special_sections() {
8402 figment::Jail::expect_with(|jail| {
8403 jail.create_file(
8404 "base.toml",
8405 r#"
8406 [profile.default]
8407 # Base file should not have 'extends' to avoid nested inheritance
8408
8409 [labels]
8410 "0x0000000000000000000000000000000000000001" = "Alice"
8411 "0x0000000000000000000000000000000000000002" = "Bob"
8412
8413 [[profile.default.fs_permissions]]
8414 access = "read"
8415 path = "./src"
8416
8417 [[profile.default.fs_permissions]]
8418 access = "read-write"
8419 path = "./cache"
8420 "#,
8421 )?;
8422
8423 jail.create_file(
8424 "foundry.toml",
8425 r#"
8426 [profile.default]
8427 extends = "base.toml"
8428
8429 [labels]
8430 "0x0000000000000000000000000000000000000002" = "Bob Updated"
8431 "0x0000000000000000000000000000000000000003" = "Charlie"
8432
8433 [[profile.default.fs_permissions]]
8434 access = "read"
8435 path = "./test"
8436 "#,
8437 )?;
8438
8439 let config = Config::load().unwrap();
8440
8441 assert_eq!(config.labels.get(&Address::with_last_byte(1)), Some(&"Alice".to_string()));
8443 assert_eq!(
8444 config.labels.get(&Address::with_last_byte(2)),
8445 Some(&"Bob Updated".to_string())
8446 );
8447 assert_eq!(
8448 config.labels.get(&Address::with_last_byte(3)),
8449 Some(&"Charlie".to_string())
8450 );
8451
8452 assert_eq!(config.fs_permissions.permissions.len(), 3); assert!(
8456 config
8457 .fs_permissions
8458 .permissions
8459 .iter()
8460 .any(|p| p.path.to_str().unwrap() == "./src")
8461 );
8462 assert!(
8463 config
8464 .fs_permissions
8465 .permissions
8466 .iter()
8467 .any(|p| p.path.to_str().unwrap() == "./cache")
8468 );
8469 assert!(
8470 config
8471 .fs_permissions
8472 .permissions
8473 .iter()
8474 .any(|p| p.path.to_str().unwrap() == "./test")
8475 );
8476
8477 Ok(())
8478 });
8479 }
8480
8481 #[test]
8482 fn test_inheritance_with_compilation_settings() {
8483 figment::Jail::expect_with(|jail| {
8484 jail.create_file(
8485 "base.toml",
8486 r#"
8487 [profile.default]
8488 solc = "0.8.19"
8489 evm_version = "paris"
8490 via_ir = false
8491 optimizer = true
8492 optimizer_runs = 200
8493
8494 [profile.default.optimizer_details]
8495 peephole = true
8496 inliner = false
8497 jumpdest_remover = true
8498 order_literals = false
8499 deduplicate = true
8500 cse = true
8501 constant_optimizer = true
8502 yul = true
8503
8504 [profile.default.optimizer_details.yul_details]
8505 stack_allocation = true
8506 optimizer_steps = "dhfoDgvulfnTUtnIf"
8507 "#,
8508 )?;
8509
8510 jail.create_file(
8511 "foundry.toml",
8512 r#"
8513 [profile.default]
8514 extends = "base.toml"
8515 evm_version = "shanghai" # Override
8516 optimizer_runs = 1000 # Override
8517
8518 [profile.default.optimizer_details]
8519 inliner = true # Override
8520 # Rest inherited
8521 "#,
8522 )?;
8523
8524 let config = Config::load().unwrap();
8525
8526 assert_eq!(config.solc, Some(SolcReq::Version(Version::new(0, 8, 19))));
8528 assert_eq!(config.evm_version, EvmVersion::Shanghai);
8529 assert_eq!(config.via_ir, false);
8530 assert_eq!(config.optimizer, Some(true));
8531 assert_eq!(config.optimizer_runs, Some(1000));
8532
8533 let details = config.optimizer_details.as_ref().unwrap();
8535 assert_eq!(details.peephole, Some(true));
8536 assert_eq!(details.inliner, Some(true));
8537 assert_eq!(details.jumpdest_remover, None);
8538 assert_eq!(details.order_literals, None);
8539 assert_eq!(details.deduplicate, Some(true));
8540 assert_eq!(details.cse, Some(true));
8541 assert_eq!(details.constant_optimizer, None);
8542 assert_eq!(details.yul, Some(true));
8543
8544 if let Some(yul_details) = details.yul_details.as_ref() {
8546 assert_eq!(yul_details.stack_allocation, Some(true));
8547 assert_eq!(yul_details.optimizer_steps, Some("dhfoDgvulfnTUtnIf".to_string()));
8548 }
8549
8550 Ok(())
8551 });
8552 }
8553
8554 #[test]
8555 fn test_inheritance_with_remappings() {
8556 figment::Jail::expect_with(|jail| {
8557 jail.create_file(
8558 "base.toml",
8559 r#"
8560 [profile.default]
8561 remappings = [
8562 "forge-std/=lib/forge-std/src/",
8563 "@openzeppelin/=lib/openzeppelin-contracts/",
8564 "ds-test/=lib/ds-test/src/"
8565 ]
8566 auto_detect_remappings = false
8567 "#,
8568 )?;
8569
8570 jail.create_file(
8571 "foundry.toml",
8572 r#"
8573 [profile.default]
8574 extends = "base.toml"
8575 remappings = [
8576 "@custom/=lib/custom/",
8577 "ds-test/=lib/forge-std/lib/ds-test/src/" # Note: This will be added alongside base remappings
8578 ]
8579 "#,
8580 )?;
8581
8582 let config = Config::load().unwrap();
8583
8584 assert!(config.remappings.iter().any(|r| r.to_string().contains("@custom/")));
8586 assert!(config.remappings.iter().any(|r| r.to_string().contains("ds-test/")));
8587 assert!(config.remappings.iter().any(|r| r.to_string().contains("forge-std/")));
8588 assert!(config.remappings.iter().any(|r| r.to_string().contains("@openzeppelin/")));
8589
8590 assert!(!config.auto_detect_remappings);
8592
8593 Ok(())
8594 });
8595 }
8596
8597 #[test]
8598 fn test_inheritance_with_multiple_profiles_and_single_file() {
8599 figment::Jail::expect_with(|jail| {
8600 jail.create_file(
8602 "base.toml",
8603 r#"
8604 [profile.prod]
8605 optimizer = true
8606 optimizer_runs = 10000
8607 via_ir = true
8608
8609 [profile.test]
8610 optimizer = false
8611
8612 [profile.test.fuzz]
8613 runs = 100
8614 "#,
8615 )?;
8616
8617 jail.create_file(
8619 "foundry.toml",
8620 r#"
8621 [profile.prod]
8622 extends = "base.toml"
8623 evm_version = "shanghai" # Additional setting
8624
8625 [profile.test]
8626 extends = "base.toml"
8627
8628 [profile.test.fuzz]
8629 runs = 500 # Override
8630 "#,
8631 )?;
8632
8633 jail.set_env("FOUNDRY_PROFILE", "prod");
8635 let config = Config::load().unwrap();
8636 assert_eq!(config.optimizer, Some(true));
8637 assert_eq!(config.optimizer_runs, Some(10000));
8638 assert_eq!(config.via_ir, true);
8639 assert_eq!(config.evm_version, EvmVersion::Shanghai);
8640
8641 jail.set_env("FOUNDRY_PROFILE", "test");
8643 let config = Config::load().unwrap();
8644 assert_eq!(config.optimizer, Some(false));
8645 assert_eq!(config.fuzz.runs, 500);
8646
8647 Ok(())
8648 });
8649 }
8650
8651 #[test]
8652 fn test_inheritance_with_multiple_profiles_and_files() {
8653 figment::Jail::expect_with(|jail| {
8654 jail.create_file(
8655 "prod.toml",
8656 r#"
8657 [profile.prod]
8658 optimizer = true
8659 optimizer_runs = 20000
8660 gas_limit = 50000000
8661 "#,
8662 )?;
8663 jail.create_file(
8664 "dev.toml",
8665 r#"
8666 [profile.dev]
8667 optimizer = true
8668 optimizer_runs = 333
8669 gas_limit = 555555
8670 "#,
8671 )?;
8672
8673 jail.create_file(
8675 "foundry.toml",
8676 r#"
8677 [profile.dev]
8678 extends = "dev.toml"
8679 sender = "0x0000000000000000000000000000000000000001"
8680
8681 [profile.prod]
8682 extends = "prod.toml"
8683 sender = "0x0000000000000000000000000000000000000002"
8684 "#,
8685 )?;
8686
8687 jail.set_env("FOUNDRY_PROFILE", "dev");
8689 let config = Config::load().unwrap();
8690 assert_eq!(config.optimizer, Some(true));
8691 assert_eq!(config.optimizer_runs, Some(333));
8692 assert_eq!(config.gas_limit, 555555.into());
8693 assert_eq!(config.sender, Address::with_last_byte(1));
8694
8695 jail.set_env("FOUNDRY_PROFILE", "prod");
8697 let config = Config::load().unwrap();
8698 assert_eq!(config.optimizer, Some(true));
8699 assert_eq!(config.optimizer_runs, Some(20000));
8700 assert_eq!(config.gas_limit, 50000000.into());
8701 assert_eq!(config.sender, Address::with_last_byte(2));
8702
8703 Ok(())
8704 });
8705 }
8706
8707 #[test]
8708 fn test_extends_strategy_extend_arrays() {
8709 figment::Jail::expect_with(|jail| {
8710 jail.create_file(
8712 "base.toml",
8713 r#"
8714 [profile.default]
8715 libs = ["lib", "node_modules"]
8716 ignored_error_codes = [5667, 1878]
8717 optimizer_runs = 200
8718 "#,
8719 )?;
8720
8721 jail.create_file(
8723 "foundry.toml",
8724 r#"
8725 [profile.default]
8726 extends = "base.toml"
8727 libs = ["mylib", "customlib"]
8728 ignored_error_codes = [1234]
8729 optimizer_runs = 500
8730 "#,
8731 )?;
8732
8733 let config = Config::load().unwrap();
8734
8735 assert_eq!(config.libs.len(), 4);
8737 assert!(config.libs.iter().any(|l| l.to_str() == Some("lib")));
8738 assert!(config.libs.iter().any(|l| l.to_str() == Some("node_modules")));
8739 assert!(config.libs.iter().any(|l| l.to_str() == Some("mylib")));
8740 assert!(config.libs.iter().any(|l| l.to_str() == Some("customlib")));
8741
8742 assert_eq!(config.ignored_error_codes.len(), 3);
8743 assert!(
8744 config.ignored_error_codes.contains(&SolidityErrorCode::UnusedFunctionParameter)
8745 ); assert!(
8747 config.ignored_error_codes.contains(&SolidityErrorCode::SpdxLicenseNotProvided)
8748 ); assert!(config.ignored_error_codes.contains(&SolidityErrorCode::from(1234u64))); assert_eq!(config.optimizer_runs, Some(500));
8753
8754 Ok(())
8755 });
8756 }
8757
8758 #[test]
8759 fn test_extends_strategy_replace_arrays() {
8760 figment::Jail::expect_with(|jail| {
8761 jail.create_file(
8763 "base.toml",
8764 r#"
8765 [profile.default]
8766 libs = ["lib", "node_modules"]
8767 ignored_error_codes = [5667, 1878]
8768 optimizer_runs = 200
8769 "#,
8770 )?;
8771
8772 jail.create_file(
8774 "foundry.toml",
8775 r#"
8776 [profile.default]
8777 extends = { path = "base.toml", strategy = "replace-arrays" }
8778 libs = ["mylib", "customlib"]
8779 ignored_error_codes = [1234]
8780 optimizer_runs = 500
8781 "#,
8782 )?;
8783
8784 let config = Config::load().unwrap();
8785
8786 assert_eq!(config.libs.len(), 2);
8788 assert!(config.libs.iter().any(|l| l.to_str() == Some("mylib")));
8789 assert!(config.libs.iter().any(|l| l.to_str() == Some("customlib")));
8790 assert!(!config.libs.iter().any(|l| l.to_str() == Some("lib")));
8791 assert!(!config.libs.iter().any(|l| l.to_str() == Some("node_modules")));
8792
8793 assert_eq!(config.ignored_error_codes.len(), 1);
8794 assert!(config.ignored_error_codes.contains(&SolidityErrorCode::from(1234u64))); assert!(
8796 !config.ignored_error_codes.contains(&SolidityErrorCode::UnusedFunctionParameter)
8797 ); assert_eq!(config.optimizer_runs, Some(500));
8801
8802 Ok(())
8803 });
8804 }
8805
8806 #[test]
8807 fn test_extends_strategy_no_collision_success() {
8808 figment::Jail::expect_with(|jail| {
8809 jail.create_file(
8811 "base.toml",
8812 r#"
8813 [profile.default]
8814 optimizer = true
8815 optimizer_runs = 200
8816 src = "src"
8817 "#,
8818 )?;
8819
8820 jail.create_file(
8822 "foundry.toml",
8823 r#"
8824 [profile.default]
8825 extends = { path = "base.toml", strategy = "no-collision" }
8826 test = "tests"
8827 libs = ["lib"]
8828 "#,
8829 )?;
8830
8831 let config = Config::load().unwrap();
8832
8833 assert_eq!(config.optimizer, Some(true));
8835 assert_eq!(config.optimizer_runs, Some(200));
8836 assert_eq!(config.src, PathBuf::from("src"));
8837
8838 assert_eq!(config.test, PathBuf::from("tests"));
8840 assert_eq!(config.libs.len(), 1);
8841 assert!(config.libs.iter().any(|l| l.to_str() == Some("lib")));
8842
8843 Ok(())
8844 });
8845 }
8846
8847 #[test]
8848 fn test_extends_strategy_no_collision_error() {
8849 figment::Jail::expect_with(|jail| {
8850 jail.create_file(
8852 "base.toml",
8853 r#"
8854 [profile.default]
8855 optimizer = true
8856 optimizer_runs = 200
8857 libs = ["lib", "node_modules"]
8858 "#,
8859 )?;
8860
8861 jail.create_file(
8863 "foundry.toml",
8864 r#"
8865 [profile.default]
8866 extends = { path = "base.toml", strategy = "no-collision" }
8867 optimizer_runs = 500
8868 libs = ["mylib"]
8869 "#,
8870 )?;
8871
8872 let result = Config::load();
8874
8875 if let Ok(config) = result {
8876 panic!(
8877 "Expected error but got config with optimizer_runs: {:?}, libs: {:?}",
8878 config.optimizer_runs, config.libs
8879 );
8880 }
8881
8882 let err = result.unwrap_err();
8883 let err_str = err.to_string();
8884 assert!(
8885 err_str.contains("Key collision detected") || err_str.contains("collision"),
8886 "Error message doesn't mention collision: {err_str}"
8887 );
8888
8889 Ok(())
8890 });
8891 }
8892
8893 #[test]
8894 fn test_extends_both_syntaxes() {
8895 figment::Jail::expect_with(|jail| {
8896 jail.create_file(
8898 "base.toml",
8899 r#"
8900 [profile.default]
8901 libs = ["lib"]
8902 optimizer = true
8903 "#,
8904 )?;
8905
8906 jail.create_file(
8908 "foundry_string.toml",
8909 r#"
8910 [profile.default]
8911 extends = "base.toml"
8912 libs = ["custom"]
8913 "#,
8914 )?;
8915
8916 jail.create_file(
8918 "foundry_object.toml",
8919 r#"
8920 [profile.default]
8921 extends = { path = "base.toml", strategy = "replace-arrays" }
8922 libs = ["custom"]
8923 "#,
8924 )?;
8925
8926 jail.set_env("FOUNDRY_CONFIG", "foundry_string.toml");
8928 let config = Config::load().unwrap();
8929 assert_eq!(config.libs.len(), 2); assert!(config.libs.iter().any(|l| l.to_str() == Some("lib")));
8931 assert!(config.libs.iter().any(|l| l.to_str() == Some("custom")));
8932
8933 jail.set_env("FOUNDRY_CONFIG", "foundry_object.toml");
8935 let config = Config::load().unwrap();
8936 assert_eq!(config.libs.len(), 1); assert!(config.libs.iter().any(|l| l.to_str() == Some("custom")));
8938 assert!(!config.libs.iter().any(|l| l.to_str() == Some("lib")));
8939
8940 Ok(())
8941 });
8942 }
8943
8944 #[test]
8945 fn test_extends_strategy_default_is_extend_arrays() {
8946 figment::Jail::expect_with(|jail| {
8947 jail.create_file(
8949 "base.toml",
8950 r#"
8951 [profile.default]
8952 libs = ["lib", "node_modules"]
8953 optimizer = true
8954 "#,
8955 )?;
8956
8957 jail.create_file(
8959 "foundry.toml",
8960 r#"
8961 [profile.default]
8962 extends = "base.toml"
8963 libs = ["custom"]
8964 optimizer = false
8965 "#,
8966 )?;
8967
8968 let config = Config::load().unwrap();
8970
8971 assert_eq!(config.libs.len(), 3);
8973 assert!(config.libs.iter().any(|l| l.to_str() == Some("lib")));
8974 assert!(config.libs.iter().any(|l| l.to_str() == Some("node_modules")));
8975 assert!(config.libs.iter().any(|l| l.to_str() == Some("custom")));
8976
8977 assert_eq!(config.optimizer, Some(false));
8979
8980 Ok(())
8981 });
8982 }
8983
8984 #[test]
8985 fn test_deprecated_deny_warnings_is_handled() {
8986 figment::Jail::expect_with(|jail| {
8987 jail.create_file(
8988 "foundry.toml",
8989 r#"
8990 [profile.default]
8991 deny_warnings = true
8992 "#,
8993 )?;
8994 let config = Config::load().unwrap();
8995
8996 assert_eq!(config.deny, DenyLevel::Warnings);
8998 Ok(())
8999 });
9000 }
9001
9002 #[test]
9003 fn warns_on_deprecated_keys_in_inactive_profiles() {
9004 figment::Jail::expect_with(|jail| {
9005 jail.create_file(
9006 "foundry.toml",
9007 r#"
9008 [profile.default]
9009 src = "src"
9010
9011 [profile.ci]
9012 deny_warnings = true
9013 "#,
9014 )?;
9015
9016 let cfg = Config::load().unwrap();
9017 assert!(
9018 cfg.warnings.iter().any(|w| matches!(
9019 w,
9020 crate::Warning::DeprecatedKey { old, new }
9021 if old == "deny_warnings" && new == "deny = warnings"
9022 )),
9023 "Expected deprecated key warning for inactive profile, got: {:?}",
9024 cfg.warnings
9025 );
9026 Ok(())
9027 });
9028 }
9029
9030 #[test]
9031 fn warns_on_deprecated_profile_names() {
9032 figment::Jail::expect_with(|jail| {
9033 jail.create_file(
9034 "foundry.toml",
9035 r#"
9036 [profile.cancun]
9037 "#,
9038 )?;
9039
9040 let cfg = Config::load().unwrap();
9041 assert!(
9042 cfg.warnings.iter().any(|w| matches!(
9043 w,
9044 crate::Warning::DeprecatedKey { old, new }
9045 if old == "cancun" && new == "evm_version = Cancun"
9046 )),
9047 "Expected deprecated profile-name warning, got: {:?}",
9048 cfg.warnings
9049 );
9050 Ok(())
9051 });
9052 }
9053
9054 #[test]
9055 fn warns_on_unknown_keys_in_profile() {
9056 figment::Jail::expect_with(|jail| {
9057 jail.create_file(
9058 "foundry.toml",
9059 r#"
9060 [profile.default]
9061 unknown_key_xyz = 123
9062 "#,
9063 )?;
9064
9065 let cfg = Config::load().unwrap();
9066 assert!(cfg.warnings.iter().any(
9067 |w| matches!(w, crate::Warning::UnknownKey { key, .. } if key == "unknown_key_xyz")
9068 ));
9069 Ok(())
9070 });
9071 }
9072
9073 #[test]
9074 fn warns_on_unknown_keys_in_endpoint_entries() {
9075 figment::Jail::expect_with(|jail| {
9076 jail.create_file(
9077 "foundry.toml",
9078 r#"
9079 [profile.default.rpc_endpoints]
9080 local = { endpoint = "http://localhost:8545", retriez = 3 }
9081
9082 [rpc_endpoints]
9083 mainnet = "https://eth.example"
9084 sepolia = { url = "https://sepolia.example", retries = 2, auth = "token" }
9085 optimism = { endpoints = ["https://op.example"], compute_units_per_second = 10 }
9086 base = { endpoint = "https://base.example", timeout = 5 }
9087
9088 [etherscan]
9089 mainnet = { key = "KEY", chainId = 1 }
9090 sepolia = { key = "KEY", chain = 11155111, url = "https://api.example" }
9091 "#,
9092 )?;
9093
9094 let cfg = Config::load().unwrap();
9095 let unknown: Vec<_> = cfg
9096 .warnings
9097 .iter()
9098 .filter_map(|w| match w {
9099 crate::Warning::UnknownSectionKey { key, section, .. } => {
9100 Some((key.as_str(), section.as_str()))
9101 }
9102 _ => None,
9103 })
9104 .collect();
9105 assert_eq!(
9106 unknown,
9107 [
9108 ("retriez", "rpc_endpoints.local"),
9109 ("timeout", "rpc_endpoints.base"),
9110 ("chainId", "etherscan.mainnet"),
9111 ],
9112 "{:?}",
9113 cfg.warnings
9114 );
9115 Ok(())
9116 });
9117 }
9118
9119 #[test]
9120 fn no_unknown_key_warning_for_network_field() {
9121 figment::Jail::expect_with(|jail| {
9124 jail.create_file(
9125 "foundry.toml",
9126 r#"
9127 [profile.default]
9128 network = "tempo"
9129 "#,
9130 )?;
9131
9132 let cfg = Config::load().unwrap();
9133 assert!(
9134 !cfg.warnings.iter().any(
9135 |w| matches!(w, crate::Warning::UnknownKey { key, .. } if key == "network")
9136 ),
9137 "did not expect UnknownKey warning for `network`, got: {:?}",
9138 cfg.warnings
9139 );
9140 Ok(())
9141 });
9142 }
9143
9144 #[test]
9145 fn no_unknown_key_warning_for_legacy_tempo_alias() {
9146 figment::Jail::expect_with(|jail| {
9148 jail.create_file(
9149 "foundry.toml",
9150 r#"
9151 [profile.default]
9152 tempo = true
9153 "#,
9154 )?;
9155
9156 let cfg = Config::load().unwrap();
9157 assert!(
9158 !cfg.warnings
9159 .iter()
9160 .any(|w| matches!(w, crate::Warning::UnknownKey { key, .. } if key == "tempo")),
9161 "did not expect UnknownKey warning for `tempo`, got: {:?}",
9162 cfg.warnings
9163 );
9164 Ok(())
9165 });
9166 }
9167
9168 #[test]
9169 #[cfg(feature = "monad")]
9170 fn no_unknown_key_warning_for_legacy_monad_alias() {
9171 figment::Jail::expect_with(|jail| {
9172 jail.create_file(
9173 "foundry.toml",
9174 r#"
9175 [profile.default]
9176 monad = true
9177 "#,
9178 )?;
9179
9180 let cfg = Config::load().unwrap();
9181 assert!(
9182 !cfg.warnings
9183 .iter()
9184 .any(|w| matches!(w, crate::Warning::UnknownKey { key, .. } if key == "monad")),
9185 "did not expect UnknownKey warning for `monad`, got: {:?}",
9186 cfg.warnings
9187 );
9188 Ok(())
9189 });
9190 }
9191
9192 #[test]
9193 #[cfg(not(feature = "monad"))]
9194 fn warns_for_monad_alias_without_monad_support() {
9195 figment::Jail::expect_with(|jail| {
9196 jail.create_file(
9197 "foundry.toml",
9198 r#"
9199 [profile.default]
9200 monad = true
9201 "#,
9202 )?;
9203
9204 let cfg = Config::load().unwrap();
9205 assert!(
9206 cfg.warnings
9207 .iter()
9208 .any(|w| matches!(w, crate::Warning::UnknownKey { key, .. } if key == "monad")),
9209 "expected UnknownKey warning for `monad`, got: {:?}",
9210 cfg.warnings
9211 );
9212 Ok(())
9213 });
9214 }
9215
9216 #[test]
9217 fn fails_on_ambiguous_version_in_compilation_restrictions() {
9218 figment::Jail::expect_with(|jail| {
9219 jail.create_file(
9220 "foundry.toml",
9221 r#"
9222 [profile.default]
9223 src = "src"
9224
9225 [[profile.default.compilation_restrictions]]
9226 paths = "src/*.sol"
9227 version = "0.8.11"
9228 "#,
9229 )?;
9230
9231 let err = Config::load().expect_err("expected bare version to fail");
9232 let err_msg = err.to_string();
9233 assert!(
9234 err_msg.contains("Invalid version format '0.8.11'")
9235 && err_msg.contains("Bare version numbers are ambiguous"),
9236 "Expected error about ambiguous version, got: {err_msg}"
9237 );
9238
9239 Ok(())
9240 });
9241 }
9242
9243 #[test]
9244 fn accepts_explicit_version_requirements() {
9245 figment::Jail::expect_with(|jail| {
9246 jail.create_file(
9247 "foundry.toml",
9248 r#"
9249 [profile.default]
9250 src = "src"
9251
9252 [[profile.default.compilation_restrictions]]
9253 paths = "src/*.sol"
9254 version = "=0.8.11"
9255
9256 [[profile.default.compilation_restrictions]]
9257 paths = "test/*.sol"
9258 version = ">=0.8.11"
9259 "#,
9260 )?;
9261
9262 let config = Config::load().expect("should accept explicit version requirements");
9263 assert_eq!(config.compilation_restrictions.len(), 2);
9264
9265 Ok(())
9266 });
9267 }
9268
9269 #[test]
9270 fn warns_on_unknown_keys_in_all_config_sections() {
9271 figment::Jail::expect_with(|jail| {
9272 jail.create_file(
9273 "foundry.toml",
9274 r#"
9275 [profile.default]
9276 src = "src"
9277 unknown_profile_key = "should_warn"
9278
9279 # Standalone sections with unknown keys
9280 [fmt]
9281 line_length = 120
9282 unknown_fmt_key = "should_warn"
9283
9284 [lint]
9285 severity = ["high"]
9286 unknown_lint_key = "should_warn"
9287
9288 [doc]
9289 out = "docs"
9290 unknown_doc_key = "should_warn"
9291
9292 [fuzz]
9293 runs = 256
9294 unknown_fuzz_key = "should_warn"
9295
9296 [invariant]
9297 runs = 256
9298 unknown_invariant_key = "should_warn"
9299
9300 [symbolic]
9301 enabled = true
9302 depth = 128
9303 unknown_symbolic_key = "should_warn"
9304
9305 [mutation]
9306 unknown_mutation_key = "should_warn"
9307
9308 [vyper]
9309 unknown_vyper_key = "should_warn"
9310
9311 [bind_json]
9312 out = "bindings.sol"
9313 unknown_bind_json_key = "should_warn"
9314
9315 # Nested profile sections with unknown keys
9316 [profile.default.fmt]
9317 line_length = 100
9318 unknown_nested_fmt_key = "should_warn"
9319
9320 [profile.default.lint]
9321 severity = ["low"]
9322 unknown_nested_lint_key = "should_warn"
9323
9324 [profile.default.doc]
9325 out = "documentation"
9326 unknown_nested_doc_key = "should_warn"
9327
9328 [profile.default.fuzz]
9329 runs = 512
9330 unknown_nested_fuzz_key = "should_warn"
9331
9332 [profile.default.invariant]
9333 runs = 512
9334 unknown_nested_invariant_key = "should_warn"
9335
9336 [profile.default.symbolic]
9337 max_paths = 512
9338 unknown_nested_symbolic_key = "should_warn"
9339
9340 [profile.default.mutation]
9341 unknown_nested_mutation_key = "should_warn"
9342
9343 [profile.default.vyper]
9344 unknown_nested_vyper_key = "should_warn"
9345
9346 [profile.default.bind_json]
9347 out = "nested_bindings.sol"
9348 unknown_nested_bind_json_key = "should_warn"
9349
9350 # Array sections with unknown keys
9351 [[profile.default.compilation_restrictions]]
9352 paths = "src/*.sol"
9353 unknown_compilation_key = "should_warn"
9354
9355 [[profile.default.additional_compiler_profiles]]
9356 name = "via-ir"
9357 via_ir = true
9358 unknown_compiler_profile_key = "should_warn"
9359 "#,
9360 )?;
9361
9362 let cfg = Config::load().unwrap();
9363
9364 assert!(
9366 cfg.warnings.iter().any(|w| matches!(
9367 w,
9368 crate::Warning::UnknownKey { key, .. } if key == "unknown_profile_key"
9369 )),
9370 "Expected warning for 'unknown_profile_key' in profile, got: {:?}",
9371 cfg.warnings
9372 );
9373
9374 let standalone_expected = [
9376 ("unknown_fmt_key", "fmt"),
9377 ("unknown_lint_key", "lint"),
9378 ("unknown_doc_key", "doc"),
9379 ("unknown_fuzz_key", "fuzz"),
9380 ("unknown_invariant_key", "invariant"),
9381 ("unknown_symbolic_key", "symbolic"),
9382 ("unknown_mutation_key", "mutation"),
9383 ("unknown_vyper_key", "vyper"),
9384 ("unknown_bind_json_key", "bind_json"),
9385 ];
9386
9387 for (expected_key, expected_section) in standalone_expected {
9388 assert!(
9389 cfg.warnings.iter().any(|w| matches!(
9390 w,
9391 crate::Warning::UnknownSectionKey { key, section, .. }
9392 if key == expected_key && section == expected_section
9393 )),
9394 "Expected warning for '{}' in standalone section '{}', got: {:?}",
9395 expected_key,
9396 expected_section,
9397 cfg.warnings
9398 );
9399 }
9400
9401 let nested_expected = [
9403 ("unknown_nested_fmt_key", "fmt"),
9404 ("unknown_nested_lint_key", "lint"),
9405 ("unknown_nested_doc_key", "doc"),
9406 ("unknown_nested_fuzz_key", "fuzz"),
9407 ("unknown_nested_invariant_key", "invariant"),
9408 ("unknown_nested_symbolic_key", "symbolic"),
9409 ("unknown_nested_mutation_key", "mutation"),
9410 ("unknown_nested_vyper_key", "vyper"),
9411 ("unknown_nested_bind_json_key", "bind_json"),
9412 ];
9413
9414 for (expected_key, expected_section) in nested_expected {
9415 assert!(
9416 cfg.warnings.iter().any(|w| matches!(
9417 w,
9418 crate::Warning::UnknownSectionKey { key, section, .. }
9419 if key == expected_key && section == expected_section
9420 )),
9421 "Expected warning for '{}' in nested section '{}', got: {:?}",
9422 expected_key,
9423 expected_section,
9424 cfg.warnings
9425 );
9426 }
9427
9428 let array_expected = [
9430 ("unknown_compilation_key", "compilation_restrictions"),
9431 ("unknown_compiler_profile_key", "additional_compiler_profiles"),
9432 ];
9433
9434 for (expected_key, expected_section) in array_expected {
9435 assert!(
9436 cfg.warnings.iter().any(|w| matches!(
9437 w,
9438 crate::Warning::UnknownSectionKey { key, section, .. }
9439 if key == expected_key && section == expected_section
9440 )),
9441 "Expected warning for '{}' in array section '{}', got: {:?}",
9442 expected_key,
9443 expected_section,
9444 cfg.warnings
9445 );
9446 }
9447
9448 let unknown_key_warnings: Vec<_> = cfg
9450 .warnings
9451 .iter()
9452 .filter(|w| {
9453 matches!(w, crate::Warning::UnknownKey { .. })
9454 || matches!(w, crate::Warning::UnknownSectionKey { .. })
9455 })
9456 .collect();
9457
9458 assert_eq!(
9460 unknown_key_warnings.len(),
9461 21,
9462 "Expected 21 unknown key warnings (1 profile + 9 standalone + 9 nested + 2 array), got {}: {:?}",
9463 unknown_key_warnings.len(),
9464 unknown_key_warnings
9465 );
9466
9467 Ok(())
9468 });
9469 }
9470
9471 #[test]
9472 fn warns_on_unknown_keys_in_extended_config() {
9473 figment::Jail::expect_with(|jail| {
9474 jail.create_file(
9476 "base.toml",
9477 r#"
9478 [profile.default]
9479 optimizer_runs = 800
9480 unknown_base_profile_key = "should_warn"
9481
9482 [lint]
9483 severity = ["high"]
9484 unknown_base_lint_key = "should_warn"
9485
9486 [fmt]
9487 line_length = 100
9488 unknown_base_fmt_key = "should_warn"
9489 "#,
9490 )?;
9491
9492 jail.create_file(
9494 "foundry.toml",
9495 r#"
9496 [profile.default]
9497 extends = "base.toml"
9498 src = "src"
9499 unknown_local_profile_key = "should_warn"
9500
9501 [lint]
9502 unknown_local_lint_key = "should_warn"
9503
9504 [fuzz]
9505 runs = 512
9506 unknown_local_fuzz_key = "should_warn"
9507
9508 [[profile.default.compilation_restrictions]]
9509 paths = "src/*.sol"
9510 unknown_local_restriction_key = "should_warn"
9511 "#,
9512 )?;
9513
9514 let cfg = Config::load().unwrap();
9515
9516 assert_eq!(cfg.optimizer_runs, Some(800));
9518
9519 let expected_unknown_keys = ["unknown_base_profile_key", "unknown_local_profile_key"];
9527 for expected_key in expected_unknown_keys {
9528 assert!(
9529 cfg.warnings.iter().any(|w| matches!(
9530 w,
9531 crate::Warning::UnknownKey { key, .. } if key == expected_key
9532 )),
9533 "Expected warning for '{}', got: {:?}",
9534 expected_key,
9535 cfg.warnings
9536 );
9537 }
9538
9539 let expected_section_keys = [
9540 ("unknown_base_lint_key", "lint"),
9541 ("unknown_base_fmt_key", "fmt"),
9542 ("unknown_local_lint_key", "lint"),
9543 ("unknown_local_fuzz_key", "fuzz"),
9544 ("unknown_local_restriction_key", "compilation_restrictions"),
9545 ];
9546 for (expected_key, expected_section) in expected_section_keys {
9547 assert!(
9548 cfg.warnings.iter().any(|w| matches!(
9549 w,
9550 crate::Warning::UnknownSectionKey { key, section, .. }
9551 if key == expected_key && section == expected_section
9552 )),
9553 "Expected warning for '{}' in section '{}', got: {:?}",
9554 expected_key,
9555 expected_section,
9556 cfg.warnings
9557 );
9558 }
9559
9560 let unknown_warnings: Vec<_> = cfg
9562 .warnings
9563 .iter()
9564 .filter(|w| {
9565 matches!(w, crate::Warning::UnknownKey { .. })
9566 || matches!(w, crate::Warning::UnknownSectionKey { .. })
9567 })
9568 .collect();
9569 assert_eq!(
9570 unknown_warnings.len(),
9571 7,
9572 "Expected 7 unknown key warnings, got {}: {:?}",
9573 unknown_warnings.len(),
9574 unknown_warnings
9575 );
9576
9577 Ok(())
9578 });
9579 }
9580
9581 #[test]
9583 fn warns_on_unknown_profile() {
9584 figment::Jail::expect_with(|jail| {
9585 jail.create_file(
9586 "foundry.toml",
9587 r#"
9588 [profile.default]
9589 src = "src"
9590 "#,
9591 )?;
9592
9593 jail.set_env("FOUNDRY_PROFILE", "nonexistent");
9594 let cfg = Config::load().expect("expected unknown profile to fall back to default");
9595 assert_eq!(cfg.profile, Config::DEFAULT_PROFILE);
9596 assert!(
9597 cfg.warnings.iter().any(|w| matches!(
9598 w,
9599 crate::Warning::UnknownProfile { profile } if profile == "nonexistent"
9600 )),
9601 "Expected UnknownProfile warning, got: {:?}",
9602 cfg.warnings
9603 );
9604
9605 Ok(())
9606 });
9607 }
9608
9609 #[test]
9611 fn no_false_warnings_for_vyper_config_keys() {
9612 figment::Jail::expect_with(|jail| {
9613 jail.create_file(
9614 "foundry.toml",
9615 r#"
9616 [profile.default]
9617 src = "src"
9618
9619 [vyper]
9620 optimize = "O1"
9621 path = "/usr/bin/vyper"
9622 experimental_codegen = true
9623 venom_experimental = false
9624 debug = true
9625 enable_decimals = true
9626
9627 [vyper.venom]
9628 disable_cse = true
9629 inline_threshold = 15
9630 "#,
9631 )?;
9632
9633 let cfg = Config::load().unwrap();
9634 let vyper_warnings: Vec<_> = cfg
9636 .warnings
9637 .iter()
9638 .filter(|w| {
9639 matches!(
9640 w,
9641 crate::Warning::UnknownSectionKey { section, .. } if section == "vyper"
9642 )
9643 })
9644 .collect();
9645
9646 assert!(
9647 vyper_warnings.is_empty(),
9648 "Valid vyper keys should not trigger warnings, got: {vyper_warnings:?}"
9649 );
9650
9651 Ok(())
9652 });
9653 }
9654
9655 #[test]
9657 fn no_false_warnings_for_nested_vyper_config_keys() {
9658 figment::Jail::expect_with(|jail| {
9659 jail.create_file(
9660 "foundry.toml",
9661 r#"
9662 [profile.default]
9663 src = "src"
9664
9665 [profile.default.vyper]
9666 opt_level = "s"
9667 path = "/opt/vyper/bin/vyper"
9668 experimental_codegen = false
9669 debug = true
9670 enable_decimals = true
9671 venom = { disable_sccp = true, disable_mem2var = false }
9672 "#,
9673 )?;
9674
9675 let cfg = Config::load().unwrap();
9676 let vyper_warnings: Vec<_> = cfg
9678 .warnings
9679 .iter()
9680 .filter(|w| {
9681 matches!(
9682 w,
9683 crate::Warning::UnknownSectionKey { section, .. } if section == "vyper"
9684 )
9685 })
9686 .collect();
9687
9688 assert!(
9689 vyper_warnings.is_empty(),
9690 "Valid nested vyper keys should not trigger warnings, got: {vyper_warnings:?}"
9691 );
9692
9693 Ok(())
9694 });
9695 }
9696
9697 #[test]
9700 fn no_false_warnings_for_inline_vyper_config() {
9701 figment::Jail::expect_with(|jail| {
9702 jail.create_file(
9703 "foundry.toml",
9704 r#"
9705 [profile.default]
9706 src = "src"
9707 vyper = { optimize = "gas", debug = true }
9708
9709 [profile.default-venom]
9710 vyper = { opt_level = "O2", experimental_codegen = true, venom = { disable_cse = true } }
9711
9712 [profile.ci-venom]
9713 vyper = { venom_experimental = true, enable_decimals = true }
9714 "#,
9715 )?;
9716
9717 let cfg = Config::load().unwrap();
9718 let vyper_warnings: Vec<_> = cfg
9719 .warnings
9720 .iter()
9721 .filter(|w| {
9722 matches!(
9723 w,
9724 crate::Warning::UnknownSectionKey { section, .. } if section == "vyper"
9725 )
9726 })
9727 .collect();
9728
9729 assert!(
9730 vyper_warnings.is_empty(),
9731 "Valid inline vyper config should not trigger warnings, got: {vyper_warnings:?}"
9732 );
9733
9734 Ok(())
9735 });
9736 }
9737
9738 #[test]
9740 fn warns_on_unknown_vyper_keys() {
9741 figment::Jail::expect_with(|jail| {
9742 jail.create_file(
9743 "foundry.toml",
9744 r#"
9745 [profile.default]
9746 src = "src"
9747
9748 [vyper]
9749 optimize = "gas"
9750 unknown_vyper_option = true
9751 "#,
9752 )?;
9753
9754 let cfg = Config::load().unwrap();
9755 assert!(
9756 cfg.warnings.iter().any(|w| matches!(
9757 w,
9758 crate::Warning::UnknownSectionKey { key, section, .. }
9759 if key == "unknown_vyper_option" && section == "vyper"
9760 )),
9761 "Unknown vyper key should trigger warning, got: {:?}",
9762 cfg.warnings
9763 );
9764
9765 Ok(())
9766 });
9767 }
9768
9769 #[test]
9771 fn succeeds_on_known_profile() {
9772 figment::Jail::expect_with(|jail| {
9773 jail.create_file(
9774 "foundry.toml",
9775 r#"
9776 [profile.default]
9777 src = "src"
9778
9779 [profile.ci]
9780 src = "src"
9781 fuzz = { runs = 10000 }
9782 "#,
9783 )?;
9784
9785 jail.set_env("FOUNDRY_PROFILE", "ci");
9786 let config = Config::load().expect("known profile should work");
9787 assert_eq!(config.profile.as_str(), "ci");
9788 assert_eq!(config.fuzz.runs, 10000);
9789
9790 Ok(())
9791 });
9792 }
9793
9794 #[test]
9797 fn nested_lib_config_falls_back_to_default_profile() {
9798 figment::Jail::expect_with(|jail| {
9799 let lib_path = jail.directory().join("lib/mylib");
9801 std::fs::create_dir_all(&lib_path).unwrap();
9802 jail.create_file(
9803 "lib/mylib/foundry.toml",
9804 r#"
9805 [profile.default]
9806 src = "contracts"
9807 "#,
9808 )?;
9809
9810 jail.set_env("FOUNDRY_PROFILE", "ci");
9812
9813 let config = Config::load_with_root_and_fallback(&lib_path)
9815 .expect("lib config should load with fallback");
9816 assert_eq!(config.profile, Config::DEFAULT_PROFILE);
9817 assert_eq!(config.src.as_os_str(), "contracts");
9818
9819 Ok(())
9820 });
9821 }
9822
9823 #[test]
9825 fn nested_lib_config_uses_profile_if_exists() {
9826 figment::Jail::expect_with(|jail| {
9827 let lib_path = jail.directory().join("lib/mylib");
9829 std::fs::create_dir_all(&lib_path).unwrap();
9830 jail.create_file(
9831 "lib/mylib/foundry.toml",
9832 r#"
9833 [profile.default]
9834 src = "contracts"
9835
9836 [profile.ci]
9837 src = "contracts"
9838 fuzz = { runs = 5000 }
9839 "#,
9840 )?;
9841
9842 jail.set_env("FOUNDRY_PROFILE", "ci");
9844
9845 let config = Config::load_with_root_and_fallback(&lib_path)
9847 .expect("lib config should load with profile");
9848 assert_eq!(config.profile.as_str(), "ci");
9849 assert_eq!(config.fuzz.runs, 5000);
9850
9851 Ok(())
9852 });
9853 }
9854
9855 #[test]
9857 fn succeeds_on_hyphenated_profile_name() {
9858 figment::Jail::expect_with(|jail| {
9859 jail.create_file(
9860 "foundry.toml",
9861 r#"
9862 [profile.default]
9863 src = "src"
9864
9865 [profile.ci-venom]
9866 src = "src"
9867 fuzz = { runs = 7500 }
9868
9869 [profile.default-venom]
9870 src = "src"
9871 fuzz = { runs = 8000 }
9872 "#,
9873 )?;
9874
9875 jail.set_env("FOUNDRY_PROFILE", "ci-venom");
9877 let config = Config::load().expect("hyphenated profile should work");
9878 assert_eq!(config.profile.as_str(), "ci-venom");
9879 assert_eq!(config.fuzz.runs, 7500);
9880
9881 jail.set_env("FOUNDRY_PROFILE", "default-venom");
9883 let config = Config::load().expect("hyphenated profile should work");
9884 assert_eq!(config.profile.as_str(), "default-venom");
9885 assert_eq!(config.fuzz.runs, 8000);
9886
9887 assert!(
9889 config.profiles.iter().any(|p| p.as_str() == "ci-venom"),
9890 "profiles should contain 'ci-venom', got: {:?}",
9891 config.profiles
9892 );
9893 assert!(
9894 config.profiles.iter().any(|p| p.as_str() == "default-venom"),
9895 "profiles should contain 'default-venom', got: {:?}",
9896 config.profiles
9897 );
9898
9899 Ok(())
9900 });
9901 }
9902
9903 #[test]
9904 fn standalone_section_name_can_be_used_as_profile_name() {
9905 figment::Jail::expect_with(|jail| {
9906 jail.create_file(
9907 "foundry.toml",
9908 r#"
9909 [profile.symbolic]
9910 eth-rpc-url = "https://example.com/"
9911 "#,
9912 )?;
9913 jail.set_env("FOUNDRY_PROFILE", "symbolic");
9914
9915 let config = Config::load().unwrap();
9916 assert_eq!(config.profile.as_str(), "symbolic");
9917 assert_eq!(config.eth_rpc_url.as_deref(), Some("https://example.com/"));
9918
9919 Ok(())
9920 });
9921 }
9922
9923 #[test]
9925 fn hyphenated_profile_with_nested_sections() {
9926 figment::Jail::expect_with(|jail| {
9927 jail.create_file(
9928 "foundry.toml",
9929 r#"
9930 [profile.default]
9931 src = "src"
9932
9933 [profile.ci-venom]
9934 src = "src"
9935 optimizer_runs = 500
9936
9937 [profile.ci-venom.fuzz]
9938 runs = 10000
9939 max_test_rejects = 350000
9940
9941 [profile.ci-venom.invariant]
9942 runs = 375
9943 depth = 500
9944 "#,
9945 )?;
9946
9947 jail.set_env("FOUNDRY_PROFILE", "ci-venom");
9948 let config =
9949 Config::load().expect("hyphenated profile with nested sections should work");
9950 assert_eq!(config.profile.as_str(), "ci-venom");
9951 assert_eq!(config.optimizer_runs, Some(500));
9952 assert_eq!(config.fuzz.runs, 10000);
9953 assert_eq!(config.fuzz.max_test_rejects, 350000);
9954 assert_eq!(config.invariant.runs, 375);
9955 assert_eq!(config.invariant.depth, 500);
9956
9957 Ok(())
9958 });
9959 }
9960
9961 #[test]
9962 fn coverage_section_in_profile() {
9963 figment::Jail::expect_with(|jail| {
9964 jail.create_file(
9965 "foundry.toml",
9966 r#"
9967 [profile.default.coverage]
9968 report = ["summary", "lcov"]
9969 lcov_version = "2.2.0"
9970 ir_minimum = true
9971 keep_optimizer = true
9972 report_file = "out/lcov.info"
9973 include_libs = true
9974 exclude_tests = true
9975 skip_files = ["test/**", "src/mocks/**"]
9976 "#,
9977 )?;
9978 let config = Config::load_with_root(jail.directory()).unwrap();
9979 assert_eq!(
9980 config.coverage.report,
9981 vec![CoverageReportKind::Summary, CoverageReportKind::Lcov]
9982 );
9983 assert_eq!(config.coverage.lcov_version, semver::Version::new(2, 2, 0));
9984 assert!(config.coverage.ir_minimum);
9985 assert!(config.coverage.keep_optimizer);
9986 assert_eq!(
9987 config.coverage.report_file.as_deref(),
9988 Some(std::path::Path::new("out/lcov.info"))
9989 );
9990 assert!(config.coverage.include_libs);
9991 assert!(config.coverage.exclude_tests);
9992 assert_eq!(
9993 config.coverage.skip_files,
9994 vec!["test/**".to_string(), "src/mocks/**".to_string()]
9995 );
9996 Ok(())
9997 });
9998 }
9999
10000 #[test]
10001 fn coverage_standalone_section_falls_back_to_default_profile() {
10002 figment::Jail::expect_with(|jail| {
10003 jail.create_file(
10006 "foundry.toml",
10007 r#"
10008 [coverage]
10009 skip_files = ["script/**"]
10010 exclude_tests = true
10011 "#,
10012 )?;
10013 let config = Config::load_with_root(jail.directory()).unwrap();
10014 assert_eq!(config.coverage.skip_files, vec!["script/**".to_string()]);
10015 assert!(config.coverage.exclude_tests);
10016 assert_eq!(config.coverage.report, vec![CoverageReportKind::Summary]);
10018 assert_eq!(config.coverage.lcov_version, semver::Version::new(1, 0, 0));
10019 Ok(())
10020 });
10021 }
10022
10023 #[test]
10024 fn coverage_per_profile_overrides_default() {
10025 figment::Jail::expect_with(|jail| {
10026 jail.create_file(
10027 "foundry.toml",
10028 r#"
10029 [profile.default.coverage]
10030 skip_files = ["script/**"]
10031
10032 [profile.ci.coverage]
10033 skip_files = ["test/**", "lib/**"]
10034 exclude_tests = true
10035 "#,
10036 )?;
10037
10038 let config = Config::load_with_root(jail.directory()).unwrap();
10040 assert_eq!(config.coverage.skip_files, vec!["script/**".to_string()]);
10041 assert!(!config.coverage.exclude_tests);
10042
10043 jail.set_env("FOUNDRY_PROFILE", "ci");
10045 let config = Config::load_with_root(jail.directory()).unwrap();
10046 assert_eq!(
10047 config.coverage.skip_files,
10048 vec!["test/**".to_string(), "lib/**".to_string()]
10049 );
10050 assert!(config.coverage.exclude_tests);
10051 Ok(())
10052 });
10053 }
10054
10055 #[test]
10056 fn coverage_cache_protects_project_paths() {
10057 let directory = tempdir().unwrap();
10058 let root = directory.path().join("coverage");
10059 fs::create_dir(&root).unwrap();
10060 let mut config = Config::with_root(&root);
10061 config.cache_path = "..".into();
10062 assert!(config.coverage_cache_path().is_none());
10063 config.cache_path = "src".into();
10064 assert!(config.coverage_cache_path().is_none());
10065 config.cache_path = "cache".into();
10066 let cache = config.coverage_cache_path().unwrap();
10067 fs::create_dir_all(&cache).unwrap();
10068 fs::write(cache.join("user-data"), "preserve").unwrap();
10069 assert!(config.coverage_cache_path().is_none());
10070 fs::write(cache.join(Config::COVERAGE_CACHE_MARKER), "").unwrap();
10071 assert_eq!(config.coverage_cache_path(), Some(cache));
10072 }
10073
10074 #[cfg(windows)]
10075 #[test]
10076 fn coverage_cache_uses_compiler_paths() {
10077 let directory = tempdir().unwrap();
10078 let mut config = Config::with_root(directory.path());
10079 config.cache_path = "custom-cache".into();
10080 config.out = "custom-out".into();
10081 let cache = config.coverage_cache_path().unwrap();
10082 fs::create_dir_all(&cache).unwrap();
10083 assert_eq!(cache.as_os_str(), canonicalize(&cache).unwrap().as_os_str());
10084 fs::write(cache.join(Config::COVERAGE_CACHE_MARKER), "").unwrap();
10085 assert_eq!(config.coverage_cache_path(), Some(cache));
10086 }
10087
10088 #[cfg(unix)]
10089 #[test]
10090 fn coverage_cache_rejects_symlink_overlap() {
10091 let directory = tempdir().unwrap();
10092 let root = directory.path();
10093 fs::create_dir(root.join("src")).unwrap();
10094 std::os::unix::fs::symlink(root.join("src"), root.join("cache")).unwrap();
10095 let config = Config::with_root(root);
10096 assert!(config.coverage_cache_path().is_none());
10097 }
10098
10099 #[test]
10100 fn toml_root_does_not_override_project_root() {
10101 figment::Jail::expect_with(|jail| {
10102 jail.create_file(
10103 "foundry.toml",
10104 r#"
10105 [profile.default]
10106 root = "/elsewhere"
10107
10108 [profile.ci]
10109 root = "/elsewhere-ci"
10110
10111 [profile.fmt]
10112
10113 [profile.root]
10114
10115 [fmt]
10116 root = "/elsewhere-fmt"
10117
10118 [rpc_endpoints]
10119 root = "https://example.com"
10120 "#,
10121 )?;
10122 let expected = Config::with_root(jail.directory()).root;
10123
10124 let config = Config::load_with_root(jail.directory()).unwrap();
10125 assert_eq!(config.root, expected);
10126 assert!(
10127 config
10128 .warnings
10129 .iter()
10130 .any(|w| matches!(w, crate::Warning::UnknownKey { key, .. } if key == "root"))
10131 );
10132 assert!(config.rpc_endpoints.contains_key("root"));
10133 assert!(config.profiles.contains(&Profile::new("root")));
10134
10135 for profile in ["ci", "fmt"] {
10136 jail.set_env("FOUNDRY_PROFILE", profile);
10137 let config = Config::load_with_root(jail.directory()).unwrap();
10138 assert_eq!(config.root, expected);
10139 }
10140 Ok(())
10141 });
10142 }
10143
10144 #[test]
10145 fn supplied_compiler_project_preserves_artifacts_and_compilation_settings() {
10146 let directory = tempdir().unwrap();
10147 let mut config = Config::with_root(directory.path()).sanitized();
10148 config.solc = Some(SolcReq::Local(config.root.join("missing-solc")));
10149 config.force = true;
10150 config
10151 .additional_compiler_profiles
10152 .push(toml::from_str("name = 'via-ir'\nvia_ir = true").unwrap());
10153 config
10154 .compilation_restrictions
10155 .push(toml::from_str("paths = 'src/**'\nversion = '=0.8.21'\nvia_ir = true").unwrap());
10156 fs::create_dir_all(&config.src).unwrap();
10157 fs::write(config.src.join("Foo.sol"), "pragma solidity ^0.8.0; contract Foo {}").unwrap();
10158 fs::create_dir_all(&config.out).unwrap();
10159 fs::create_dir_all(&config.cache_path).unwrap();
10160 let artifact = config.out.join("Foo.json");
10161 let cache = config.cache_path.join(SOLIDITY_FILES_CACHE_FILENAME);
10162 fs::write(&artifact, "existing artifact").unwrap();
10163 fs::write(&cache, "existing cache").unwrap();
10164
10165 let compiler = MultiCompiler { solc: None, vyper: None };
10166 let project = config.create_project_with_compiler(|| Ok(compiler), true, true).unwrap();
10167
10168 assert!(project.compiler.solc.is_none());
10169 assert!(project.compiler.vyper.is_none());
10170 assert!(project.cached);
10171 assert!(project.no_artifacts);
10172 assert_eq!(project.paths.artifacts, config.out);
10173 assert_eq!(project.settings.solc.via_ir, Some(false));
10174 assert_eq!(project.additional_settings["via-ir"].solc.via_ir, Some(true));
10175 let restriction = &project.restrictions[&config.src.join("Foo.sol")];
10176 assert_eq!(restriction.version, Some("=0.8.21".parse().unwrap()));
10177 assert_eq!(restriction.restrictions.solc.via_ir, Some(true));
10178 assert_eq!(fs::read_to_string(artifact).unwrap(), "existing artifact");
10179 assert_eq!(fs::read_to_string(cache).unwrap(), "existing cache");
10180 }
10181
10182 #[test]
10183 fn restricted_inline_config_only_lowers_limits() {
10184 let base = Config::default();
10185 let change = |edit: fn(&mut Config)| {
10186 let mut inline = base.clone();
10187 edit(&mut inline);
10188 base.restricted_inline_change(&inline)
10189 };
10190 assert_eq!(change(|c| c.fuzz.max_test_rejects = 1), None);
10191 assert_eq!(
10193 change(|c| c.fuzz.max_test_rejects = 0),
10194 Some("raise `fuzz.max_test_rejects`".into())
10195 );
10196 assert_eq!(change(|c| c.fuzz.dictionary.dictionary_weight = 0), None);
10197 assert_eq!(change(|c| c.fuzz.dictionary.max_fuzz_dictionary_values = 1), None);
10198 assert_eq!(
10199 change(|c| c.fuzz.dictionary.max_fuzz_dictionary_values = usize::MAX),
10200 Some("raise `fuzz.dictionary`".into())
10201 );
10202 assert_eq!(
10203 change(|c| c.invariant.dictionary.max_fuzz_dictionary_literals = usize::MAX),
10204 Some("raise `invariant.dictionary`".into())
10205 );
10206 assert_eq!(
10207 change(|c| c.fuzz.fail_on_revert = !c.fuzz.fail_on_revert),
10208 Some("change `fuzz.fail_on_revert`".into())
10209 );
10210 assert_eq!(
10211 change(|c| c.invariant.fail_on_revert = !c.invariant.fail_on_revert),
10212 Some("change `invariant.fail_on_revert`".into())
10213 );
10214 }
10215
10216 #[test]
10217 fn linked_library_policy_settings() {
10218 figment::Jail::expect_with(|jail| {
10219 jail.create_file(
10220 "foundry.toml",
10221 r#"
10222 [profile.default]
10223 libraries = ["src/Lib.sol:Lib:0x0000000000000000000000000000000000000001"]
10224 [profile.ci]
10225 allow_linked_libraries = false
10226 "#,
10227 )?;
10228 let config = Config::load_with_root(jail.directory()).unwrap();
10229 assert!(config.allow_linked_libraries);
10230 assert!(!config.solc_settings().unwrap().settings.libraries.libs.is_empty());
10231
10232 jail.set_env("FOUNDRY_PROFILE", "ci");
10233 let config = Config::load_with_root(jail.directory()).unwrap();
10234 assert!(!config.allow_linked_libraries);
10235 assert!(config.dynamic_test_linking);
10236 assert!(!config.libraries_with_remappings().unwrap().libs.is_empty());
10237 assert!(config.solc_settings().unwrap().settings.libraries.libs.is_empty());
10238 let roundtrip = Config::from_provider(&config).unwrap();
10239 assert!(!roundtrip.allow_linked_libraries);
10240
10241 jail.set_env("FOUNDRY_ALLOW_LINKED_LIBRARIES", "true");
10242 let config = Config::load_with_root(jail.directory()).unwrap();
10243 assert!(config.allow_linked_libraries);
10244 assert!(!config.solc_settings().unwrap().settings.libraries.libs.is_empty());
10245 Ok(())
10246 });
10247 }
10248
10249 #[test]
10250 fn project_root_error_fails_extraction_after_merges() {
10251 let figment = Figment::from(ProjectRootErrorProvider(io::Error::from(
10252 io::ErrorKind::PermissionDenied,
10253 )))
10254 .merge(("eth_rpc_url", "http://localhost:8545"));
10255 let err = Config::from_provider(figment).unwrap_err();
10256 assert_eq!(
10257 err.to_string(),
10258 "failed to extract foundry config:\nfoundry config error: could not determine project root: permission denied\n"
10259 );
10260 }
10261}