This repository has been archived by the owner on Oct 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 794
/
Copy pathmod.rs
1806 lines (1615 loc) · 63.6 KB
/
mod.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
//! Solc artifact types
use ethers_core::abi::Abi;
use colored::Colorize;
use md5::Digest;
use semver::{Version, VersionReq};
use std::{
collections::{BTreeMap, HashSet},
fmt, fs,
path::{Path, PathBuf},
str::FromStr,
};
use crate::{
compile::*, error::SolcIoError, remappings::Remapping, utils, ProjectPathsConfig, SolcError,
};
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
use tracing::warn;
pub mod ast;
pub use ast::*;
pub mod bytecode;
pub mod contract;
pub mod output_selection;
pub mod serde_helpers;
use crate::{
artifacts::output_selection::{ContractOutputSelection, OutputSelection},
filter::FilteredSources,
};
pub use bytecode::*;
pub use contract::*;
pub use serde_helpers::{deserialize_bytes, deserialize_opt_bytes};
/// Solidity files are made up of multiple `source units`, a solidity contract is such a `source
/// unit`, therefore a solidity file can contain multiple contracts: (1-N*) relationship.
///
/// This types represents this mapping as `file name -> (contract name -> T)`, where the generic is
/// intended to represent contract specific information, like [`Contract`] itself, See [`Contracts`]
pub type FileToContractsMap<T> = BTreeMap<String, BTreeMap<String, T>>;
/// file -> (contract name -> Contract)
pub type Contracts = FileToContractsMap<Contract>;
/// An ordered list of files and their source
pub type Sources = BTreeMap<PathBuf, Source>;
/// A set of different Solc installations with their version and the sources to be compiled
pub(crate) type VersionedSources = BTreeMap<Solc, (Version, Sources)>;
/// A set of different Solc installations with their version and the sources to be compiled
pub(crate) type VersionedFilteredSources = BTreeMap<Solc, (Version, FilteredSources)>;
const SOLIDITY: &str = "Solidity";
/// Input type `solc` expects
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CompilerInput {
pub language: String,
pub sources: Sources,
pub settings: Settings,
}
impl CompilerInput {
/// Reads all contracts found under the path
pub fn new(path: impl AsRef<Path>) -> Result<Vec<Self>, SolcIoError> {
Source::read_all_from(path.as_ref()).map(Self::with_sources)
}
/// Creates a new [CompilerInput]s with default settings and the given sources
///
/// A [CompilerInput] expects a language setting, supported by solc are solidity or yul.
/// In case the `sources` is a mix of solidity and yul files, 2 CompilerInputs are returned
pub fn with_sources(sources: Sources) -> Vec<Self> {
let mut solidity_sources = BTreeMap::new();
let mut yul_sources = BTreeMap::new();
for (path, source) in sources {
if path.extension() == Some(std::ffi::OsStr::new("yul")) {
yul_sources.insert(path, source);
} else {
solidity_sources.insert(path, source);
}
}
let mut res = Vec::new();
if !solidity_sources.is_empty() {
res.push(Self {
language: SOLIDITY.to_string(),
sources: solidity_sources,
settings: Default::default(),
});
}
if !yul_sources.is_empty() {
res.push(Self {
language: "Yul".to_string(),
sources: yul_sources,
settings: Default::default(),
});
}
res
}
/// This will remove/adjust values in the `CompilerInput` that are not compatible with this
/// version
pub fn sanitized(mut self, version: &Version) -> Self {
static PRE_V0_6_0: once_cell::sync::Lazy<VersionReq> =
once_cell::sync::Lazy::new(|| VersionReq::parse("<0.6.0").unwrap());
static PRE_V0_8_10: once_cell::sync::Lazy<VersionReq> =
once_cell::sync::Lazy::new(|| VersionReq::parse("<0.8.10").unwrap());
if PRE_V0_6_0.matches(version) {
if let Some(ref mut meta) = self.settings.metadata {
// introduced in <https://docs.soliditylang.org/en/v0.6.0/using-the-compiler.html#compiler-api>
// missing in <https://docs.soliditylang.org/en/v0.5.17/using-the-compiler.html#compiler-api>
meta.bytecode_hash.take();
}
// introduced in <https://docs.soliditylang.org/en/v0.6.0/using-the-compiler.html#compiler-api>
let _ = self.settings.debug.take();
}
if PRE_V0_8_10.matches(version) {
if let Some(ref mut debug) = self.settings.debug {
// introduced in <https://docs.soliditylang.org/en/v0.8.10/using-the-compiler.html#compiler-api>
// <https://github.com/ethereum/solidity/releases/tag/v0.8.10>
debug.debug_info.clear();
}
}
self
}
/// Sets the settings for compilation
#[must_use]
pub fn settings(mut self, settings: Settings) -> Self {
self.settings = settings;
self
}
/// Sets the EVM version for compilation
#[must_use]
pub fn evm_version(mut self, version: EvmVersion) -> Self {
self.settings.evm_version = Some(version);
self
}
/// Sets the optimizer runs (default = 200)
#[must_use]
pub fn optimizer(mut self, runs: usize) -> Self {
self.settings.optimizer.runs(runs);
self
}
/// Normalizes the EVM version used in the settings to be up to the latest one
/// supported by the provided compiler version.
#[must_use]
pub fn normalize_evm_version(mut self, version: &Version) -> Self {
if let Some(ref mut evm_version) = self.settings.evm_version {
self.settings.evm_version = evm_version.normalize_version(version);
}
self
}
#[must_use]
pub fn with_remappings(mut self, remappings: Vec<Remapping>) -> Self {
self.settings.remappings = remappings;
self
}
/// Sets the path of the source files to `root` adjoined to the existing path
#[must_use]
pub fn join_path(mut self, root: impl AsRef<Path>) -> Self {
let root = root.as_ref();
self.sources = self.sources.into_iter().map(|(path, s)| (root.join(path), s)).collect();
self
}
/// Removes the `base` path from all source files
pub fn strip_prefix(mut self, base: impl AsRef<Path>) -> Self {
let base = base.as_ref();
self.sources = self
.sources
.into_iter()
.map(|(path, s)| (path.strip_prefix(base).map(|p| p.to_path_buf()).unwrap_or(path), s))
.collect();
self
}
}
/// A `CompilerInput` representation used for verify
///
/// This type is an alternative `CompilerInput` but uses non-alphabetic ordering of the `sources`
/// and instead emits the (Path -> Source) path in the same order as the pairs in the `sources`
/// `Vec`. This is used over a map, so we can determine the order in which etherscan will display
/// the verified contracts
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StandardJsonCompilerInput {
pub language: String,
#[serde(with = "serde_helpers::tuple_vec_map")]
pub sources: Vec<(PathBuf, Source)>,
pub settings: Settings,
}
// === impl StandardJsonCompilerInput ===
impl StandardJsonCompilerInput {
pub fn new(sources: Vec<(PathBuf, Source)>, settings: Settings) -> Self {
Self { language: SOLIDITY.to_string(), sources, settings }
}
/// Normalizes the EVM version used in the settings to be up to the latest one
/// supported by the provided compiler version.
#[must_use]
pub fn normalize_evm_version(mut self, version: &Version) -> Self {
if let Some(ref mut evm_version) = self.settings.evm_version {
self.settings.evm_version = evm_version.normalize_version(version);
}
self
}
}
impl From<StandardJsonCompilerInput> for CompilerInput {
fn from(input: StandardJsonCompilerInput) -> Self {
let StandardJsonCompilerInput { language, sources, settings } = input;
CompilerInput { language, sources: sources.into_iter().collect(), settings }
}
}
impl From<CompilerInput> for StandardJsonCompilerInput {
fn from(input: CompilerInput) -> Self {
let CompilerInput { language, sources, settings } = input;
StandardJsonCompilerInput { language, sources: sources.into_iter().collect(), settings }
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Settings {
/// Stop compilation after the given stage.
/// since 0.8.11: only "parsing" is valid here
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stop_after: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub remappings: Vec<Remapping>,
pub optimizer: Optimizer,
/// Metadata settings
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<SettingsMetadata>,
/// This field can be used to select desired outputs based
/// on file and contract names.
/// If this field is omitted, then the compiler loads and does type
/// checking, but will not generate any outputs apart from errors.
#[serde(default)]
pub output_selection: OutputSelection,
#[serde(
default,
with = "serde_helpers::display_from_str_opt",
skip_serializing_if = "Option::is_none"
)]
pub evm_version: Option<EvmVersion>,
/// Change compilation pipeline to go through the Yul intermediate representation. This is
/// false by default.
#[serde(rename = "viaIR", default, skip_serializing_if = "Option::is_none")]
pub via_ir: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub debug: Option<DebuggingSettings>,
/// Addresses of the libraries. If not all libraries are given here,
/// it can result in unlinked objects whose output data is different.
///
/// The top level key is the name of the source file where the library is used.
/// If remappings are used, this source file should match the global path
/// after remappings were applied.
/// If this key is an empty string, that refers to a global level.
#[serde(default, skip_serializing_if = "Libraries::is_empty")]
pub libraries: Libraries,
}
impl Settings {
/// Creates a new `Settings` instance with the given `output_selection`
pub fn new(output_selection: impl Into<OutputSelection>) -> Self {
Self { output_selection: output_selection.into(), ..Default::default() }
}
/// Inserts a set of `ContractOutputSelection`
pub fn push_all(&mut self, settings: impl IntoIterator<Item = ContractOutputSelection>) {
for value in settings {
self.push_output_selection(value)
}
}
/// Inserts a set of `ContractOutputSelection`
#[must_use]
pub fn with_extra_output(
mut self,
settings: impl IntoIterator<Item = ContractOutputSelection>,
) -> Self {
for value in settings {
self.push_output_selection(value)
}
self
}
/// Inserts the value for all files and contracts
///
/// ```
/// use ethers_solc::artifacts::output_selection::ContractOutputSelection;
/// use ethers_solc::artifacts::Settings;
/// let mut selection = Settings::default();
/// selection.push_output_selection(ContractOutputSelection::Metadata);
/// ```
pub fn push_output_selection(&mut self, value: impl ToString) {
self.push_contract_output_selection("*", value)
}
/// Inserts the `key` `value` pair to the `output_selection` for all files
///
/// If the `key` already exists, then the value is added to the existing list
pub fn push_contract_output_selection(
&mut self,
contracts: impl Into<String>,
value: impl ToString,
) {
let value = value.to_string();
let values = self
.output_selection
.as_mut()
.entry("*".to_string())
.or_default()
.entry(contracts.into())
.or_default();
if !values.contains(&value) {
values.push(value)
}
}
/// Sets the value for all files and contracts
pub fn set_output_selection(&mut self, values: impl IntoIterator<Item = impl ToString>) {
self.set_contract_output_selection("*", values)
}
/// Sets the `key` to the `values` pair to the `output_selection` for all files
///
/// This will replace the existing values for `key` if they're present
pub fn set_contract_output_selection(
&mut self,
key: impl Into<String>,
values: impl IntoIterator<Item = impl ToString>,
) {
self.output_selection
.as_mut()
.entry("*".to_string())
.or_default()
.insert(key.into(), values.into_iter().map(|s| s.to_string()).collect());
}
/// Sets the ``viaIR` valu
#[must_use]
pub fn set_via_ir(mut self, via_ir: bool) -> Self {
self.via_ir = Some(via_ir);
self
}
/// Enables `viaIR`
#[must_use]
pub fn with_via_ir(self) -> Self {
self.set_via_ir(true)
}
/// Adds `ast` to output
#[must_use]
pub fn with_ast(mut self) -> Self {
let output =
self.output_selection.as_mut().entry("*".to_string()).or_insert_with(BTreeMap::default);
output.insert("".to_string(), vec!["ast".to_string()]);
self
}
}
impl Default for Settings {
fn default() -> Self {
Self {
stop_after: None,
optimizer: Default::default(),
metadata: None,
output_selection: OutputSelection::default_output_selection(),
evm_version: Some(EvmVersion::default()),
via_ir: None,
debug: None,
libraries: Default::default(),
remappings: Default::default(),
}
.with_ast()
}
}
/// A wrapper type for all libraries in the form of `<file>:<lib>:<addr>`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(transparent)]
pub struct Libraries {
/// All libraries, `(file path -> (Lib name -> Address))
pub libs: BTreeMap<PathBuf, BTreeMap<String, String>>,
}
// === impl Libraries ===
impl Libraries {
/// Parses all libraries in the form of
/// `<file>:<lib>:<addr>`
///
/// # Example
///
/// ```
/// use ethers_solc::artifacts::Libraries;
/// let libs = Libraries::parse(&[
/// "src/DssSpell.sol:DssExecLib:0xfD88CeE74f7D78697775aBDAE53f9Da1559728E4".to_string(),
/// ])
/// .unwrap();
/// ```
pub fn parse(libs: &[String]) -> Result<Self, SolcError> {
let mut libraries = BTreeMap::default();
for lib in libs {
let mut items = lib.split(':');
let file = items.next().ok_or_else(|| {
SolcError::msg(format!("failed to parse path to library file: {}", lib))
})?;
let lib = items
.next()
.ok_or_else(|| SolcError::msg(format!("failed to parse library name: {}", lib)))?;
let addr = items.next().ok_or_else(|| {
SolcError::msg(format!("failed to parse library address: {}", lib))
})?;
if items.next().is_some() {
return Err(SolcError::msg(format!(
"failed to parse, too many arguments passed: {}",
lib
)))
}
libraries
.entry(file.into())
.or_insert_with(BTreeMap::default)
.insert(lib.to_string(), addr.to_string());
}
Ok(Self { libs: libraries })
}
pub fn is_empty(&self) -> bool {
self.libs.is_empty()
}
pub fn len(&self) -> usize {
self.libs.len()
}
/// Solc expects the lib paths to match the global path after remappings were applied
///
/// See also [ProjectPathsConfig::resolve_import]
pub fn with_applied_remappings(mut self, config: &ProjectPathsConfig) -> Self {
self.libs = self
.libs
.into_iter()
.map(|(file, target)| {
let file = config.resolve_import(&config.root, &file).unwrap_or_else(|err| {
warn!(target: "libs", "Failed to resolve library `{}` for linking: {:?}", file.display(), err);
file
});
(file, target)
})
.collect();
self
}
}
impl From<BTreeMap<PathBuf, BTreeMap<String, String>>> for Libraries {
fn from(libs: BTreeMap<PathBuf, BTreeMap<String, String>>) -> Self {
Self { libs }
}
}
impl AsRef<BTreeMap<PathBuf, BTreeMap<String, String>>> for Libraries {
fn as_ref(&self) -> &BTreeMap<PathBuf, BTreeMap<String, String>> {
&self.libs
}
}
impl AsMut<BTreeMap<PathBuf, BTreeMap<String, String>>> for Libraries {
fn as_mut(&mut self) -> &mut BTreeMap<PathBuf, BTreeMap<String, String>> {
&mut self.libs
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Optimizer {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runs: Option<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.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<OptimizerDetails>,
}
impl Optimizer {
pub fn runs(&mut self, runs: usize) {
self.runs = Some(runs);
}
pub fn disable(&mut self) {
self.enabled.take();
}
pub fn enable(&mut self) {
self.enabled = Some(true)
}
}
impl Default for Optimizer {
fn default() -> Self {
Self { enabled: Some(false), runs: Some(200), details: None }
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct OptimizerDetails {
/// The peephole optimizer is always on if no details are given,
/// use details to switch it off.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub peephole: Option<bool>,
/// The inliner is always on if no details are given,
/// use details to switch it off.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub inliner: Option<bool>,
/// The unused jumpdest remover is always on if no details are given,
/// use details to switch it off.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub jumpdest_remover: Option<bool>,
/// Sometimes re-orders literals in commutative operations.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub order_literals: Option<bool>,
/// Removes duplicate code blocks
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deduplicate: Option<bool>,
/// Common subexpression elimination, this is the most complicated step but
/// can also provide the largest gain.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cse: Option<bool>,
/// Optimize representation of literal numbers and strings in code.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub constant_optimizer: Option<bool>,
/// The new Yul optimizer. Mostly operates on the code of ABI coder v2
/// and inline assembly.
/// It is activated together with the global optimizer setting
/// and can be deactivated here.
/// Before Solidity 0.6.0 it had to be activated through this switch.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub yul: Option<bool>,
/// Tuning options for the Yul optimizer.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub yul_details: Option<YulDetails>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct YulDetails {
/// Improve allocation of stack slots for variables, can free up stack slots early.
/// Activated by default if the Yul optimizer is activated.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stack_allocation: Option<bool>,
/// Select optimization steps to be applied.
/// Optional, the optimizer will use the default sequence if omitted.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub optimizer_steps: Option<String>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum EvmVersion {
Homestead,
TangerineWhistle,
SpuriousDragon,
Byzantium,
Constantinople,
Petersburg,
Istanbul,
Berlin,
London,
}
impl Default for EvmVersion {
fn default() -> Self {
Self::London
}
}
impl EvmVersion {
/// Checks against the given solidity `semver::Version`
pub fn normalize_version(self, version: &Version) -> Option<EvmVersion> {
// the EVM version flag was only added at 0.4.21
// we work our way backwards
if version >= &CONSTANTINOPLE_SOLC {
// If the Solc is at least at london, it supports all EVM versions
Some(if version >= &LONDON_SOLC {
self
// For all other cases, cap at the at-the-time highest possible
// fork
} else if version >= &BERLIN_SOLC && self >= EvmVersion::Berlin {
EvmVersion::Berlin
} else if version >= &ISTANBUL_SOLC && self >= EvmVersion::Istanbul {
EvmVersion::Istanbul
} else if version >= &PETERSBURG_SOLC && self >= EvmVersion::Petersburg {
EvmVersion::Petersburg
} else if self >= EvmVersion::Constantinople {
EvmVersion::Constantinople
} else {
self
})
} else {
None
}
}
}
impl fmt::Display for EvmVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let string = match self {
EvmVersion::Homestead => "homestead",
EvmVersion::TangerineWhistle => "tangerineWhistle",
EvmVersion::SpuriousDragon => "spuriousDragon",
EvmVersion::Constantinople => "constantinople",
EvmVersion::Petersburg => "petersburg",
EvmVersion::Istanbul => "istanbul",
EvmVersion::Berlin => "berlin",
EvmVersion::London => "london",
EvmVersion::Byzantium => "byzantium",
};
write!(f, "{}", string)
}
}
impl FromStr for EvmVersion {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"homestead" => Ok(EvmVersion::Homestead),
"tangerineWhistle" => Ok(EvmVersion::TangerineWhistle),
"spuriousDragon" => Ok(EvmVersion::SpuriousDragon),
"constantinople" => Ok(EvmVersion::Constantinople),
"petersburg" => Ok(EvmVersion::Petersburg),
"istanbul" => Ok(EvmVersion::Istanbul),
"berlin" => Ok(EvmVersion::Berlin),
"london" => Ok(EvmVersion::London),
"byzantium" => Ok(EvmVersion::Byzantium),
s => Err(format!("Unknown evm version: {}", s)),
}
}
}
/// Debugging settings for solc
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DebuggingSettings {
#[serde(
default,
with = "serde_helpers::display_from_str_opt",
skip_serializing_if = "Option::is_none"
)]
pub revert_strings: Option<RevertStrings>,
///How much extra debug information to include in comments in the produced EVM assembly and
/// Yul code.
/// Available components are:
// - `location`: Annotations of the form `@src <index>:<start>:<end>` indicating the location of
// the corresponding element in the original Solidity file, where:
// - `<index>` is the file index matching the `@use-src` annotation,
// - `<start>` is the index of the first byte at that location,
// - `<end>` is the index of the first byte after that location.
// - `snippet`: A single-line code snippet from the location indicated by `@src`. The snippet is
// quoted and follows the corresponding `@src` annotation.
// - `*`: Wildcard value that can be used to request everything.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub debug_info: Vec<String>,
}
/// How to treat revert (and require) reason strings.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum RevertStrings {
/// "default" does not inject compiler-generated revert strings and keeps user-supplied ones.
Default,
/// "strip" removes all revert strings (if possible, i.e. if literals are used) keeping
/// side-effects
Strip,
/// "debug" injects strings for compiler-generated internal reverts, implemented for ABI
/// encoders V1 and V2 for now.
Debug,
/// "verboseDebug" even appends further information to user-supplied revert strings (not yet
/// implemented)
VerboseDebug,
}
impl fmt::Display for RevertStrings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let string = match self {
RevertStrings::Default => "default",
RevertStrings::Strip => "strip",
RevertStrings::Debug => "debug",
RevertStrings::VerboseDebug => "verboseDebug",
};
write!(f, "{}", string)
}
}
impl FromStr for RevertStrings {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"default" => Ok(RevertStrings::Default),
"strip" => Ok(RevertStrings::Strip),
"debug" => Ok(RevertStrings::Debug),
"verboseDebug" | "verbosedebug" => Ok(RevertStrings::VerboseDebug),
s => Err(format!("Unknown evm version: {}", s)),
}
}
}
impl Default for RevertStrings {
fn default() -> Self {
RevertStrings::Default
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SettingsMetadata {
/// Use only literal content and not URLs (false by default)
#[serde(default, rename = "useLiteralContent", skip_serializing_if = "Option::is_none")]
pub use_literal_content: Option<bool>,
/// Use the given hash method for the metadata hash that is appended to the bytecode.
/// The metadata hash can be removed from the bytecode via option "none".
/// The other options are "ipfs" and "bzzr1".
/// If the option is omitted, "ipfs" is used by default.
#[serde(
default,
rename = "bytecodeHash",
skip_serializing_if = "Option::is_none",
with = "serde_helpers::display_from_str_opt"
)]
pub bytecode_hash: Option<BytecodeHash>,
}
impl From<BytecodeHash> for SettingsMetadata {
fn from(hash: BytecodeHash) -> Self {
Self { use_literal_content: None, bytecode_hash: Some(hash) }
}
}
/// Determines the hash method for the metadata hash that is appended to the bytecode.
///
/// Solc's default is `Ipfs`, see <https://docs.soliditylang.org/en/latest/using-the-compiler.html#compiler-api>.
#[derive(Clone, Debug, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BytecodeHash {
Ipfs,
None,
Bzzr1,
}
impl Default for BytecodeHash {
fn default() -> Self {
BytecodeHash::Ipfs
}
}
impl FromStr for BytecodeHash {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"none" => Ok(BytecodeHash::None),
"ipfs" => Ok(BytecodeHash::Ipfs),
"bzzr1" => Ok(BytecodeHash::Bzzr1),
s => Err(format!("Unknown bytecode hash: {}", s)),
}
}
}
impl fmt::Display for BytecodeHash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
BytecodeHash::Ipfs => "ipfs",
BytecodeHash::None => "none",
BytecodeHash::Bzzr1 => "bzzr1",
};
f.write_str(s)
}
}
/// Bindings for [`solc` contract metadata](https://docs.soliditylang.org/en/latest/metadata.html)
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Metadata {
pub compiler: Compiler,
pub language: String,
pub output: Output,
pub settings: MetadataSettings,
pub sources: MetadataSources,
pub version: i64,
}
/// Compiler settings
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MetadataSettings {
/// Required for Solidity: File and name of the contract or library this metadata is created
/// for.
#[serde(default, rename = "compilationTarget")]
pub compilation_target: BTreeMap<String, String>,
#[serde(flatten)]
pub inner: Settings,
}
/// Compilation source files/source units, keys are file names
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct MetadataSources {
#[serde(flatten)]
pub inner: BTreeMap<String, MetadataSource>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MetadataSource {
/// Required: keccak256 hash of the source file
pub keccak256: String,
/// Required (unless "content" is used, see below): Sorted URL(s)
/// to the source file, protocol is more or less arbitrary, but a
/// Swarm URL is recommended
#[serde(default)]
pub urls: Vec<String>,
/// Required (unless "url" is used): literal contents of the source file
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content: Option<String>,
/// Optional: SPDX license identifier as given in the source file
pub license: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Compiler {
pub version: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Output {
pub abi: Vec<SolcAbi>,
pub devdoc: Option<Doc>,
pub userdoc: Option<Doc>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SolcAbi {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub inputs: Vec<Item>,
#[serde(rename = "stateMutability")]
pub state_mutability: Option<String>,
#[serde(rename = "type")]
pub abi_type: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub outputs: Vec<Item>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Item {
#[serde(rename = "internalType")]
pub internal_type: Option<String>,
pub name: String,
#[serde(rename = "type")]
pub put_type: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Doc {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub methods: Option<DocLibraries>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct DocLibraries {
#[serde(flatten)]
pub libs: BTreeMap<String, serde_json::Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct Source {
pub content: String,
}
impl Source {
/// this is a heuristically measured threshold at which we can generally expect a speedup by
/// using rayon's `par_iter`, See `Self::read_all_files`
pub const NUM_READ_PAR: usize = 8;
/// Reads the file content
pub fn read(file: impl AsRef<Path>) -> Result<Self, SolcIoError> {
let file = file.as_ref();
Ok(Self { content: fs::read_to_string(file).map_err(|err| SolcIoError::new(err, file))? })
}
/// Recursively finds all source files under the given dir path and reads them all
pub fn read_all_from(dir: impl AsRef<Path>) -> Result<Sources, SolcIoError> {
Self::read_all_files(utils::source_files(dir))
}
/// Reads all source files of the given vec
///
/// Depending on the len of the vec it will try to read the files in parallel
pub fn read_all_files(files: Vec<PathBuf>) -> Result<Sources, SolcIoError> {
use rayon::prelude::*;
if files.len() < Self::NUM_READ_PAR {
Self::read_all(files)
} else {
files
.par_iter()
.map(Into::into)
.map(|file| Self::read(&file).map(|source| (file, source)))
.collect()
}
}
/// Reads all files
pub fn read_all<T, I>(files: I) -> Result<Sources, SolcIoError>
where
I: IntoIterator<Item = T>,
T: Into<PathBuf>,
{
files
.into_iter()
.map(Into::into)
.map(|file| Self::read(&file).map(|source| (file, source)))
.collect()
}
/// Parallelized version of `Self::read_all` that reads all files using a parallel iterator
///
/// NOTE: this is only expected to be faster than `Self::read_all` if the given iterator
/// contains at least several paths. see also `Self::read_all_files`.
pub fn par_read_all<T, I>(files: I) -> Result<Sources, SolcIoError>
where
I: IntoIterator<Item = T>,
<I as IntoIterator>::IntoIter: Send,
T: Into<PathBuf> + Send,
{
use rayon::{iter::ParallelBridge, prelude::ParallelIterator};
files
.into_iter()
.par_bridge()
.map(Into::into)
.map(|file| Self::read(&file).map(|source| (file, source)))
.collect()
}
/// Generate a non-cryptographically secure checksum of the file's content
pub fn content_hash(&self) -> String {
let mut hasher = md5::Md5::new();
hasher.update(&self.content);
let result = hasher.finalize();
hex::encode(result)
}
/// Returns all import statements of the file
pub fn parse_imports(&self) -> Vec<&str> {
utils::find_import_paths(self.as_ref()).map(|m| m.as_str()).collect()
}
}
#[cfg(feature = "async")]
impl Source {
/// async version of `Self::read`
pub async fn async_read(file: impl AsRef<Path>) -> Result<Self, SolcIoError> {
let file = file.as_ref();
Ok(Self {
content: tokio::fs::read_to_string(file)
.await
.map_err(|err| SolcIoError::new(err, file))?,
})
}
/// Finds all source files under the given dir path and reads them all
pub async fn async_read_all_from(dir: impl AsRef<Path>) -> Result<Sources, SolcIoError> {
Self::async_read_all(utils::source_files(dir.as_ref())).await
}
/// async version of `Self::read_all`
pub async fn async_read_all<T, I>(files: I) -> Result<Sources, SolcIoError>
where
I: IntoIterator<Item = T>,
T: Into<PathBuf>,
{
futures_util::future::join_all(
files
.into_iter()