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: integration openzeppelin evm template #284

Merged
merged 19 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
585 changes: 310 additions & 275 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,7 @@ toml_edit = { version = "0.22", features = ["serde"] }
symlink = "0.1"
serde_json = { version = "1.0", features = ["preserve_order"] }
serde = { version = "1.0", features = ["derive"] }
zombienet-sdk = "0.2.7"
zombienet-support = "0.2.7"
zombienet-sdk = "0.2.14"
git2_credentials = "0.13.0"

# pop-cli
Expand Down
12 changes: 8 additions & 4 deletions crates/pop-cli/src/commands/new/parachain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use cliclack::{
outro, outro_cancel,
};
use pop_common::{
enum_variants,
enum_variants, enum_variants_without_deprecated,
templates::{Template, Type},
Git, GitHub, Release,
};
Expand All @@ -40,8 +40,9 @@ pub struct NewParachainCommand {
#[arg(
short = 't',
long,
help = "Template to use.",
value_parser = enum_variants!(Parachain)
help = format!("Template to use. [possible values: {}]", enum_variants_without_deprecated!(Parachain)),
value_parser = enum_variants!(Parachain),
hide_possible_values = true // Hide the deprecated templates
)]
pub(crate) template: Option<Parachain>,
#[arg(
Expand Down Expand Up @@ -216,7 +217,7 @@ async fn generate_parachain_from_template(
// add next steps
let mut next_steps = vec![
format!("cd into \"{name_template}\" and enjoy hacking! 🚀"),
"Use `pop build` to build your parachain.".into(),
"Use `pop build --release` to build your parachain.".into(),
];
if let Some(network_config) = template.network_config() {
next_steps.push(format!(
Expand Down Expand Up @@ -244,6 +245,9 @@ fn is_template_supported(provider: &Provider, template: &Parachain) -> Result<()
provider, template
)));
};
if template.is_deprecated() {
warning(format!("NOTE: this template is deprecated.{}", template.deprecated_message()))?;
}
Ok(())
}

