diff --git a/crates/pop-contracts/src/build.rs b/crates/pop-contracts/src/build.rs index 6b7acf17..a8943462 100644 --- a/crates/pop-contracts/src/build.rs +++ b/crates/pop-contracts/src/build.rs @@ -1,65 +1,64 @@ -use thiserror::Error; use contract_build::{execute, ExecuteArgs}; use std::path::PathBuf; +use thiserror::Error; use crate::utils::helpers::get_manifest_path; #[derive(Error, Debug)] pub enum Error { - #[error("Failed to build smart contract: {0}")] - BuildError(String), - #[error("Contract test environment setup failed: {0}")] - SetupError(String), + #[error("Failed to build smart contract: {0}")] + BuildError(String), + #[error("Contract test environment setup failed: {0}")] + SetupError(String), } pub fn build_smart_contract(path: &Option) -> Result { - let manifest_path = match get_manifest_path(path) { - Ok(path) => path, - Err(e) => return Err(Error::BuildError(format!("Failed to get manifest path: {}", e))), - }; + let manifest_path = match get_manifest_path(path) { + Ok(path) => path, + Err(e) => return Err(Error::BuildError(format!("Failed to get manifest path: {}", e))), + }; - let args = ExecuteArgs { manifest_path, ..Default::default() }; - let result = execute(args).map_err(|e| Error::BuildError(format!("{}", e)))?; - let formatted_result = result.display(); - Ok(formatted_result) + let args = ExecuteArgs { manifest_path, ..Default::default() }; + let result = execute(args).map_err(|e| Error::BuildError(format!("{}", e)))?; + let formatted_result = result.display(); + Ok(formatted_result) } - #[cfg(feature = "unit_contract")] #[cfg(test)] mod tests { - use super::*; - use anyhow::Result; - use std::fs; + use super::*; + use anyhow::Result; + use std::fs; - fn setup_test_environment() -> Result { - let temp_dir = tempfile::tempdir()?; - let temp_contract_dir = temp_dir.path().join("test_contract"); - fs::create_dir(&temp_contract_dir)?; - crate::create_smart_contract("test_contract".to_string(), temp_contract_dir.as_path())?; - Ok(temp_dir) - } + fn setup_test_environment() -> Result { + let temp_dir = tempfile::tempdir()?; + let temp_contract_dir = temp_dir.path().join("test_contract"); + fs::create_dir(&temp_contract_dir)?; + crate::create_smart_contract("test_contract".to_string(), temp_contract_dir.as_path())?; + Ok(temp_dir) + } - #[test] - fn test_contract_build() -> Result<()> { - let temp_contract_dir = setup_test_environment()?; - let build = build_smart_contract(&Some(temp_contract_dir.path().join("test_contract")))?; - assert!(build.is_ok(), "Result should be Ok"); + #[test] + fn test_contract_build() -> Result<()> { + let temp_contract_dir = setup_test_environment()?; + let build = build_smart_contract(&Some(temp_contract_dir.path().join("test_contract")))?; + assert!(build.is_ok(), "Result should be Ok"); - assert!(temp_contract_dir.path().join("test_contract/target").exists()); - assert!(temp_contract_dir - .path() - .join("test_contract/target/ink/test_contract.contract") - .exists()); - assert!(temp_contract_dir - .path() - .join("test_contract/target/ink/test_contract.wasm") - .exists()); - assert!(temp_contract_dir - .path() - .join("test_contract/target/ink/test_contract.json") - .exists()); + assert!(temp_contract_dir.path().join("test_contract/target").exists()); + assert!(temp_contract_dir + .path() + .join("test_contract/target/ink/test_contract.contract") + .exists()); + assert!(temp_contract_dir + .path() + .join("test_contract/target/ink/test_contract.wasm") + .exists()); + assert!(temp_contract_dir + .path() + .join("test_contract/target/ink/test_contract.json") + .exists()); - Ok(()) - } + Ok(()) + } } diff --git a/crates/pop-contracts/src/new.rs b/crates/pop-contracts/src/new.rs index 6c3ccda1..05804956 100644 --- a/crates/pop-contracts/src/new.rs +++ b/crates/pop-contracts/src/new.rs @@ -1,65 +1,67 @@ -use thiserror::Error; use contract_build::new_contract_project; use std::path::Path; +use thiserror::Error; #[derive(Error, Debug)] pub enum Error { - #[error("Failed to create new contract project: {0}")] - NewContractError(String), - #[error("IO error: {0}")] - IoError(#[from] std::io::Error), + #[error("Failed to create new contract project: {0}")] + NewContractError(String), + #[error("IO error: {0}")] + IoError(#[from] std::io::Error), } pub fn create_smart_contract(name: String, target: &Path) -> Result<(), Error> { - // Canonicalize the target path to ensure consistency and resolve any symbolic links. - let canonicalized_path = target.canonicalize() - // If an I/O error occurs during canonicalization, convert it into an Error enum variant. - .map_err(|e| Error::IoError(e))?; - - // Retrieve the parent directory of the canonicalized path. - let parent_path = canonicalized_path.parent() - // If the parent directory cannot be retrieved (e.g., if the path has no parent), - // return a NewContractError variant indicating the failure. - .ok_or(Error::NewContractError("Failed to get parent directory".to_string()))?; - - // Create a new contract project with the provided name in the parent directory. - new_contract_project(&name, Some(parent_path)) - // If an error occurs during the creation of the contract project, - // convert it into a NewContractError variant with a formatted error message. - .map_err(|e| Error::NewContractError(format!("{}", e))) + // Canonicalize the target path to ensure consistency and resolve any symbolic links. + let canonicalized_path = target + .canonicalize() + // If an I/O error occurs during canonicalization, convert it into an Error enum variant. + .map_err(|e| Error::IoError(e))?; + + // Retrieve the parent directory of the canonicalized path. + let parent_path = canonicalized_path + .parent() + // If the parent directory cannot be retrieved (e.g., if the path has no parent), + // return a NewContractError variant indicating the failure. + .ok_or(Error::NewContractError("Failed to get parent directory".to_string()))?; + + // Create a new contract project with the provided name in the parent directory. + new_contract_project(&name, Some(parent_path)) + // If an error occurs during the creation of the contract project, + // convert it into a NewContractError variant with a formatted error message. + .map_err(|e| Error::NewContractError(format!("{}", e))) } #[cfg(test)] mod tests { - use super::*; - use std::fs; - use tempfile; + use super::*; use anyhow::{Error, Result}; + use std::fs; + use tempfile; - fn setup_test_environment() -> Result { - let temp_dir = tempfile::tempdir()?; - let temp_contract_dir = temp_dir.path().join("test_contract"); - fs::create_dir(&temp_contract_dir)?; - create_smart_contract("test_contract".to_string(), temp_contract_dir.as_path())?; - Ok(temp_dir) - } + fn setup_test_environment() -> Result { + let temp_dir = tempfile::tempdir()?; + let temp_contract_dir = temp_dir.path().join("test_contract"); + fs::create_dir(&temp_contract_dir)?; + create_smart_contract("test_contract".to_string(), temp_contract_dir.as_path())?; + Ok(temp_dir) + } - #[test] - fn test_create_smart_contract_success() -> Result<(), Error> { - let temp_dir = setup_test_environment()?; + #[test] + fn test_create_smart_contract_success() -> Result<(), Error> { + let temp_dir = setup_test_environment()?; - // Verify that the generated smart contract contains the expected content - let generated_file_content = - fs::read_to_string(temp_dir.path().join("test_contract/lib.rs")) - .expect("Could not read file"); + // Verify that the generated smart contract contains the expected content + let generated_file_content = + fs::read_to_string(temp_dir.path().join("test_contract/lib.rs")) + .expect("Could not read file"); - assert!(generated_file_content.contains("#[ink::contract]")); - assert!(generated_file_content.contains("mod test_contract {")); + assert!(generated_file_content.contains("#[ink::contract]")); + assert!(generated_file_content.contains("mod test_contract {")); - // Verify that the generated Cargo.toml file contains the expected content - fs::read_to_string(temp_dir.path().join("test_contract/Cargo.toml")) - .expect("Could not read file"); + // Verify that the generated Cargo.toml file contains the expected content + fs::read_to_string(temp_dir.path().join("test_contract/Cargo.toml")) + .expect("Could not read file"); - Ok(()) - } + Ok(()) + } } diff --git a/crates/pop-contracts/src/test.rs b/crates/pop-contracts/src/test.rs index 2690bb99..49a4a011 100644 --- a/crates/pop-contracts/src/test.rs +++ b/crates/pop-contracts/src/test.rs @@ -4,64 +4,72 @@ use thiserror::Error; #[derive(Error, Debug)] pub enum Error { - #[error("Failed to execute test command: {0}")] - TestCommandError(String), - #[error("Failed to set test directory: {0}")] - TestDirError(String), - #[error("Failed to create test environment: {0}")] - TestEnvironmentError(String), + #[error("Failed to execute test command: {0}")] + TestCommandError(String), + #[error("Failed to set test directory: {0}")] + TestDirError(String), + #[error("Failed to create test environment: {0}")] + TestEnvironmentError(String), } pub fn test_smart_contract(path: &Option) -> Result<(), Error> { - // Execute `cargo test` command in the specified directory. - let result = cmd("cargo", vec!["test"]) - .dir(path.clone().unwrap_or_else(|| PathBuf::from("./"))) - .run() - .map_err(|e| Error::TestCommandError(format!("Cargo test command failed: {}", e)))?; + // Execute `cargo test` command in the specified directory. + let result = cmd("cargo", vec!["test"]) + .dir(path.clone().unwrap_or_else(|| PathBuf::from("./"))) + .run() + .map_err(|e| Error::TestCommandError(format!("Cargo test command failed: {}", e)))?; - if result.status.success() { - Ok(()) - } else { - Err(Error::TestCommandError("Cargo test command failed.".to_string())) - } + if result.status.success() { + Ok(()) + } else { + Err(Error::TestCommandError("Cargo test command failed.".to_string())) + } } pub fn test_e2e_smart_contract(path: &Option) -> Result<(), Error> { - // Execute `cargo test --features=e2e-tests` command in the specified directory. - let result = cmd("cargo", vec!["test", "--features=e2e-tests"]) - .dir(path.clone().unwrap_or_else(|| PathBuf::from("./"))) - .run() - .map_err(|e| Error::TestCommandError(format!("Cargo test command failed: {}", e)))?; + // Execute `cargo test --features=e2e-tests` command in the specified directory. + let result = cmd("cargo", vec!["test", "--features=e2e-tests"]) + .dir(path.clone().unwrap_or_else(|| PathBuf::from("./"))) + .run() + .map_err(|e| Error::TestCommandError(format!("Cargo test command failed: {}", e)))?; - if result.status.success() { - Ok(()) - } else { - Err(Error::TestCommandError("Cargo test command failed.".to_string())) - } + if result.status.success() { + Ok(()) + } else { + Err(Error::TestCommandError("Cargo test command failed.".to_string())) + } } #[cfg(feature = "unit_contract")] #[cfg(test)] mod tests { - use super::*; - use std::fs; - use tempfile; + use super::*; + use std::fs; + use tempfile; - fn setup_test_environment() -> Result { - let temp_dir = tempfile::tempdir().map_err(|e| Error::TestEnvironmentError(format!("Failed to create temp dir: {}", e)))?; - let temp_contract_dir = temp_dir.path().join("test_contract"); - fs::create_dir(&temp_contract_dir).map_err(|e| Error::TestEnvironmentError(format!("Failed to create test contract directory: {}", e)))?; - let result = crate::create_smart_contract("test_contract".to_string(), temp_contract_dir.as_path()).map_err(|e| Error::TestEnvironmentError(format!("Failed to create smart contract: {}", e)))?; - assert!(result.is_ok(), "Contract test environment setup failed"); - Ok(temp_dir) - } + fn setup_test_environment() -> Result { + let temp_dir = tempfile::tempdir().map_err(|e| { + Error::TestEnvironmentError(format!("Failed to create temp dir: {}", e)) + })?; + let temp_contract_dir = temp_dir.path().join("test_contract"); + fs::create_dir(&temp_contract_dir).map_err(|e| { + Error::TestEnvironmentError(format!("Failed to create test contract directory: {}", e)) + })?; + let result = + crate::create_smart_contract("test_contract".to_string(), temp_contract_dir.as_path()) + .map_err(|e| { + Error::TestEnvironmentError(format!("Failed to create smart contract: {}", e)) + })?; + assert!(result.is_ok(), "Contract test environment setup failed"); + Ok(temp_dir) + } - #[test] - fn test_contract_test() -> Result<(), Error> { - let temp_contract_dir = setup_test_environment()?; - // Run unit tests for the smart contract in the temporary contract directory. - let result = test_smart_contract(&Some(temp_contract_dir.path().join("test_contract")))?; - assert!(result.is_ok(), "Result should be Ok"); - Ok(()) - } + #[test] + fn test_contract_test() -> Result<(), Error> { + let temp_contract_dir = setup_test_environment()?; + // Run unit tests for the smart contract in the temporary contract directory. + let result = test_smart_contract(&Some(temp_contract_dir.path().join("test_contract")))?; + assert!(result.is_ok(), "Result should be Ok"); + Ok(()) + } } diff --git a/crates/pop-contracts/src/utils/helpers.rs b/crates/pop-contracts/src/utils/helpers.rs index 99822745..72b37226 100644 --- a/crates/pop-contracts/src/utils/helpers.rs +++ b/crates/pop-contracts/src/utils/helpers.rs @@ -1,42 +1,40 @@ -use thiserror::Error; use contract_build::ManifestPath; use contract_extrinsics::BalanceVariant; use ink_env::{DefaultEnvironment, Environment}; use std::{path::PathBuf, str::FromStr}; use subxt::{Config, PolkadotConfig as DefaultConfig}; +use thiserror::Error; #[derive(Error, Debug)] pub enum Error { - #[error("Failed to parse balance: {0}")] - BalanceParsingFailed(String), - #[error("Failed to parse account address: {0}")] - AccountAddressParsingFailed(String), + #[error("Failed to parse balance: {0}")] + BalanceParsingFailed(String), + #[error("Failed to parse account address: {0}")] + AccountAddressParsingFailed(String), #[error("Failed to get manifest path: {0}")] - ManifestPathError(String), + ManifestPathError(String), } pub fn get_manifest_path(path: &Option) -> Result { - if let Some(path) = path { - let full_path = PathBuf::from(path.to_string_lossy().to_string() + "/Cargo.toml"); - return ManifestPath::try_from(Some(full_path)).map_err(|e| { - Error::ManifestPathError(format!("Failed to get manifest path: {}", e)) - }); - } else { - return ManifestPath::try_from(path.as_ref()).map_err(|e| { - Error::ManifestPathError(format!("Failed to get manifest path: {}", e)) - }); - } + if let Some(path) = path { + let full_path = PathBuf::from(path.to_string_lossy().to_string() + "/Cargo.toml"); + return ManifestPath::try_from(Some(full_path)) + .map_err(|e| Error::ManifestPathError(format!("Failed to get manifest path: {}", e))); + } else { + return ManifestPath::try_from(path.as_ref()) + .map_err(|e| Error::ManifestPathError(format!("Failed to get manifest path: {}", e))); + } } - -pub fn parse_balance(balance: &str) -> Result::Balance>, Error> { - BalanceVariant::from_str(balance) - .map_err(|e| Error::BalanceParsingFailed(format!("{}", e))) +pub fn parse_balance( + balance: &str, +) -> Result::Balance>, Error> { + BalanceVariant::from_str(balance).map_err(|e| Error::BalanceParsingFailed(format!("{}", e))) } pub fn parse_account(account: &str) -> Result<::AccountId, Error> { - ::AccountId::from_str(account) - .map_err(|e| Error::AccountAddressParsingFailed(format!("{}", e))) + ::AccountId::from_str(account) + .map_err(|e| Error::AccountAddressParsingFailed(format!("{}", e))) } #[cfg(test)] diff --git a/crates/pop-contracts/src/utils/signer.rs b/crates/pop-contracts/src/utils/signer.rs index acc2aca4..1e8cff88 100644 --- a/crates/pop-contracts/src/utils/signer.rs +++ b/crates/pop-contracts/src/utils/signer.rs @@ -1,30 +1,29 @@ -use thiserror::Error; use contract_build::util::decode_hex; use sp_core::Bytes; use subxt_signer::{sr25519::Keypair, SecretUri}; +use thiserror::Error; #[derive(Error, Debug)] pub enum Error { - #[error("Failed to parse secret URI: {0}")] - ParseSecretUriError(String), - #[error("Failed to create keypair from URI: {0}")] - KeyPairCreationError(String), - #[error("Failed to parse hex encoded bytes: {0}")] - HexParsingError(String), + #[error("Failed to parse secret URI: {0}")] + ParseSecretUriError(String), + #[error("Failed to create keypair from URI: {0}")] + KeyPairCreationError(String), + #[error("Failed to parse hex encoded bytes: {0}")] + HexParsingError(String), } /// Create a Signer from a secret URI. pub(crate) fn create_signer(suri: &str) -> Result { - let uri = ::from_str(suri) - .map_err(|e| Error::ParseSecretUriError(format!("{}", e)))?; - let keypair = Keypair::from_uri(&uri) - .map_err(|e| Error::KeyPairCreationError(format!("{}", e)))?; - Ok(keypair) + let uri = ::from_str(suri) + .map_err(|e| Error::ParseSecretUriError(format!("{}", e)))?; + let keypair = + Keypair::from_uri(&uri).map_err(|e| Error::KeyPairCreationError(format!("{}", e)))?; + Ok(keypair) } /// Parse hex encoded bytes. pub fn parse_hex_bytes(input: &str) -> Result { - let bytes = decode_hex(input) - .map_err(|e| Error::HexParsingError(format!("{}", e)))?; - Ok(bytes.into()) + let bytes = decode_hex(input).map_err(|e| Error::HexParsingError(format!("{}", e)))?; + Ok(bytes.into()) } diff --git a/crates/pop-parachains/src/utils/git.rs b/crates/pop-parachains/src/utils/git.rs index 50cd15de..0c239a6b 100644 --- a/crates/pop-parachains/src/utils/git.rs +++ b/crates/pop-parachains/src/utils/git.rs @@ -1,15 +1,15 @@ use anyhow::Result; -use thiserror::Error; use git2::{build::RepoBuilder, FetchOptions, IndexAddOption, Repository, ResetType}; use regex::Regex; use std::fs; use std::path::Path; +use thiserror::Error; use url::Url; #[derive(Error, Debug)] pub enum Error { - #[error("a git error occurred: {0}")] - Git(String), + #[error("a git error occurred: {0}")] + Git(String), } pub struct Git; @@ -96,9 +96,9 @@ impl GitHub { .path_segments() .map(|c| c.collect::>()) .expect("repository must have path segments"); - Ok(path_segments - .get(0) - .ok_or(Error::Git("the organization (or user) is missing from the github url".to_string()))?) + Ok(path_segments.get(0).ok_or(Error::Git( + "the organization (or user) is missing from the github url".to_string(), + ))?) } pub(crate) fn name(repo: &Url) -> Result<&str> { diff --git a/crates/pop-parachains/src/utils/helpers.rs b/crates/pop-parachains/src/utils/helpers.rs index a91aa930..77ddb4d6 100644 --- a/crates/pop-parachains/src/utils/helpers.rs +++ b/crates/pop-parachains/src/utils/helpers.rs @@ -1,59 +1,59 @@ use std::{ - fs::{self, OpenOptions}, - io::{self, stdin, stdout, Write}, - path::Path, + fs::{self, OpenOptions}, + io::{self, stdin, stdout, Write}, + path::Path, }; use thiserror::Error; #[derive(Error, Debug)] pub enum Error { - #[error("User aborted due to existing target folder.")] - Aborted, - #[error("Failed to execute rustfmt")] - RustfmtError(#[from] io::Error), + #[error("User aborted due to existing target folder.")] + Aborted, + #[error("Failed to execute rustfmt")] + RustfmtError(#[from] io::Error), } pub(crate) fn sanitize(target: &Path) -> Result<(), Error> { - if target.exists() { - print!("\"{}\" folder exists. Do you want to clean it? [y/n]: ", target.display()); - stdout().flush()?; - - let mut input = String::new(); - stdin().read_line(&mut input)?; - - if input.trim().to_lowercase() == "y" { - fs::remove_dir_all(target).map_err(|_| Error::Aborted)?; - } else { - return Err(Error::Aborted); - } - } - Ok(()) + if target.exists() { + print!("\"{}\" folder exists. Do you want to clean it? [y/n]: ", target.display()); + stdout().flush()?; + + let mut input = String::new(); + stdin().read_line(&mut input)?; + + if input.trim().to_lowercase() == "y" { + fs::remove_dir_all(target).map_err(|_| Error::Aborted)?; + } else { + return Err(Error::Aborted); + } + } + Ok(()) } pub(crate) fn write_to_file(path: &Path, contents: &str) -> Result<(), Error> { - let mut file = OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(path) - .map_err(|err| Error::RustfmtError(err))?; - - file.write_all(contents.as_bytes()).map_err(|err| Error::RustfmtError(err))?; - - if path.extension().map_or(false, |ext| ext == "rs") { - let output = std::process::Command::new("rustfmt") - .arg(path.to_str().unwrap()) - .output() - .map_err(|err| Error::RustfmtError(err))?; - - if !output.status.success() { - return Err(Error::RustfmtError(io::Error::new( - io::ErrorKind::Other, - "rustfmt exited with non-zero status code", - ))); - } - } - - Ok(()) + let mut file = OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(path) + .map_err(|err| Error::RustfmtError(err))?; + + file.write_all(contents.as_bytes()).map_err(|err| Error::RustfmtError(err))?; + + if path.extension().map_or(false, |ext| ext == "rs") { + let output = std::process::Command::new("rustfmt") + .arg(path.to_str().unwrap()) + .output() + .map_err(|err| Error::RustfmtError(err))?; + + if !output.status.success() { + return Err(Error::RustfmtError(io::Error::new( + io::ErrorKind::Other, + "rustfmt exited with non-zero status code", + ))); + } + } + + Ok(()) } diff --git a/crates/pop-parachains/src/utils/pallet_helpers.rs b/crates/pop-parachains/src/utils/pallet_helpers.rs index ce97a4ab..b2aa4ea1 100644 --- a/crates/pop-parachains/src/utils/pallet_helpers.rs +++ b/crates/pop-parachains/src/utils/pallet_helpers.rs @@ -1,50 +1,50 @@ use std::{ - env::current_dir, - fs, - path::{Path, PathBuf}, - process, + env::current_dir, + fs, + path::{Path, PathBuf}, + process, }; use thiserror::Error; #[derive(Error, Debug)] pub enum ResolvePalletError { - #[error("Failed to access the current directory")] - CurrentDirAccessFailed, - #[error("Failed to locate the workspace")] - WorkspaceLocateFailed, - #[error("Failed to create pallet directory")] - PalletDirCreationFailed, + #[error("Failed to access the current directory")] + CurrentDirAccessFailed, + #[error("Failed to locate the workspace")] + WorkspaceLocateFailed, + #[error("Failed to create pallet directory")] + PalletDirCreationFailed, } /// Resolve pallet path /// For a template it should be `