forked from foundry-rs/foundry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
4763 lines (4246 loc) · 158 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Foundry configuration.
#![warn(missing_docs, unused_crate_dependencies)]
#[macro_use]
extern crate tracing;
use crate::cache::StorageCachingConfig;
use alloy_primitives::{address, Address, B256, U256};
use eyre::{ContextCompat, WrapErr};
use figment::{
providers::{Env, Format, Serialized, Toml},
value::{Dict, Map, Value},
Error, Figment, Metadata, Profile, Provider,
};
use foundry_compilers::{
artifacts::{
output_selection::ContractOutputSelection, serde_helpers, BytecodeHash, DebuggingSettings,
Libraries, ModelCheckerSettings, ModelCheckerTarget, Optimizer, OptimizerDetails,
RevertStrings, Settings, SettingsMetadata, Severity,
},
cache::SOLIDITY_FILES_CACHE_FILENAME,
error::SolcError,
remappings::{RelativeRemapping, Remapping},
ConfigurableArtifacts, EvmVersion, Project, ProjectPathsConfig, Solc, SolcConfig,
};
use inflector::Inflector;
use regex::Regex;
use revm_primitives::SpecId;
use semver::Version;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{
borrow::Cow,
collections::HashMap,
fs,
path::{Path, PathBuf},
str::FromStr,
};
// Macros useful for creating a figment.
mod macros;
// Utilities for making it easier to handle tests.
pub mod utils;
pub use crate::utils::*;
mod endpoints;
pub use endpoints::{ResolvedRpcEndpoints, RpcEndpoint, RpcEndpoints};
mod etherscan;
mod resolve;
pub use resolve::UnresolvedEnvVarError;
pub mod cache;
use cache::{Cache, ChainCache};
pub mod fmt;
pub use fmt::FormatterConfig;
pub mod fs_permissions;
pub use crate::fs_permissions::FsPermissions;
pub mod error;
pub use error::SolidityErrorCode;
pub mod doc;
pub use doc::DocConfig;
mod warning;
pub use warning::*;
// helpers for fixing configuration warnings
pub mod fix;
// reexport so cli types can implement `figment::Provider` to easily merge compiler arguments
pub use alloy_chains::{Chain, NamedChain};
pub use figment;
/// config providers
pub mod providers;
use crate::{
error::ExtractConfigError,
etherscan::{EtherscanConfigError, EtherscanConfigs, ResolvedEtherscanConfig},
};
use providers::*;
mod fuzz;
pub use fuzz::{FuzzConfig, FuzzDictionaryConfig};
mod invariant;
use crate::fs_permissions::PathPermission;
pub use invariant::InvariantConfig;
use providers::remappings::RemappingsProvider;
mod inline;
use crate::etherscan::EtherscanEnvProvider;
pub use inline::{validate_profiles, InlineConfig, InlineConfigError, InlineConfigParser, NatSpec};
/// Foundry configuration
///
/// # Defaults
///
/// All configuration values have a default, documented in the [fields](#fields)
/// section below. [`Config::default()`] returns the default values for
/// the default profile while [`Config::with_root()`] returns the values based on the given
/// directory. [`Config::load()`] starts with the default profile and merges various providers into
/// the config, same for [`Config::load_with_root()`], but there the default values are determined
/// by [`Config::with_root()`]
///
/// # Provider Details
///
/// `Config` is a Figment [`Provider`] with the following characteristics:
///
/// * **Profile**
///
/// The profile is set to the value of the `profile` field.
///
/// * **Metadata**
///
/// This provider is named `Foundry Config`. It does not specify a
/// [`Source`](figment::Source) and uses default interpolation.
///
/// * **Data**
///
/// The data emitted by this provider are the keys and values corresponding
/// to the fields and values of the structure. The dictionary is emitted to
/// the "default" meta-profile.
///
/// Note that these behaviors differ from those of [`Config::figment()`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Config {
/// The selected profile. **(default: _default_ `default`)**
///
/// **Note:** This field is never serialized nor deserialized. When a
/// `Config` is merged into a `Figment` as a `Provider`, this profile is
/// selected on the `Figment`. When a `Config` is extracted, this field is
/// set to the extracting Figment's selected `Profile`.
#[serde(skip)]
pub profile: Profile,
/// path of the source contracts dir, like `src` or `contracts`
pub src: PathBuf,
/// path of the test dir
pub test: PathBuf,
/// path of the script dir
pub script: PathBuf,
/// path to where artifacts shut be written to
pub out: PathBuf,
/// all library folders to include, `lib`, `node_modules`
pub libs: Vec<PathBuf>,
/// `Remappings` to use for this repo
pub remappings: Vec<RelativeRemapping>,
/// Whether to autodetect remappings by scanning the `libs` folders recursively
pub auto_detect_remappings: bool,
/// library addresses to link
pub libraries: Vec<String>,
/// whether to enable cache
pub cache: bool,
/// where the cache is stored if enabled
pub cache_path: PathBuf,
/// where the broadcast logs are stored
pub broadcast: PathBuf,
/// additional solc allow paths for `--allow-paths`
pub allow_paths: Vec<PathBuf>,
/// additional solc include paths for `--include-path`
pub include_paths: Vec<PathBuf>,
/// whether to force a `project.clean()`
pub force: bool,
/// evm version to use
#[serde(with = "from_str_lowercase")]
pub evm_version: EvmVersion,
/// list of contracts to report gas of
pub gas_reports: Vec<String>,
/// list of contracts to ignore for gas reports
pub gas_reports_ignore: Vec<String>,
/// The Solc instance to use if any.
///
/// This takes precedence over `auto_detect_solc`, if a version is set then this overrides
/// auto-detection.
///
/// **Note** for backwards compatibility reasons this also accepts solc_version from the toml
/// file, see [`BackwardsCompatProvider`]
pub solc: Option<SolcReq>,
/// whether to autodetect the solc compiler version to use
pub auto_detect_solc: bool,
/// Offline mode, if set, network access (downloading solc) is disallowed.
///
/// Relationship with `auto_detect_solc`:
/// - if `auto_detect_solc = true` and `offline = true`, the required solc version(s) will
/// be auto detected but if the solc version is not installed, it will _not_ try to
/// install it
pub offline: bool,
/// Whether to activate optimizer
pub optimizer: bool,
/// Sets the optimizer runs
pub optimizer_runs: usize,
/// Switch optimizer components on or off in detail.
/// The "enabled" switch above provides two defaults which can be
/// tweaked here. If "details" is given, "enabled" can be omitted.
pub optimizer_details: Option<OptimizerDetails>,
/// Model checker settings.
pub model_checker: Option<ModelCheckerSettings>,
/// verbosity to use
pub verbosity: u8,
/// url of the rpc server that should be used for any rpc calls
pub eth_rpc_url: Option<String>,
/// JWT secret that should be used for any rpc calls
pub eth_rpc_jwt: Option<String>,
/// etherscan API key, or alias for an `EtherscanConfig` in `etherscan` table
pub etherscan_api_key: Option<String>,
/// Multiple etherscan api configs and their aliases
#[serde(default, skip_serializing_if = "EtherscanConfigs::is_empty")]
pub etherscan: EtherscanConfigs,
/// list of solidity error codes to always silence in the compiler output
pub ignored_error_codes: Vec<SolidityErrorCode>,
/// list of file paths to ignore
#[serde(rename = "ignored_warnings_from")]
pub ignored_file_paths: Vec<PathBuf>,
/// When true, compiler warnings are treated as errors
pub deny_warnings: bool,
/// Only run test functions matching the specified regex pattern.
#[serde(rename = "match_test")]
pub test_pattern: Option<RegexWrapper>,
/// Only run test functions that do not match the specified regex pattern.
#[serde(rename = "no_match_test")]
pub test_pattern_inverse: Option<RegexWrapper>,
/// Only run tests in contracts matching the specified regex pattern.
#[serde(rename = "match_contract")]
pub contract_pattern: Option<RegexWrapper>,
/// Only run tests in contracts that do not match the specified regex pattern.
#[serde(rename = "no_match_contract")]
pub contract_pattern_inverse: Option<RegexWrapper>,
/// Only run tests in source files matching the specified glob pattern.
#[serde(rename = "match_path", with = "from_opt_glob")]
pub path_pattern: Option<globset::Glob>,
/// Only run tests in source files that do not match the specified glob pattern.
#[serde(rename = "no_match_path", with = "from_opt_glob")]
pub path_pattern_inverse: Option<globset::Glob>,
/// Configuration for fuzz testing
pub fuzz: FuzzConfig,
/// Configuration for invariant testing
pub invariant: InvariantConfig,
/// Whether to allow ffi cheatcodes in test
pub ffi: bool,
/// Use the create 2 factory in all cases including tests and non-broadcasting scripts.
pub always_use_create_2_factory: bool,
/// Sets a timeout in seconds for vm.prompt cheatcodes
pub prompt_timeout: u64,
/// The address which will be executing all tests
pub sender: Address,
/// The tx.origin value during EVM execution
pub tx_origin: Address,
/// the initial balance of each deployed test contract
pub initial_balance: U256,
/// the block.number value during EVM execution
pub block_number: u64,
/// pins the block number for the state fork
pub fork_block_number: Option<u64>,
/// The chain name or EIP-155 chain ID.
#[serde(rename = "chain_id", alias = "chain")]
pub chain: Option<Chain>,
/// Block gas limit.
pub gas_limit: GasLimit,
/// EIP-170: Contract code size limit in bytes. Useful to increase this because of tests.
pub code_size_limit: Option<usize>,
/// `tx.gasprice` value during EVM execution.
///
/// This is an Option, so we can determine in fork mode whether to use the config's gas price
/// (if set by user) or the remote client's gas price.
pub gas_price: Option<u64>,
/// The base fee in a block.
pub block_base_fee_per_gas: u64,
/// The `block.coinbase` value during EVM execution.
pub block_coinbase: Address,
/// The `block.timestamp` value during EVM execution.
pub block_timestamp: u64,
/// The `block.difficulty` value during EVM execution.
pub block_difficulty: u64,
/// Before merge the `block.max_hash`, after merge it is `block.prevrandao`.
pub block_prevrandao: B256,
/// the `block.gaslimit` value during EVM execution
pub block_gas_limit: Option<GasLimit>,
/// The memory limit per EVM execution in bytes.
/// If this limit is exceeded, a `MemoryLimitOOG` result is thrown.
///
/// The default is 128MiB.
pub memory_limit: u64,
/// Additional output selection for all contracts, such as "ir", "devdoc", "storageLayout",
/// etc.
///
/// See the [Solc Compiler Api](https://docs.soliditylang.org/en/latest/using-the-compiler.html#compiler-api) for more information.
///
/// The following values are always set because they're required by `forge`:
/// ```json
/// {
/// "*": [
/// "abi",
/// "evm.bytecode",
/// "evm.deployedBytecode",
/// "evm.methodIdentifiers"
/// ]
/// }
/// ```
#[serde(default)]
pub extra_output: Vec<ContractOutputSelection>,
/// If set, a separate JSON file will be emitted for every contract depending on the
/// selection, eg. `extra_output_files = ["metadata"]` will create a `metadata.json` for
/// each contract in the project.
///
/// See [Contract Metadata](https://docs.soliditylang.org/en/latest/metadata.html) for more information.
///
/// The difference between `extra_output = ["metadata"]` and
/// `extra_output_files = ["metadata"]` is that the former will include the
/// contract's metadata in the contract's json artifact, whereas the latter will emit the
/// output selection as separate files.
#[serde(default)]
pub extra_output_files: Vec<ContractOutputSelection>,
/// Whether to print the names of the compiled contracts.
pub names: bool,
/// Whether to print the sizes of the compiled contracts.
pub sizes: bool,
/// If set to true, changes compilation pipeline to go through the Yul intermediate
/// representation.
pub via_ir: bool,
/// Whether to include the AST as JSON in the compiler output.
pub ast: bool,
/// RPC storage caching settings determines what chains and endpoints to cache
pub rpc_storage_caching: StorageCachingConfig,
/// Disables storage caching entirely. This overrides any settings made in
/// `rpc_storage_caching`
pub no_storage_caching: bool,
/// Disables rate limiting entirely. This overrides any settings made in
/// `compute_units_per_second`
pub no_rpc_rate_limit: bool,
/// Multiple rpc endpoints and their aliases
#[serde(default, skip_serializing_if = "RpcEndpoints::is_empty")]
pub rpc_endpoints: RpcEndpoints,
/// Whether to store the referenced sources in the metadata as literal data.
pub use_literal_content: bool,
/// Whether to include the metadata hash.
///
/// The metadata hash is machine dependent. By default, this is set to [BytecodeHash::None] to allow for deterministic code, See: <https://docs.soliditylang.org/en/latest/metadata.html>
#[serde(with = "from_str_lowercase")]
pub bytecode_hash: BytecodeHash,
/// Whether to append the metadata hash to the bytecode.
///
/// If this is `false` and the `bytecode_hash` option above is not `None` solc will issue a
/// warning.
pub cbor_metadata: bool,
/// How to treat revert (and require) reason strings.
#[serde(with = "serde_helpers::display_from_str_opt")]
pub revert_strings: Option<RevertStrings>,
/// Whether to compile in sparse mode
///
/// If this option is enabled, only the required contracts/files will be selected to be
/// included in solc's output selection, see also
/// [OutputSelection](foundry_compilers::artifacts::output_selection::OutputSelection)
pub sparse_mode: bool,
/// Generates additional build info json files for every new build, containing the
/// `CompilerInput` and `CompilerOutput`.
pub build_info: bool,
/// The path to the `build-info` directory that contains the build info json files.
pub build_info_path: Option<PathBuf>,
/// Configuration for `forge fmt`
pub fmt: FormatterConfig,
/// Configuration for `forge doc`
pub doc: DocConfig,
/// Configures the permissions of cheat codes that touch the file system.
///
/// This includes what operations can be executed (read, write)
pub fs_permissions: FsPermissions,
/// Temporary config to enable [SpecId::CANCUN]
///
/// <https://github.com/foundry-rs/foundry/issues/5782>
/// Should be removed once EvmVersion Cancun is supported by solc
pub cancun: bool,
/// Whether to enable call isolation.
///
/// Useful for more correct gas accounting and EVM behavior in general.
pub isolate: bool,
/// Whether to disable the block gas limit.
pub disable_block_gas_limit: bool,
/// Address labels
pub labels: HashMap<Address, String>,
/// Whether to enable safety checks for `vm.getCode` and `vm.getDeployedCode` invocations.
/// If disabled, it is possible to access artifacts which were not recompiled or cached.
pub unchecked_cheatcode_artifacts: bool,
/// The root path where the config detection started from, `Config::with_root`
#[doc(hidden)]
// We're skipping serialization here, so it won't be included in the [`Config::to_string()`]
// representation, but will be deserialized from the `Figment` so that forge commands can
// override it.
#[serde(rename = "root", default, skip_serializing)]
pub __root: RootPath,
/// PRIVATE: This structure may grow, As such, constructing this structure should
/// _always_ be done using a public constructor or update syntax:
///
/// ```ignore
/// use foundry_config::Config;
///
/// let config = Config { src: "other".into(), ..Default::default() };
/// ```
#[doc(hidden)]
#[serde(skip)]
pub __non_exhaustive: (),
/// Warnings gathered when loading the Config. See [`WarningsProvider`] for more information
#[serde(default, skip_serializing)]
pub __warnings: Vec<Warning>,
}
/// Mapping of fallback standalone sections. See [`FallbackProfileProvider`]
pub const STANDALONE_FALLBACK_SECTIONS: &[(&str, &str)] = &[("invariant", "fuzz")];
/// Deprecated keys and their replacements.
///
/// See [Warning::DeprecatedKey]
pub const DEPRECATIONS: &[(&str, &str)] = &[("cancun", "evm_version = Cancun")];
impl Config {
/// The default profile: "default"
pub const DEFAULT_PROFILE: Profile = Profile::const_new("default");
/// The hardhat profile: "hardhat"
pub const HARDHAT_PROFILE: Profile = Profile::const_new("hardhat");
/// TOML section for profiles
pub const PROFILE_SECTION: &'static str = "profile";
/// Standalone sections in the config which get integrated into the selected profile
pub const STANDALONE_SECTIONS: &'static [&'static str] =
&["rpc_endpoints", "etherscan", "fmt", "doc", "fuzz", "invariant", "labels"];
/// File name of config toml file
pub const FILE_NAME: &'static str = "foundry.toml";
/// The name of the directory foundry reserves for itself under the user's home directory: `~`
pub const FOUNDRY_DIR_NAME: &'static str = ".foundry";
/// Default address for tx.origin
///
/// `0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38`
pub const DEFAULT_SENDER: Address = address!("1804c8AB1F12E6bbf3894d4083f33e07309d1f38");
/// Returns the current `Config`
///
/// See `Config::figment`
#[track_caller]
pub fn load() -> Self {
Config::from_provider(Config::figment())
}
/// Returns the current `Config`
///
/// See `Config::figment_with_root`
#[track_caller]
pub fn load_with_root(root: impl Into<PathBuf>) -> Self {
Config::from_provider(Config::figment_with_root(root))
}
/// Extract a `Config` from `provider`, panicking if extraction fails.
///
/// # Panics
///
/// If extraction fails, prints an error message indicating the failure and
/// panics. For a version that doesn't panic, use [`Config::try_from()`].
///
/// # Example
///
/// ```no_run
/// use figment::providers::{Env, Format, Toml};
/// use foundry_config::Config;
///
/// // Use foundry's default `Figment`, but allow values from `other.toml`
/// // to supersede its values.
/// let figment = Config::figment().merge(Toml::file("other.toml").nested());
///
/// let config = Config::from_provider(figment);
/// ```
#[track_caller]
pub fn from_provider<T: Provider>(provider: T) -> Self {
trace!("load config with provider: {:?}", provider.metadata());
Self::try_from(provider).unwrap_or_else(|err| panic!("{}", err))
}
/// Attempts to extract a `Config` from `provider`, returning the result.
///
/// # Example
///
/// ```rust
/// use figment::providers::{Env, Format, Toml};
/// use foundry_config::Config;
///
/// // Use foundry's default `Figment`, but allow values from `other.toml`
/// // to supersede its values.
/// let figment = Config::figment().merge(Toml::file("other.toml").nested());
///
/// let config = Config::try_from(figment);
/// ```
pub fn try_from<T: Provider>(provider: T) -> Result<Self, ExtractConfigError> {
let figment = Figment::from(provider);
let mut config = figment.extract::<Self>().map_err(ExtractConfigError::new)?;
config.profile = figment.profile().clone();
Ok(config)
}
/// The config supports relative paths and tracks the root path separately see
/// `Config::with_root`
///
/// This joins all relative paths with the current root and attempts to make them canonic
#[must_use]
pub fn canonic(self) -> Self {
let root = self.__root.0.clone();
self.canonic_at(root)
}
/// Joins all relative paths with the given root so that paths that are defined as:
///
/// ```toml
/// [profile.default]
/// src = "src"
/// out = "./out"
/// libs = ["lib", "/var/lib"]
/// ```
///
/// Will be made canonic with the given root:
///
/// ```toml
/// [profile.default]
/// src = "<root>/src"
/// out = "<root>/out"
/// libs = ["<root>/lib", "/var/lib"]
/// ```
#[must_use]
pub fn canonic_at(mut self, root: impl Into<PathBuf>) -> Self {
let root = canonic(root);
fn p(root: &Path, rem: &Path) -> PathBuf {
canonic(root.join(rem))
}
self.src = p(&root, &self.src);
self.test = p(&root, &self.test);
self.script = p(&root, &self.script);
self.out = p(&root, &self.out);
self.broadcast = p(&root, &self.broadcast);
self.cache_path = p(&root, &self.cache_path);
if let Some(build_info_path) = self.build_info_path {
self.build_info_path = Some(p(&root, &build_info_path));
}
self.libs = self.libs.into_iter().map(|lib| p(&root, &lib)).collect();
self.remappings =
self.remappings.into_iter().map(|r| RelativeRemapping::new(r.into(), &root)).collect();
self.allow_paths = self.allow_paths.into_iter().map(|allow| p(&root, &allow)).collect();
self.include_paths = self.include_paths.into_iter().map(|allow| p(&root, &allow)).collect();
self.fs_permissions.join_all(&root);
if let Some(ref mut model_checker) = self.model_checker {
model_checker.contracts = std::mem::take(&mut model_checker.contracts)
.into_iter()
.map(|(path, contracts)| {
(format!("{}", p(&root, path.as_ref()).display()), contracts)
})
.collect();
}
self
}
/// Normalizes the evm version if a [SolcReq] is set
pub fn normalized_evm_version(mut self) -> Self {
self.normalize_evm_version();
self
}
/// Normalizes the evm version if a [SolcReq] is set to a valid version.
pub fn normalize_evm_version(&mut self) {
self.evm_version = self.get_normalized_evm_version();
}
/// Returns the normalized [EvmVersion] if a [SolcReq] is set to a valid version or if the solc
/// path is a valid solc binary.
///
/// Otherwise it returns the configured [EvmVersion].
pub fn get_normalized_evm_version(&self) -> EvmVersion {
if let Some(version) = self.solc.as_ref().and_then(|solc| solc.try_version().ok()) {
if let Some(evm_version) = self.evm_version.normalize_version(&version) {
return evm_version;
}
}
self.evm_version
}
/// Returns a sanitized version of the Config where are paths are set correctly and potential
/// duplicates are resolved
///
/// See [`Self::canonic`]
#[must_use]
pub fn sanitized(self) -> Self {
let mut config = self.canonic();
config.sanitize_remappings();
config.libs.sort_unstable();
config.libs.dedup();
config
}
/// Cleans up any duplicate `Remapping` and sorts them
///
/// On windows this will convert any `\` in the remapping path into a `/`
pub fn sanitize_remappings(&mut self) {
#[cfg(target_os = "windows")]
{
// force `/` in remappings on windows
use path_slash::PathBufExt;
self.remappings.iter_mut().for_each(|r| {
r.path.path = r.path.path.to_slash_lossy().into_owned().into();
});
}
}
/// Returns the directory in which dependencies should be installed
///
/// Returns the first dir from `libs` that is not `node_modules` or `lib` if `libs` is empty
pub fn install_lib_dir(&self) -> &Path {
self.libs
.iter()
.find(|p| !p.ends_with("node_modules"))
.map(|p| p.as_path())
.unwrap_or_else(|| Path::new("lib"))
}
/// Serves as the entrypoint for obtaining the project.
///
/// Returns the `Project` configured with all `solc` and path related values.
///
/// *Note*: this also _cleans_ [`Project::cleanup`] the workspace if `force` is set to true.
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// let config = Config::load_with_root(".").sanitized();
/// let project = config.project();
/// ```
pub fn project(&self) -> Result<Project, SolcError> {
self.create_project(self.cache, false)
}
/// Same as [`Self::project()`] but sets configures the project to not emit artifacts and ignore
/// cache, caching causes no output until https://github.com/gakonst/ethers-rs/issues/727
pub fn ephemeral_no_artifacts_project(&self) -> Result<Project, SolcError> {
self.create_project(false, true)
}
/// Creates a [Project] with the given `cached` and `no_artifacts` flags
pub fn create_project(&self, cached: bool, no_artifacts: bool) -> Result<Project, SolcError> {
let mut project = Project::builder()
.artifacts(self.configured_artifacts_handler())
.paths(self.project_paths())
.allowed_path(&self.__root.0)
.allowed_paths(&self.libs)
.allowed_paths(&self.allow_paths)
.include_paths(&self.include_paths)
.solc_config(SolcConfig::builder().settings(self.solc_settings()?).build())
.ignore_error_codes(self.ignored_error_codes.iter().copied().map(Into::into))
.ignore_paths(self.ignored_file_paths.clone())
.set_compiler_severity_filter(if self.deny_warnings {
Severity::Warning
} else {
Severity::Error
})
.set_auto_detect(self.is_auto_detect())
.set_offline(self.offline)
.set_cached(cached && !self.build_info)
.set_build_info(!no_artifacts && self.build_info)
.set_no_artifacts(no_artifacts)
.build()?;
if self.force {
project.cleanup()?;
}
if let Some(solc) = self.ensure_solc()? {
project.solc = solc;
}
Ok(project)
}
/// Ensures that the configured version is installed if explicitly set
///
/// If `solc` is [`SolcReq::Version`] then this will download and install the solc version if
/// it's missing, unless the `offline` flag is enabled, in which case an error is thrown.
///
/// If `solc` is [`SolcReq::Local`] then this will ensure that the path exists.
fn ensure_solc(&self) -> Result<Option<Solc>, SolcError> {
if let Some(ref solc) = self.solc {
let solc = match solc {
SolcReq::Version(version) => {
let v = version.to_string();
let mut solc = Solc::find_svm_installed_version(&v)?;
if solc.is_none() {
if self.offline {
return Err(SolcError::msg(format!(
"can't install missing solc {version} in offline mode"
)))
}
Solc::blocking_install(version)?;
solc = Solc::find_svm_installed_version(&v)?;
}
solc
}
SolcReq::Local(solc) => {
if !solc.is_file() {
return Err(SolcError::msg(format!(
"`solc` {} does not exist",
solc.display()
)))
}
Some(Solc::new(solc))
}
};
return Ok(solc)
}
Ok(None)
}
/// Returns the [SpecId] derived from the configured [EvmVersion]
#[inline]
pub fn evm_spec_id(&self) -> SpecId {
if self.cancun {
return SpecId::CANCUN
}
evm_spec_id(&self.evm_version)
}
/// Returns whether the compiler version should be auto-detected
///
/// Returns `false` if `solc_version` is explicitly set, otherwise returns the value of
/// `auto_detect_solc`
pub fn is_auto_detect(&self) -> bool {
if self.solc.is_some() {
return false
}
self.auto_detect_solc
}
/// Whether caching should be enabled for the given chain id
pub fn enable_caching(&self, endpoint: &str, chain_id: impl Into<u64>) -> bool {
!self.no_storage_caching &&
self.rpc_storage_caching.enable_for_chain_id(chain_id.into()) &&
self.rpc_storage_caching.enable_for_endpoint(endpoint)
}
/// Returns the `ProjectPathsConfig` sub set of the config.
///
/// **NOTE**: this uses the paths as they are and does __not__ modify them, see
/// `[Self::sanitized]`
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// let config = Config::load_with_root(".").sanitized();
/// let paths = config.project_paths();
/// ```
pub fn project_paths(&self) -> ProjectPathsConfig {
let mut builder = ProjectPathsConfig::builder()
.cache(self.cache_path.join(SOLIDITY_FILES_CACHE_FILENAME))
.sources(&self.src)
.tests(&self.test)
.scripts(&self.script)
.artifacts(&self.out)
.libs(self.libs.iter())
.remappings(self.get_all_remappings());
if let Some(build_info_path) = &self.build_info_path {
builder = builder.build_infos(build_info_path);
}
builder.build_with_root(&self.__root.0)
}
/// Returns all configured [`Remappings`]
///
/// **Note:** this will add an additional `<src>/=<src path>` remapping here, see
/// [Self::get_source_dir_remapping()]
///
/// So that
///
/// ```solidity
/// import "./math/math.sol";
/// import "contracts/tokens/token.sol";
/// ```
///
/// in `contracts/contract.sol` are resolved to
///
/// ```text
/// contracts/tokens/token.sol
/// contracts/math/math.sol
/// ```
pub fn get_all_remappings(&self) -> impl Iterator<Item = Remapping> + '_ {
self.remappings.iter().map(|m| m.clone().into())
}
/// Returns the configured rpc jwt secret
///
/// Returns:
/// - The jwt secret, if configured
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// # fn t() {
/// let config = Config::with_root("./");
/// let rpc_jwt = config.get_rpc_jwt_secret().unwrap().unwrap();
/// # }
/// ```
pub fn get_rpc_jwt_secret(&self) -> Result<Option<Cow<str>>, UnresolvedEnvVarError> {
Ok(self.eth_rpc_jwt.as_ref().map(|jwt| Cow::Borrowed(jwt.as_str())))
}
/// Returns the configured rpc url
///
/// Returns:
/// - the matching, resolved url of `rpc_endpoints` if `eth_rpc_url` is an alias
/// - the `eth_rpc_url` as-is if it isn't an alias
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// # fn t() {
/// let config = Config::with_root("./");
/// let rpc_url = config.get_rpc_url().unwrap().unwrap();
/// # }
/// ```
pub fn get_rpc_url(&self) -> Option<Result<Cow<str>, UnresolvedEnvVarError>> {
let maybe_alias = self.eth_rpc_url.as_ref().or(self.etherscan_api_key.as_ref())?;
if let Some(alias) = self.get_rpc_url_with_alias(maybe_alias) {
Some(alias)
} else {
Some(Ok(Cow::Borrowed(self.eth_rpc_url.as_deref()?)))
}
}
/// Resolves the given alias to a matching rpc url
///
/// Returns:
/// - the matching, resolved url of `rpc_endpoints` if `maybe_alias` is an alias
/// - None otherwise
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// # fn t() {
/// let config = Config::with_root("./");
/// let rpc_url = config.get_rpc_url_with_alias("mainnet").unwrap().unwrap();
/// # }
/// ```
pub fn get_rpc_url_with_alias(
&self,
maybe_alias: &str,
) -> Option<Result<Cow<str>, UnresolvedEnvVarError>> {
let mut endpoints = self.rpc_endpoints.clone().resolved();
Some(endpoints.remove(maybe_alias)?.map(Cow::Owned))
}
/// Returns the configured rpc, or the fallback url
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// # fn t() {
/// let config = Config::with_root("./");
/// let rpc_url = config.get_rpc_url_or("http://localhost:8545").unwrap();
/// # }
/// ```
pub fn get_rpc_url_or<'a>(
&'a self,
fallback: impl Into<Cow<'a, str>>,
) -> Result<Cow<str>, UnresolvedEnvVarError> {
if let Some(url) = self.get_rpc_url() {
url
} else {
Ok(fallback.into())
}
}
/// Returns the configured rpc or `"http://localhost:8545"` if no `eth_rpc_url` is set
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// # fn t() {
/// let config = Config::with_root("./");
/// let rpc_url = config.get_rpc_url_or_localhost_http().unwrap();
/// # }
/// ```
pub fn get_rpc_url_or_localhost_http(&self) -> Result<Cow<str>, UnresolvedEnvVarError> {
self.get_rpc_url_or("http://localhost:8545")
}
/// Returns the `EtherscanConfig` to use, if any
///
/// Returns
/// - the matching `ResolvedEtherscanConfig` of the `etherscan` table if `etherscan_api_key` is
/// an alias
/// - the matching `ResolvedEtherscanConfig` of the `etherscan` table if a `chain` is
/// configured. an alias
/// - the Mainnet `ResolvedEtherscanConfig` if `etherscan_api_key` is set, `None` otherwise
///
/// # Example
///
/// ```
/// use foundry_config::Config;
/// # fn t() {
/// let config = Config::with_root("./");
/// let etherscan_config = config.get_etherscan_config().unwrap().unwrap();
/// let client = etherscan_config.into_client().unwrap();
/// # }
/// ```
pub fn get_etherscan_config(
&self,
) -> Option<Result<ResolvedEtherscanConfig, EtherscanConfigError>> {
self.get_etherscan_config_with_chain(None).transpose()
}
/// Same as [`Self::get_etherscan_config()`] but optionally updates the config with the given
/// `chain`, and `etherscan_api_key`
///
/// If not matching alias was found, then this will try to find the first entry in the table
/// with a matching chain id. If an etherscan_api_key is already set it will take precedence
/// over the chain's entry in the table.
pub fn get_etherscan_config_with_chain(
&self,
chain: Option<Chain>,
) -> Result<Option<ResolvedEtherscanConfig>, EtherscanConfigError> {
if let Some(maybe_alias) = self.etherscan_api_key.as_ref().or(self.eth_rpc_url.as_ref()) {
if self.etherscan.contains_key(maybe_alias) {
return self.etherscan.clone().resolved().remove(maybe_alias).transpose()
}
}
// try to find by comparing chain IDs after resolving
if let Some(res) = chain
.or(self.chain)
.and_then(|chain| self.etherscan.clone().resolved().find_chain(chain))
{
match (res, self.etherscan_api_key.as_ref()) {
(Ok(mut config), Some(key)) => {
// we update the key, because if an etherscan_api_key is set, it should take
// precedence over the entry, since this is usually set via env var or CLI args.
config.key.clone_from(key);
return Ok(Some(config))
}
(Ok(config), None) => return Ok(Some(config)),
(Err(err), None) => return Err(err),
(Err(_), Some(_)) => {
// use the etherscan key as fallback
}
}
}
// etherscan fallback via API key
if let Some(key) = self.etherscan_api_key.as_ref() {
let chain = chain.or(self.chain).unwrap_or_default();
return Ok(ResolvedEtherscanConfig::create(key, chain))
}
Ok(None)
}
/// Helper function to just get the API key
///
/// Optionally updates the config with the given `chain`.
///
/// See also [Self::get_etherscan_config_with_chain]
pub fn get_etherscan_api_key(&self, chain: Option<Chain>) -> Option<String> {
self.get_etherscan_config_with_chain(chain).ok().flatten().map(|c| c.key)
}