Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow users to specify custom contract metadata files #347

Merged
merged 15 commits into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 39 additions & 39 deletions crates/pop-cli/src/commands/call/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const DEFAULT_PAYABLE_VALUE: &str = "0";

#[derive(Args, Clone)]
pub struct CallContractCommand {
/// Path to the contract build directory.
/// Path to the contract build directory or a contract metadata file.
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
#[arg(short = 'p', long)]
path: Option<PathBuf>,
/// The address of the contract to call.
Expand Down Expand Up @@ -119,26 +119,36 @@ impl CallContractCommand {
}

/// Checks if the contract has been built; if not, builds it.
/// If the path is a metadata file, skips the build process
async fn ensure_contract_built(&self, cli: &mut impl Cli) -> Result<()> {
// Check if build exists in the specified "Contract build directory"
if !has_contract_been_built(self.path.as_deref()) {
// Build the contract in release mode
cli.warning("NOTE: contract has not yet been built.")?;
let spinner = spinner();
spinner.start("Building contract in RELEASE mode...");
let result = match build_smart_contract(self.path.as_deref(), true, Verbosity::Quiet) {
Ok(result) => result,
Err(e) => {
return Err(anyhow!(format!(
if let Some(path) = self.path.as_deref() {
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
// Check if is a directory, if is a file, skip the build process
if path.is_dir() {
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
// Check if build exists in the specified "Contract build directory"
if !has_contract_been_built(self.path.as_deref()) {
// Build the contract in release mode
cli.warning("NOTE: contract has not yet been built.")?;
let spinner = spinner();
spinner.start("Building contract in RELEASE mode...");
let result = match build_smart_contract(
self.path.as_deref(),
true,
Verbosity::Quiet,
) {
Ok(result) => result,
Err(e) => {
return Err(anyhow!(format!(
"🚫 An error occurred building your contract: {}\nUse `pop build` to retry with build output.",
e.to_string()
)));
},
};
spinner.stop(format!(
"Your contract artifacts are ready. You can find them in: {}",
result.target_directory.display()
));
},
};
spinner.stop(format!(
"Your contract artifacts are ready. You can find them in: {}",
result.target_directory.display()
));
}
}
}
Ok(())
}
Expand All @@ -156,25 +166,15 @@ impl CallContractCommand {
}

// Resolve path.
let contract_path = match self.path.as_ref() {
None => {
let path = Some(PathBuf::from("./"));
if has_contract_been_built(path.as_deref()) {
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
self.path = path;
} else {
// Prompt for path.
let input_path: String = cli
.input("Where is your project located?")
.placeholder("./")
.default_input("./")
.interact()?;
self.path = Some(PathBuf::from(input_path));
}

self.path.as_ref().unwrap()
},
Some(p) => p,
};
let contract_path = self.path.get_or_insert_with(|| {
let input_path: String = cli
.input("Where is your project or metadata file located?")
.placeholder("./")
.default_input("./")
.interact()
.unwrap();
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
PathBuf::from(input_path)
});

// Parse the contract metadata provided. If there is an error, do not prompt for more.
let messages = match get_messages(contract_path) {
Expand Down Expand Up @@ -608,7 +608,7 @@ mod tests {
"wss://rpc1.paseo.popnetwork.xyz".into(),
)
.expect_input(
"Where is your project located?",
"Where is your project or metadata file located?",
temp_dir.path().join("testing").display().to_string(),
).expect_info(format!(
"pop call contract --path {} --contract 15XausWjFLBBFLDXUSBRfSfZk25warm4wZRV4ZxhZbfvjrJm --message get --url wss://rpc1.paseo.popnetwork.xyz/ --suri //Alice",
Expand Down Expand Up @@ -694,7 +694,7 @@ mod tests {
"wss://rpc1.paseo.popnetwork.xyz".into(),
)
.expect_input(
"Where is your project located?",
"Where is your project or metadata file located?",
temp_dir.path().join("testing").display().to_string(),
).expect_info(format!(
"pop call contract --path {} --contract 15XausWjFLBBFLDXUSBRfSfZk25warm4wZRV4ZxhZbfvjrJm --message specific_flip --args \"true\", \"2\" --value 50 --url wss://rpc1.paseo.popnetwork.xyz/ --suri //Alice --execute",
Expand Down Expand Up @@ -779,7 +779,7 @@ mod tests {
"wss://rpc1.paseo.popnetwork.xyz".into(),
)
.expect_input(
"Where is your project located?",
"Where is your project or metadata file located?",
temp_dir.path().join("testing").display().to_string(),
).expect_info(format!(
"pop call contract --path {} --contract 15XausWjFLBBFLDXUSBRfSfZk25warm4wZRV4ZxhZbfvjrJm --message specific_flip --args \"true\", \"2\" --value 50 --url wss://rpc1.paseo.popnetwork.xyz/ --suri //Alice --execute",
Expand Down
53 changes: 34 additions & 19 deletions crates/pop-contracts/src/utils/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,15 @@ pub enum FunctionType {
/// Extracts a list of smart contract messages parsing the metadata file.
///
/// # Arguments
/// * `path` - Location path of the project.
/// * `path` - Location path of the project or contract metadata file.
pub fn get_messages(path: &Path) -> Result<Vec<ContractFunction>, Error> {
let cargo_toml_path = match path.ends_with("Cargo.toml") {
true => path.to_path_buf(),
false => path.join("Cargo.toml"),
let contract_artifacts = if path.is_dir() || path.ends_with("Cargo.toml") {
let cargo_toml_path =
if path.ends_with("Cargo.toml") { path.to_path_buf() } else { path.join("Cargo.toml") };
ContractArtifacts::from_manifest_or_file(Some(&cargo_toml_path), None)?
} else {
ContractArtifacts::from_manifest_or_file(None, Some(&path.to_path_buf()))?
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
};
let contract_artifacts =
ContractArtifacts::from_manifest_or_file(Some(&cargo_toml_path), None)?;
let transcoder = contract_artifacts.contract_transcoder()?;
let metadata = transcoder.metadata();
Ok(metadata
Expand Down Expand Up @@ -336,25 +337,39 @@ mod tests {
fn get_messages_work() -> Result<()> {
let temp_dir = new_environment("testing")?;
let current_dir = env::current_dir().expect("Failed to get current directory");

// Helper function to avoid duplicated code
fn assert_contract_metadata_parsed(message: Vec<ContractFunction>) -> Result<()> {
assert_eq!(message.len(), 3);
assert_eq!(message[0].label, "flip");
assert_eq!(message[0].docs, " A message that can be called on instantiated contracts. This one flips the value of the stored `bool` from `true` to `false` and vice versa.");
assert_eq!(message[1].label, "get");
assert_eq!(message[1].docs, " Simply returns the current value of our `bool`.");
assert_eq!(message[2].label, "specific_flip");
assert_eq!(message[2].docs, " A message for testing, flips the value of the stored `bool` with `new_value` and is payable");
// assert parsed arguments
assert_eq!(message[2].args.len(), 2);
assert_eq!(message[2].args[0].label, "new_value".to_string());
assert_eq!(message[2].args[0].type_name, "bool".to_string());
assert_eq!(message[2].args[1].label, "number".to_string());
assert_eq!(message[2].args[1].type_name, "Option<u32>: None, Some(u32)".to_string());
Ok(())
}

mock_build_process(
temp_dir.path().join("testing"),
current_dir.join("./tests/files/testing.contract"),
current_dir.join("./tests/files/testing.json"),
)?;

// Test with a directory path
let message = get_messages(&temp_dir.path().join("testing"))?;
assert_eq!(message.len(), 3);
assert_eq!(message[0].label, "flip");
assert_eq!(message[0].docs, " A message that can be called on instantiated contracts. This one flips the value of the stored `bool` from `true` to `false` and vice versa.");
assert_eq!(message[1].label, "get");
assert_eq!(message[1].docs, " Simply returns the current value of our `bool`.");
assert_eq!(message[2].label, "specific_flip");
assert_eq!(message[2].docs, " A message for testing, flips the value of the stored `bool` with `new_value` and is payable");
// assert parsed arguments
assert_eq!(message[2].args.len(), 2);
assert_eq!(message[2].args[0].label, "new_value".to_string());
assert_eq!(message[2].args[0].type_name, "bool".to_string());
assert_eq!(message[2].args[1].label, "number".to_string());
assert_eq!(message[2].args[1].type_name, "Option<u32>: None, Some(u32)".to_string());
assert_contract_metadata_parsed(message)?;

// Test with a metadata file path
let message = get_messages(&current_dir.join("./tests/files/testing.contract"))?;
assert_contract_metadata_parsed(message)?;

Ok(())
}

Expand Down