Expand Down
6 changes: 3 additions & 3 deletions crates/pop-common/src/templates/extractor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use std::{fs, io, path::Path};
/// * `ignore_directories` - A vector of directory names to ignore during the extraction. If empty,
/// no directories are ignored.
pub fn extract_template_files(
template_name: String,
template_name: &str,
repo_directory: &Path,
target_directory: &Path,
ignore_directories: Option<Vec<String>>,
Expand Down Expand Up @@ -72,7 +72,7 @@ mod tests {
// Contract
let mut temp_dir = generate_testing_contract("erc20")?;
let mut output_dir = tempfile::tempdir()?;
extract_template_files("erc20".to_string(), temp_dir.path(), output_dir.path(), None)?;
extract_template_files("erc20", temp_dir.path(), output_dir.path(), None)?;
assert!(output_dir.path().join("lib.rs").exists());
assert!(output_dir.path().join("Cargo.toml").exists());
assert!(output_dir.path().join("frontend").exists());
Expand All @@ -81,7 +81,7 @@ mod tests {
temp_dir = generate_testing_contract("erc721")?;
output_dir = tempfile::tempdir()?;
extract_template_files(
"erc721".to_string(),
"erc721",
temp_dir.path(),
output_dir.path(),
Some(vec!["frontend".to_string()]),
Expand Down
24 changes: 23 additions & 1 deletion crates/pop-common/src/templates/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
use strum::{EnumMessage, EnumProperty, VariantArray};
pub use thiserror::Error;

pub mod extractor;

Check warning on line 6 in crates/pop-common/src/templates/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

missing documentation for a module

warning: missing documentation for a module --> crates/pop-common/src/templates/mod.rs:6:1 | 6 | pub mod extractor; | ^^^^^^^^^^^^^^^^^

#[derive(Error, Debug)]
pub enum Error {

Check warning on line 9 in crates/pop-common/src/templates/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

missing documentation for an enum

warning: missing documentation for an enum --> crates/pop-common/src/templates/mod.rs:9:1 | 9 | pub enum Error { | ^^^^^^^^^^^^^^
#[error("The `Repository` property is missing from the template variant")]
RepositoryMissing,

Check warning on line 11 in crates/pop-common/src/templates/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

missing documentation for a variant

warning: missing documentation for a variant --> crates/pop-common/src/templates/mod.rs:11:2 | 11 | RepositoryMissing, | ^^^^^^^^^^^^^^^^^

#[error("The `TypeMissing` property is missing from the template variant")]
TypeMissing,

Check warning on line 14 in crates/pop-common/src/templates/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

missing documentation for a variant

warning: missing documentation for a variant --> crates/pop-common/src/templates/mod.rs:14:2 | 14 | TypeMissing, | ^^^^^^^^^^^
}

/// A trait for templates. A template is a variant of a template type.
Expand All @@ -19,7 +19,7 @@
Clone + Default + EnumMessage + EnumProperty + Eq + PartialEq + VariantArray
{
// What is the template's type strum property identifier.
const PROPERTY: &'static str = "Type";

Check warning on line 22 in crates/pop-common/src/templates/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

missing documentation for an associated constant

warning: missing documentation for an associated constant --> crates/pop-common/src/templates/mod.rs:22:2 | 22 | const PROPERTY: &'static str = "Type"; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

/// Get the template's name.
fn name(&self) -> &str {
Expand All @@ -45,6 +45,16 @@
fn template_type(&self) -> Result<&str, Error> {
self.get_str(Self::PROPERTY).ok_or(Error::TypeMissing)
}

/// Get whether the template is deprecated.
fn is_deprecated(&self) -> bool {
self.get_str("IsDeprecated").map_or(false, |s| s == "true")
}

/// Get the deprecation message for the template
fn deprecated_message(&self) -> &str {
self.get_str("DeprecatedMessage").unwrap_or_default()
}
}

/// A trait for defining overarching types of specific template variants.
Expand Down Expand Up @@ -76,7 +86,7 @@
fn templates(&self) -> Vec<&T> {
T::VARIANTS
.iter()
.filter(|t| t.get_str(T::PROPERTY) == Some(self.name()))
.filter(|t| t.get_str(T::PROPERTY) == Some(self.name()) && !t.is_deprecated())
.collect()
}

Expand All @@ -88,7 +98,7 @@
}

#[macro_export]
macro_rules! enum_variants {

Check warning on line 101 in crates/pop-common/src/templates/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

missing documentation for a macro

warning: missing documentation for a macro --> crates/pop-common/src/templates/mod.rs:101:1 | 101 | macro_rules! enum_variants { | ^^^^^^^^^^^^^^^^^^^^^^^^^^
($e: ty) => {{
PossibleValuesParser::new(
<$e>::VARIANTS
Expand All @@ -99,3 +109,15 @@
.try_map(|s| <$e>::from_str(&s).map_err(|e| format!("could not convert from {s} to type")))
}};
}

#[macro_export]
macro_rules! enum_variants_without_deprecated {

Check warning on line 114 in crates/pop-common/src/templates/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

missing documentation for a macro

warning: missing documentation for a macro --> crates/pop-common/src/templates/mod.rs:114:1 | 114 | macro_rules! enum_variants_without_deprecated { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
($e:ty) => {{
<$e>::VARIANTS
.iter()
.filter(|variant| !variant.is_deprecated()) // Exclude deprecated variants for --help
.map(|v| v.as_ref())
.collect::<Vec<_>>()
.join(", ")
}};
}
9 changes: 2 additions & 7 deletions crates/pop-contracts/src/new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
create_template_contract(name, canonicalized_path, template)
}

pub fn is_valid_contract_name(name: &str) -> Result<(), Error> {

Check warning on line 30 in crates/pop-contracts/src/new.rs

View workflow job for this annotation

GitHub Actions / clippy

missing documentation for a function

warning: missing documentation for a function --> crates/pop-contracts/src/new.rs:30:1 | 30 | pub fn is_valid_contract_name(name: &str) -> Result<(), Error> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: requested on the command line with `-W missing-docs`
if !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
return Err(Error::InvalidName(
"Contract names can only contain alphanumeric characters and underscores".to_owned(),
Expand Down Expand Up @@ -65,15 +65,10 @@
// Retrieve only the template contract files.
if template == &Contract::PSP22 || template == &Contract::PSP34 {
// Different template structure requires extracting different path
extract_template_files(
String::from(""),
temp_dir.path(),
canonicalized_path.as_path(),
None,
)?;
extract_template_files("", temp_dir.path(), canonicalized_path.as_path(), None)?;
} else {
extract_template_files(
template.to_string(),
template.as_ref(),
temp_dir.path(),
canonicalized_path.as_path(),
Some(vec!["frontend".to_string()]),
Expand Down
1 change: 0 additions & 1 deletion crates/pop-parachains/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ toml_edit.workspace = true
walkdir.workspace = true
# Zombienet
zombienet-sdk.workspace = true
zombienet-support.workspace = true

# Pop
pop-common = { path = "../pop-common", version = "0.3.0" }
Expand Down
42 changes: 41 additions & 1 deletion crates/pop-parachains/src/new_parachain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{
use anyhow::Result;
use pop_common::{
git::Git,
templates::{Template, Type},
templates::{extractor::extract_template_files, Template, Type},
};
use std::{fs, path::Path};
use walkdir::WalkDir;
Expand All @@ -32,6 +32,9 @@ pub fn instantiate_template_dir(
if Provider::Pop.provides(template) {
return instantiate_standard_template(template, target, config, tag_version);
}
if Provider::OpenZeppelin.provides(template) {
return instantiate_openzeppelin_template(template, target, tag_version);
}
let tag = Git::clone_and_degit(template.repository_url()?, target, tag_version)?;
Ok(tag)
}
Expand Down Expand Up @@ -75,6 +78,25 @@ pub fn instantiate_standard_template(
Ok(tag)
}

pub fn instantiate_openzeppelin_template(
template: &Parachain,
target: &Path,
tag_version: Option<String>,
) -> Result<Option<String>> {
let temp_dir = ::tempfile::TempDir::new_in(std::env::temp_dir())?;
let source = temp_dir.path();

let tag = Git::clone_and_degit(template.repository_url()?, source, tag_version)?;
AlexD10S marked this conversation as resolved.
Show resolved Hide resolved
let mut template_name = template.template_name_without_provider();
// Handle deprecated OpenZeppelin template
if matches!(template, Parachain::DeprecatedOpenZeppelinGeneric) {
template_name = Parachain::OpenZeppelinGeneric.template_name_without_provider();
}

extract_template_files(template_name, temp_dir.path(), target, None)?;
Ok(tag)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -120,4 +142,22 @@ mod tests {

Ok(())
}

#[test]
fn test_parachain_instantiate_openzeppelin_template() -> Result<()> {
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
instantiate_openzeppelin_template(&Parachain::OpenZeppelinEVM, temp_dir.path(), None)?;

let node_manifest =
pop_common::manifest::from_path(Some(&temp_dir.path().join("node/Cargo.toml")))
.expect("Failed to read file");
assert_eq!("evm-template-node", node_manifest.package().name());

let runtime_manifest =
pop_common::manifest::from_path(Some(&temp_dir.path().join("runtime/Cargo.toml")))
.expect("Failed to read file");
assert_eq!("evm-runtime-template", runtime_manifest.package().name());

Ok(())
}
}
Loading
Loading