pop_contracts/utils/
mod.rs

1// SPDX-License-Identifier: GPL-3.0
2
3use crate::{errors::Error, Bytes, DefaultEnvironment, Environment};
4use std::{
5	path::{Path, PathBuf},
6	str::FromStr,
7};
8#[cfg(feature = "v5")]
9use {
10	contract_build::{util::decode_hex, ManifestPath},
11	contract_extrinsics::BalanceVariant,
12};
13#[cfg(feature = "v6")]
14use {
15	contract_build_inkv6::{util::decode_hex, ManifestPath},
16	contract_extrinsics_inkv6::BalanceVariant,
17};
18
19/// Module for account mapping functionality.
20#[cfg(feature = "v6")]
21pub mod map_account;
22pub mod metadata;
23
24/// Retrieves the manifest path for a contract project.
25///
26/// # Arguments
27/// * `path` - An optional path to the project directory.
28pub fn get_manifest_path(path: Option<&Path>) -> Result<ManifestPath, Error> {
29	if let Some(path) = path {
30		let full_path = PathBuf::from(path.to_string_lossy().to_string() + "/Cargo.toml");
31		ManifestPath::try_from(Some(full_path))
32			.map_err(|e| Error::ManifestPath(format!("Failed to get manifest path: {}", e)))
33	} else {
34		ManifestPath::try_from(path.as_ref())
35			.map_err(|e| Error::ManifestPath(format!("Failed to get manifest path: {}", e)))
36	}
37}
38
39/// Parses a balance value from a string representation.
40///
41/// # Arguments
42/// * `balance` - A string representing the balance value to parse.
43pub fn parse_balance(
44	balance: &str,
45) -> Result<BalanceVariant<<DefaultEnvironment as Environment>::Balance>, Error> {
46	BalanceVariant::from_str(balance).map_err(|e| Error::BalanceParsing(format!("{}", e)))
47}
48
49/// Parse hex encoded bytes.
50///
51/// # Arguments
52/// * `input` - A string containing hex-encoded bytes.
53pub fn parse_hex_bytes(input: &str) -> Result<Bytes, Error> {
54	let bytes = decode_hex(input).map_err(|e| Error::HexParsing(format!("{}", e)))?;
55	Ok(bytes.into())
56}
57
58/// Canonicalizes the given path to ensure consistency and resolve any symbolic links.
59///
60/// # Arguments
61/// * `target` - A reference to the `Path` to be canonicalized.
62pub fn canonicalized_path(target: &Path) -> Result<PathBuf, Error> {
63	// Canonicalize the target path to ensure consistency and resolve any symbolic links.
64	target
65		.canonicalize()
66		// If an I/O error occurs during canonicalization, convert it into an Error enum variant.
67		.map_err(Error::IO)
68}
69
70#[cfg(test)]
71mod tests {
72	use super::*;
73	use anyhow::Result;
74	use std::fs;
75
76	fn setup_test_environment() -> Result<tempfile::TempDir, Error> {
77		let temp_dir = tempfile::tempdir().expect("Could not create temp dir");
78		let temp_contract_dir = temp_dir.path().join("test_contract");
79		fs::create_dir(&temp_contract_dir)?;
80		crate::create_smart_contract(
81			"test_contract",
82			temp_contract_dir.as_path(),
83			&crate::Contract::Standard,
84		)?;
85		Ok(temp_dir)
86	}
87
88	#[test]
89	fn test_get_manifest_path() -> Result<(), Error> {
90		let temp_dir = setup_test_environment()?;
91		get_manifest_path(Some(&temp_dir.path().join("test_contract")))?;
92		Ok(())
93	}
94
95	#[test]
96	fn test_canonicalized_path() -> Result<(), Error> {
97		let temp_dir = tempfile::tempdir()?;
98		// Error case
99		let error_directory = canonicalized_path(&temp_dir.path().join("my_directory"));
100		assert!(error_directory.is_err());
101		// Success case
102		canonicalized_path(temp_dir.path())?;
103		Ok(())
104	}
105
106	#[test]
107	fn parse_balance_works() -> Result<(), Error> {
108		let balance = parse_balance("100000")?;
109		assert_eq!(balance, BalanceVariant::Default(100000));
110		Ok(())
111	}
112
113	#[test]
114	fn parse_balance_fails_wrong_balance() -> Result<(), Error> {
115		assert!(matches!(parse_balance("wrongbalance"), Err(super::Error::BalanceParsing(..))));
116		Ok(())
117	}
118
119	#[test]
120	fn parse_hex_bytes_works() -> Result<(), Error> {
121		let input_in_hex = "48656c6c6f";
122		let result = parse_hex_bytes(input_in_hex)?;
123		assert_eq!(result, Bytes(vec![72, 101, 108, 108, 111]));
124		Ok(())
125	}
126
127	#[test]
128	fn parse_hex_bytes_fails_wrong_input() -> Result<()> {
129		assert!(matches!(parse_hex_bytes("wronghexvalue"), Err(Error::HexParsing(..))));
130		Ok(())
131	}
132}