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 14 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
115 changes: 87 additions & 28 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 artifact.
#[arg(short = 'p', long)]
path: Option<PathBuf>,
/// The address of the contract to call.
Expand Down Expand Up @@ -68,8 +68,6 @@ pub struct CallContractCommand {
impl CallContractCommand {
/// Executes the command.
pub(crate) async fn execute(mut self) -> Result<()> {
// Ensure contract is built.
self.ensure_contract_built(&mut cli::Cli).await?;
// Check if message specified via command line argument.
let prompt_to_repeat_call = self.message.is_none();
// Configure the call based on command line arguments/call UI.
Expand Down Expand Up @@ -119,8 +117,15 @@ impl CallContractCommand {
}

/// Checks if the contract has been built; if not, builds it.
/// If the path is a contract artifact 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"
// The path is expected to be set. If it is not, exit early without attempting to build the contract.
let Some(path) = self.path.as_deref() else { return Ok(()) };
// Check if the path is a file or the build exists in the specified "Contract build
// directory"
if !path.is_dir() || has_contract_been_built(self.path.as_deref()) {
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
return Ok(());
}
if !has_contract_been_built(self.path.as_deref()) {
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
// Build the contract in release mode
cli.warning("NOTE: contract has not yet been built.")?;
Expand Down Expand Up @@ -156,25 +161,21 @@ 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));
}
if self.path.is_none() {
let input_path: String = cli
.input("Where is your project or contract artifact located?")
.placeholder("./")
.default_input("./")
.interact()?;
self.path = Some(PathBuf::from(input_path));
}
let contract_path = self
.path
.as_ref()
.expect("path is guaranteed to be set as input is prompted when None; qed");

self.path.as_ref().unwrap()
},
Some(p) => p,
};
// Ensure contract is built.
self.ensure_contract_built(&mut cli::Cli).await?;

// 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 @@ -208,7 +209,6 @@ impl CallContractCommand {
Ok(_) => Ok(()),
Err(_) => Err("Invalid address."),
})
.default_input("5DYs7UGBm2LuX4ryvyqfksozNAW5V47tPbGiVgnjYWCZ29bt")
.interact()?;
self.contract = Some(contract_address);
};
Expand Down Expand Up @@ -434,7 +434,7 @@ mod tests {
use super::*;
use crate::cli::MockCli;
use pop_contracts::{mock_build_process, new_environment};
use std::env;
use std::{env, fs::write};
use url::Url;

#[tokio::test]
Expand Down Expand Up @@ -508,6 +508,52 @@ mod tests {
cli.verify()
}

#[tokio::test]
async fn call_contract_dry_run_with_artifact_file_works() -> Result<()> {
let mut current_dir = env::current_dir().expect("Failed to get current directory");
current_dir.pop();

let mut cli = MockCli::new()
.expect_intro(&"Call a contract")
.expect_warning("Your call has not been executed.")
.expect_info("Gas limit: Weight { ref_time: 100, proof_size: 10 }");

// From .contract file
let mut call_config = CallContractCommand {
path: Some(current_dir.join("pop-contracts/tests/files/testing.contract")),
contract: Some("15XausWjFLBBFLDXUSBRfSfZk25warm4wZRV4ZxhZbfvjrJm".to_string()),
message: Some("flip".to_string()),
args: vec![].to_vec(),
value: "0".to_string(),
gas_limit: Some(100),
proof_size: Some(10),
url: Url::parse("wss://rpc1.paseo.popnetwork.xyz")?,
suri: "//Alice".to_string(),
dry_run: true,
execute: false,
dev_mode: false,
};
call_config.configure(&mut cli, false).await?;
assert_eq!(call_config.display(), format!(
"pop call contract --path {} --contract 15XausWjFLBBFLDXUSBRfSfZk25warm4wZRV4ZxhZbfvjrJm --message flip --gas 100 --proof_size 10 --url wss://rpc1.paseo.popnetwork.xyz/ --suri //Alice --dry_run",
current_dir.join("pop-contracts/tests/files/testing.contract").display().to_string(),
));
// Contract deployed on Pop Network testnet, test dry-run
call_config.execute_call(&mut cli, false).await?;

// From .json file
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
call_config.path = Some(current_dir.join("pop-contracts/tests/files/testing.json"));
call_config.configure(&mut cli, false).await?;
assert_eq!(call_config.display(), format!(
"pop call contract --path {} --contract 15XausWjFLBBFLDXUSBRfSfZk25warm4wZRV4ZxhZbfvjrJm --message flip --gas 100 --proof_size 10 --url wss://rpc1.paseo.popnetwork.xyz/ --suri //Alice --dry_run",
current_dir.join("pop-contracts/tests/files/testing.json").display().to_string(),
));
// Contract deployed on Pop Network testnet, test dry-run
call_config.execute_call(&mut cli, false).await?;

cli.verify()
}

#[tokio::test]
async fn call_contract_query_duplicate_call_works() -> Result<()> {
let temp_dir = new_environment("testing")?;
Expand Down Expand Up @@ -608,7 +654,7 @@ mod tests {
"wss://rpc1.paseo.popnetwork.xyz".into(),
)
.expect_input(
"Where is your project located?",
"Where is your project or contract artifact 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 +740,7 @@ mod tests {
"wss://rpc1.paseo.popnetwork.xyz".into(),
)
.expect_input(
"Where is your project located?",
"Where is your project or contract artifact 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 +825,7 @@ mod tests {
"wss://rpc1.paseo.popnetwork.xyz".into(),
)
.expect_input(
"Where is your project located?",
"Where is your project or contract artifact 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 @@ -828,6 +874,19 @@ mod tests {
#[tokio::test]
async fn guide_user_to_call_contract_fails_not_build() -> Result<()> {
let temp_dir = new_environment("testing")?;
let mut current_dir = env::current_dir().expect("Failed to get current directory");
current_dir.pop();
// Create invalid `.json` and `.contract` files in the mock build directory and avoid
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
// building the contract.
let invalid_contract_path = temp_dir.path().join("testing.contract");
let invalid_json_path = temp_dir.path().join("testing.json");
write(&invalid_contract_path, b"This is an invalid contract file")?;
write(&invalid_json_path, b"This is an invalid JSON file")?;
mock_build_process(
temp_dir.path().join("testing"),
invalid_contract_path.clone(),
invalid_json_path.clone(),
)?;
let mut cli = MockCli::new();
assert!(matches!(CallContractCommand {
path: Some(temp_dir.path().join("testing")),
Expand All @@ -842,7 +901,7 @@ mod tests {
dry_run: false,
execute: false,
dev_mode: false,
}.configure(&mut cli, false).await, Err(message) if message.to_string().contains("Unable to fetch contract metadata: Failed to find any contract artifacts in target directory.")));
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
}.configure(&mut cli, false).await, Err(message) if message.to_string().contains("Unable to fetch contract metadata")));
cli.verify()
}

Expand Down
10 changes: 7 additions & 3 deletions crates/pop-cli/src/common/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@ pub fn has_contract_been_built(path: Option<&Path>) -> bool {
Ok(manifest) => manifest,
Err(_) => return false,
};
let contract_name = manifest.package().name();
project_path.join("target/ink").exists() &&
project_path.join(format!("target/ink/{}.contract", contract_name)).exists()
if manifest.package.as_ref().is_none() {
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
false
} else {
let contract_name = manifest.package().name();
project_path.join("target/ink").exists() &&
project_path.join(format!("target/ink/{}.contract", contract_name)).exists()
}
}

