From 434b49d982670037bc0bb725006c693c44f8900b Mon Sep 17 00:00:00 2001 From: Matthias Seitz Date: Fri, 1 Oct 2021 15:36:38 +0200 Subject: [PATCH] chore: add artifact convenience read and change contracts fn (#72) --- dapp/src/artifacts.rs | 29 +++++++++++++++++++---------- dapp/src/multi_runner.rs | 3 +-- 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/dapp/src/artifacts.rs b/dapp/src/artifacts.rs index 2c0b7ffbf..0c84eed57 100644 --- a/dapp/src/artifacts.rs +++ b/dapp/src/artifacts.rs @@ -1,11 +1,14 @@ use ethers::core::{types::Bytes, utils::CompiledContract}; use eyre::Result; use serde::{Deserialize, Serialize}; -use std::collections::HashMap; +use std::{ + collections::{BTreeMap, HashMap}, + path::Path, +}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DapptoolsArtifact { - contracts: HashMap>, + contracts: BTreeMap>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -40,11 +43,18 @@ where } impl DapptoolsArtifact { - pub fn contracts(&self) -> Result> { - let mut map = HashMap::new(); - for (key, value) in &self.contracts { - for (contract, data) in value.iter() { - let data: Contract = serde_json::from_value(data.clone())?; + /// Convenience function to read from a file + pub fn read(file: impl AsRef) -> Result { + let file = std::fs::File::open(file)?; + Ok(serde_json::from_reader::<_, _>(file)?) + } + + /// Returns all the contract from the artifacts + pub fn into_contracts(self) -> Result> { + let mut map = HashMap::with_capacity(self.contracts.len()); + for (key, value) in self.contracts { + for (contract, data) in value { + let data: Contract = serde_json::from_value(data)?; let data = CompiledContract { abi: data.abi, bytecode: data.evm.bytecode.object, @@ -65,9 +75,8 @@ mod tests { #[test] fn parses_dapptools_artifact() { let path = std::fs::canonicalize("testdata/dapp-artifact.json").unwrap(); - let file = std::fs::File::open(path).unwrap(); - let data = serde_json::from_reader::<_, DapptoolsArtifact>(file).unwrap(); - let contracts = data.contracts().unwrap(); + let data = DapptoolsArtifact::read(path).unwrap(); + let contracts = data.into_contracts().unwrap(); let mut expected = [ "src/test/Greeter.t.sol:Greet", "lib/ds-test/src/test.sol:DSTest", diff --git a/dapp/src/multi_runner.rs b/dapp/src/multi_runner.rs index 22c35f763..9cb591326 100644 --- a/dapp/src/multi_runner.rs +++ b/dapp/src/multi_runner.rs @@ -40,8 +40,7 @@ impl<'a> MultiContractRunnerBuilder<'a> { // 2. parallel compilation // 3. Hardhat / Truffle-style artifacts let contracts = if self.no_compile { - let out_file = std::fs::read_to_string(&self.out_path)?; - serde_json::from_str::(&out_file)?.contracts()? + DapptoolsArtifact::read(self.out_path)?.into_contracts()? } else { SolcBuilder::new(self.contracts, self.remappings, self.libraries)?.build_all()? };