#[cfg(test)]
Expand Down
44 changes: 38 additions & 6 deletions crates/pop-contracts/src/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{
use anyhow::Context;
use contract_build::Verbosity;
use contract_extrinsics::{
BalanceVariant, CallCommandBuilder, CallExec, DisplayEvents, ErrorVariant,
BalanceVariant, CallCommandBuilder, CallExec, ContractArtifacts, DisplayEvents, ErrorVariant,
ExtrinsicOptsBuilder, TokenMetadata,
};
use ink_env::{DefaultEnvironment, Environment};
Expand Down Expand Up @@ -54,13 +54,25 @@ pub async fn set_up_call(
call_opts: CallOpts,
) -> Result<CallExec<DefaultConfig, DefaultEnvironment, Keypair>, Error> {
let token_metadata = TokenMetadata::query::<DefaultConfig>(&call_opts.url).await?;
let manifest_path = get_manifest_path(call_opts.path.as_deref())?;
let signer = create_signer(&call_opts.suri)?;

let extrinsic_opts = ExtrinsicOptsBuilder::new(signer)
.manifest_path(Some(manifest_path))
.url(call_opts.url.clone())
.done();
let extrinsic_opts = match &call_opts.path {
// If path is a file construct the ExtrinsicOptsBuilder from the file.
Some(path) if path.is_file() => {
let artifacts = ContractArtifacts::from_manifest_or_file(None, Some(path))?;
ExtrinsicOptsBuilder::new(signer)
.file(Some(artifacts.artifact_path()))
.url(call_opts.url.clone())
.done()
},
_ => {
let manifest_path = get_manifest_path(call_opts.path.as_deref())?;
ExtrinsicOptsBuilder::new(signer)
.manifest_path(Some(manifest_path))
.url(call_opts.url.clone())
.done()
},
};

let value: BalanceVariant<<DefaultEnvironment as Environment>::Balance> =
parse_balance(&call_opts.value)?;
Expand Down Expand Up @@ -203,6 +215,26 @@ mod tests {
Ok(())
}

#[tokio::test]
async fn test_set_up_call_from_artifact_file() -> Result<()> {
let current_dir = env::current_dir().expect("Failed to get current directory");
let call_opts = CallOpts {
path: Some(current_dir.join("./tests/files/testing.json")),
contract: "5CLPm1CeUvJhZ8GCDZCR7nWZ2m3XXe4X5MtAQK69zEjut36A".to_string(),
message: "get".to_string(),
args: [].to_vec(),
value: "1000".to_string(),
gas_limit: None,
proof_size: None,
url: Url::parse(CONTRACTS_NETWORK_URL)?,
suri: "//Alice".to_string(),
execute: false,
};
let call = set_up_call(call_opts).await?;
assert_eq!(call.message(), "get");
Ok(())
}

#[tokio::test]
async fn test_set_up_call_error_contract_not_build() -> Result<()> {
let temp_dir = new_environment("testing")?;
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