From 08f3464106574a0b6bea2c04b571a0a179908cd4 Mon Sep 17 00:00:00 2001 From: Alex Bean Date: Thu, 23 May 2024 09:12:42 +0200 Subject: [PATCH] docs: add missing documentation comments for `pop_contracts` and `pop_parachain` crates (#181) * docs: comments in pop parachain crate * docs: pop contracts documentation * docs: fix feedback * docs: apply feedback * docs: apply feedback --- crates/pop-contracts/Cargo.toml | 2 +- crates/pop-contracts/README.md | 4 +--- crates/pop-contracts/src/build.rs | 1 + crates/pop-contracts/src/call.rs | 28 ++++++++++++++++++++++ crates/pop-contracts/src/lib.rs | 3 ++- crates/pop-contracts/src/new.rs | 6 +++++ crates/pop-contracts/src/test.rs | 10 ++++++++ crates/pop-contracts/src/up.rs | 21 ++++++++++++++++ crates/pop-parachains/README.md | 6 ++--- crates/pop-parachains/src/build.rs | 1 + crates/pop-parachains/src/lib.rs | 3 ++- crates/pop-parachains/src/new_pallet.rs | 8 ++++++- crates/pop-parachains/src/new_parachain.rs | 9 ++++++- crates/pop-parachains/src/templates.rs | 22 +++++++++++++++-- crates/pop-parachains/src/up.rs | 10 ++++++++ crates/pop-parachains/src/utils/git.rs | 28 +++++++++++++++++++--- crates/pop-parachains/src/utils/helpers.rs | 5 ++++ 17 files changed, 151 insertions(+), 16 deletions(-) diff --git a/crates/pop-contracts/Cargo.toml b/crates/pop-contracts/Cargo.toml index 16dc026e..c81c346e 100644 --- a/crates/pop-contracts/Cargo.toml +++ b/crates/pop-contracts/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pop-contracts" -description = "Library for generating, building, deploying and calling ink! smart contracts." +description = "Library for generating, building, deploying, and calling ink! smart contracts." version = "0.1.0" license = "Apache-2.0" edition.workspace = true diff --git a/crates/pop-contracts/README.md b/crates/pop-contracts/README.md index c7fe3b4c..258f3aee 100644 --- a/crates/pop-contracts/README.md +++ b/crates/pop-contracts/README.md @@ -1,8 +1,6 @@ # pop-contracts -A crate for generating, building, deploying and calling [`ink!`](https://github.com/paritytech/ink) Smart Contracts. - -> :information_source: A [crates.io](https://crates.io/crates/pop-contracts) version will be available soon! +A crate for generating, building, deploying, and calling [`ink!`](https://github.com/paritytech/ink) Smart Contracts. Used by [`pop-cli`](https://github.com/r0gue-io/pop-cli). ## Usage diff --git a/crates/pop-contracts/src/build.rs b/crates/pop-contracts/src/build.rs index 5d5ace7f..767e239d 100644 --- a/crates/pop-contracts/src/build.rs +++ b/crates/pop-contracts/src/build.rs @@ -4,6 +4,7 @@ use std::path::PathBuf; use crate::utils::helpers::get_manifest_path; +/// Build the smart contract located in the specified `path`. pub fn build_smart_contract(path: &Option) -> anyhow::Result { let manifest_path = get_manifest_path(path)?; // Default values diff --git a/crates/pop-contracts/src/call.rs b/crates/pop-contracts/src/call.rs index ae11dbc0..8f052114 100644 --- a/crates/pop-contracts/src/call.rs +++ b/crates/pop-contracts/src/call.rs @@ -16,6 +16,8 @@ use crate::utils::{ helpers::{get_manifest_path, parse_account, parse_balance}, signer::create_signer, }; + +/// Attributes for the `call` command. pub struct CallOpts { /// Path to the contract build folder. pub path: Option, @@ -39,6 +41,12 @@ pub struct CallOpts { pub execute: bool, } +/// Prepare the preprocessed data for a contract `call`. +/// +/// # Arguments +/// +/// * `call_opts` - attributes for the `call` command. +/// pub async fn set_up_call( call_opts: CallOpts, ) -> anyhow::Result> { @@ -67,6 +75,12 @@ pub async fn set_up_call( return Ok(call_exec); } +/// Simulate a smart contract call without modifying the state of the blockchain. +/// +/// # Arguments +/// +/// * `call_exec` - struct with the call to be executed. +/// pub async fn dry_run_call( call_exec: &CallExec, ) -> anyhow::Result { @@ -93,6 +107,12 @@ pub async fn dry_run_call( } } +/// Estimate the gas required for a contract call without modifying the state of the blockchain. +/// +/// # Arguments +/// +/// * `call_exec` - the preprocessed data to call a contract. +/// pub async fn dry_run_gas_estimate_call( call_exec: &CallExec, ) -> anyhow::Result { @@ -116,6 +136,14 @@ pub async fn dry_run_gas_estimate_call( } } +/// Call a smart contract on the blockchain. +/// +/// # Arguments +/// +/// * `call_exec` - struct with the call to be executed. +/// * `gas_limit` - maximum amount of gas to be used for this call. +/// * `url` - endpoint of the node which to send the call to. +/// pub async fn call_smart_contract( call_exec: CallExec, gas_limit: Weight, diff --git a/crates/pop-contracts/src/lib.rs b/crates/pop-contracts/src/lib.rs index 348632f8..ea388f28 100644 --- a/crates/pop-contracts/src/lib.rs +++ b/crates/pop-contracts/src/lib.rs @@ -1,11 +1,12 @@ // SPDX-License-Identifier: GPL-3.0 +#![doc = include_str!("../README.md")] mod build; mod call; mod errors; mod new; mod test; mod up; -pub mod utils; +mod utils; pub use build::build_smart_contract; pub use call::{ diff --git a/crates/pop-contracts/src/new.rs b/crates/pop-contracts/src/new.rs index 978b26ef..e4e3c2e7 100644 --- a/crates/pop-contracts/src/new.rs +++ b/crates/pop-contracts/src/new.rs @@ -3,6 +3,12 @@ use crate::errors::Error; use contract_build::new_contract_project; use std::path::Path; +/// Create a new smart contract. +/// +/// # Arguments +/// +/// * `name` - name for the smart contract to be created. +/// * `target` - location where the smart contract will be created. pub fn create_smart_contract(name: &str, target: &Path) -> Result<(), Error> { // Canonicalize the target path to ensure consistency and resolve any symbolic links. let canonicalized_path = target diff --git a/crates/pop-contracts/src/test.rs b/crates/pop-contracts/src/test.rs index 5867157f..518a5fcf 100644 --- a/crates/pop-contracts/src/test.rs +++ b/crates/pop-contracts/src/test.rs @@ -3,6 +3,11 @@ use crate::errors::Error; use duct::cmd; use std::path::PathBuf; +/// Run unit tests of a smart contract. +/// +/// # Arguments +/// +/// * `path` - location of the smart contract. pub fn test_smart_contract(path: &Option) -> Result<(), Error> { // Execute `cargo test` command in the specified directory. cmd("cargo", vec!["test"]) @@ -12,6 +17,11 @@ pub fn test_smart_contract(path: &Option) -> Result<(), Error> { Ok(()) } +/// Run the e2e tests of a smart contract. +/// +/// # Arguments +/// +/// * `path` - location of the smart contract. pub fn test_e2e_smart_contract(path: &Option) -> Result<(), Error> { // Execute `cargo test --features=e2e-tests` command in the specified directory. cmd("cargo", vec!["test", "--features=e2e-tests"]) diff --git a/crates/pop-contracts/src/up.rs b/crates/pop-contracts/src/up.rs index 45091ad7..29e392fc 100644 --- a/crates/pop-contracts/src/up.rs +++ b/crates/pop-contracts/src/up.rs @@ -14,6 +14,7 @@ use std::path::PathBuf; use subxt::PolkadotConfig as DefaultConfig; use subxt_signer::sr25519::Keypair; +/// Attributes for the `up` command pub struct UpOpts { /// Path to the contract build folder. pub path: Option, @@ -35,6 +36,13 @@ pub struct UpOpts { /// Secret key URI for the account deploying the contract. pub suri: String, } + +/// Prepare `InstantiateExec` data to upload and instantiate a contract. +/// +/// # Arguments +/// +/// * `up_opts` - attributes for the `up` command. +/// pub async fn set_up_deployment( up_opts: UpOpts, ) -> anyhow::Result> { @@ -64,6 +72,12 @@ pub async fn set_up_deployment( return Ok(instantiate_exec); } +/// Estimate the gas required for instantiating a contract without modifying the state of the blockchain. +/// +/// # Arguments +/// +/// * `instantiate_exec` - the preprocessed data to instantiate a contract. +/// pub async fn dry_run_gas_estimate_instantiate( instantiate_exec: &InstantiateExec, ) -> anyhow::Result { @@ -89,6 +103,13 @@ pub async fn dry_run_gas_estimate_instantiate( } } +/// Instantiate a contract. +/// +/// # Arguments +/// +/// * `instantiate_exec` - the preprocessed data to instantiate a contract. +/// * `gas_limit` - maximum amount of gas to be used for this call. +/// pub async fn instantiate_smart_contract( instantiate_exec: InstantiateExec, gas_limit: Weight, diff --git a/crates/pop-parachains/README.md b/crates/pop-parachains/README.md index b5667f00..3440cb18 100644 --- a/crates/pop-parachains/README.md +++ b/crates/pop-parachains/README.md @@ -1,11 +1,11 @@ # pop-parachains -A crate for generating, building and running Parachains and Pallets. +A crate for generating, building and running parachains and pallets. Used by +[`pop-cli`](https://github.com/r0gue-io/pop-cli). -> :information_source: A [crates.io](https://crates.io/crates/pop-parachains) version will be available soon! ## Usage -Generate a new Parachain: +Generate a new parachain: ```rust use pop_parachains::{instantiate_template_dir, Config, Git, Template}; diff --git a/crates/pop-parachains/src/build.rs b/crates/pop-parachains/src/build.rs index 7fa44a10..6bc8a805 100644 --- a/crates/pop-parachains/src/build.rs +++ b/crates/pop-parachains/src/build.rs @@ -2,6 +2,7 @@ use duct::cmd; use std::path::PathBuf; +/// Build the parachain located in the specified `path`. pub fn build_parachain(path: &Option) -> anyhow::Result<()> { cmd("cargo", vec!["build", "--release"]) .dir(path.clone().unwrap_or("./".into())) diff --git a/crates/pop-parachains/src/lib.rs b/crates/pop-parachains/src/lib.rs index 0aa45aeb..4f5e4afd 100644 --- a/crates/pop-parachains/src/lib.rs +++ b/crates/pop-parachains/src/lib.rs @@ -1,4 +1,5 @@ // SPDX-License-Identifier: GPL-3.0 +#![doc = include_str!("../README.md")] mod build; mod errors; mod generator; @@ -16,5 +17,5 @@ pub use up::{Source, Status, Zombienet}; pub use utils::git::{Git, GitHub, Release}; pub use utils::helpers::is_initial_endowment_valid; pub use utils::pallet_helpers::resolve_pallet_path; -// External exports +/// Information about the Node. External export from Zombienet-SDK. pub use zombienet_sdk::NetworkNode; diff --git a/crates/pop-parachains/src/new_pallet.rs b/crates/pop-parachains/src/new_pallet.rs index 4dd9967e..e550432e 100644 --- a/crates/pop-parachains/src/new_pallet.rs +++ b/crates/pop-parachains/src/new_pallet.rs @@ -10,12 +10,18 @@ use crate::{ utils::helpers::sanitize, }; +/// Metadata for the Template Pallet. pub struct TemplatePalletConfig { pub name: String, pub authors: String, pub description: String, } - +/// Create a new pallet from a template. +/// +/// # Arguments +/// +/// * `path` - location where the pallet will be created. +/// * `config` - customization values to include in the new pallet. pub fn create_pallet_template( path: Option, config: TemplatePalletConfig, diff --git a/crates/pop-parachains/src/new_parachain.rs b/crates/pop-parachains/src/new_parachain.rs index 1784d8da..c7848420 100644 --- a/crates/pop-parachains/src/new_parachain.rs +++ b/crates/pop-parachains/src/new_parachain.rs @@ -12,7 +12,14 @@ use anyhow::Result; use std::{fs, path::Path}; use walkdir::WalkDir; -/// Creates a new template at `target` dir +/// Create a new parachain. +/// +/// # Arguments +/// +/// * `template` - template to generate the parachain from. +/// * `target` - location where the parachain will be created. +/// * `tag_version` - version to use (`None` to use latest). +/// * `config` - customization values to include in the new parachain. pub fn instantiate_template_dir( template: &Template, target: &Path, diff --git a/crates/pop-parachains/src/templates.rs b/crates/pop-parachains/src/templates.rs index 642f0743..4fcc3f7a 100644 --- a/crates/pop-parachains/src/templates.rs +++ b/crates/pop-parachains/src/templates.rs @@ -5,6 +5,7 @@ use strum::{ use strum_macros::{AsRefStr, Display, EnumMessage, EnumProperty, EnumString, VariantArray}; use thiserror::Error; +/// Supported template providers. #[derive( AsRefStr, Clone, Default, Debug, Display, EnumMessage, EnumString, Eq, PartialEq, VariantArray, )] @@ -27,14 +28,17 @@ pub enum Provider { } impl Provider { + /// Get the list of providers supported. pub fn providers() -> &'static [Provider] { Provider::VARIANTS } + /// Get provider's name. pub fn name(&self) -> &str { self.get_message().unwrap_or_default() } + /// Get the default template of the provider. pub fn default_template(&self) -> Template { match &self { Provider::Pop => Template::Standard, @@ -42,10 +46,12 @@ impl Provider { } } + /// Get the providers detailed description message. pub fn description(&self) -> &str { self.get_detailed_message().unwrap_or_default() } + /// Get the list of templates of the provider. pub fn templates(&self) -> Vec<&Template> { Template::VARIANTS .iter() @@ -54,6 +60,7 @@ impl Provider { } } +/// Configurable settings for parachain generation. #[derive(Debug, Clone, PartialEq)] pub struct Config { pub symbol: String, @@ -61,6 +68,7 @@ pub struct Config { pub initial_endowment: String, } +/// Templates supported. #[derive( AsRefStr, Clone, @@ -76,7 +84,7 @@ pub struct Config { VariantArray, )] pub enum Template { - // Pop + /// Minimalist parachain template. #[default] #[strum( serialize = "standard", @@ -89,6 +97,7 @@ pub enum Template { ) )] Standard, + /// Parachain configured with fungible and non-fungilble asset functionalities. #[strum( serialize = "assets", message = "Assets", @@ -100,6 +109,7 @@ pub enum Template { ) )] Assets, + /// Parachain configured to support WebAssembly smart contracts. #[strum( serialize = "contracts", message = "Contracts", @@ -111,6 +121,7 @@ pub enum Template { ) )] Contracts, + /// Parachain configured with Frontier, enabling compatibility with the Ethereum Virtual Machine (EVM). #[strum( serialize = "evm", message = "EVM", @@ -122,7 +133,7 @@ pub enum Template { ) )] EVM, - // Parity + /// Minimal Substrate node configured for smart contracts via pallet-contracts. #[strum( serialize = "cpt", message = "Contracts", @@ -134,6 +145,7 @@ pub enum Template { ) )] ParityContracts, + /// Template node for a Frontier (EVM) based parachain. #[strum( serialize = "fpt", message = "EVM", @@ -148,22 +160,28 @@ pub enum Template { } impl Template { + /// Get the template's name. pub fn name(&self) -> &str { self.get_message().unwrap_or_default() } + + /// Get the detailed message of the template. pub fn description(&self) -> &str { self.get_detailed_message().unwrap_or_default() } + /// Check the template belongs to a `provider`. pub fn matches(&self, provider: &Provider) -> bool { // Match explicitly on provider name (message) self.get_str("Provider") == Some(provider.name()) } + /// Get the template's repository url. pub fn repository_url(&self) -> Result<&str, Error> { self.get_str("Repository").ok_or(Error::RepositoryMissing) } + /// Get the provider of the template. pub fn provider(&self) -> Result<&str, Error> { self.get_str("Provider").ok_or(Error::ProviderMissing) } diff --git a/crates/pop-parachains/src/up.rs b/crates/pop-parachains/src/up.rs index 5c41aec7..4eb7763a 100644 --- a/crates/pop-parachains/src/up.rs +++ b/crates/pop-parachains/src/up.rs @@ -20,6 +20,7 @@ use zombienet_support::fs::local::LocalFileSystem; const POLKADOT_SDK: &str = "https://github.com/paritytech/polkadot-sdk"; const POLKADOT_DEFAULT_VERSION: &str = "v1.11.0"; +/// A helper to spawn a local network. pub struct Zombienet { /// The cache location, used for caching binaries. cache: PathBuf, @@ -32,6 +33,13 @@ pub struct Zombienet { } impl Zombienet { + /// # Arguments + /// + /// * `cache` - location, used for caching binaries + /// * `network_config` - config file to be used to launch a network. + /// * `relay_chain_version` - the specific version used for the relay chain (none will fetch the last one). + /// * `system_parachain_version` - the specific version used for the system chain (none will fetch the last one). + /// * `parachains` - list of parachains url. pub async fn new( cache: PathBuf, network_config: &str, @@ -115,6 +123,7 @@ impl Zombienet { }) } + /// Keep a list of the missing binaries to be downloaded. pub fn missing_binaries(&self) -> Vec<&Binary> { let mut missing = Vec::new(); if !self.relay_chain.path.exists() { @@ -126,6 +135,7 @@ impl Zombienet { missing } + /// Launch the networks specified in the Zombienet `struct`. pub async fn spawn(&mut self) -> Result, Error> { // Symlink polkadot-related binaries for file in ["polkadot-execute-worker", "polkadot-prepare-worker"] { diff --git a/crates/pop-parachains/src/utils/git.rs b/crates/pop-parachains/src/utils/git.rs index 2fa14bf0..2aca744b 100644 --- a/crates/pop-parachains/src/utils/git.rs +++ b/crates/pop-parachains/src/utils/git.rs @@ -10,6 +10,7 @@ use std::path::Path; use std::{env, fs}; use url::Url; +/// A helper for handling Git operations. pub struct Git; impl Git { pub(crate) fn clone(url: &Url, working_dir: &Path, branch: Option<&str>) -> Result<()> { @@ -43,7 +44,14 @@ impl Git { } Ok(()) } - /// Clone `url` into `target` and degit it + + /// Clone a Git repository and degit it. + /// + /// # Arguments + /// + /// * `url` - the URL of the repository to clone. + /// * `target` - location where the repository will be cloned. + /// * `tag_version` - the specific tag or version of the repository to use pub fn clone_and_degit( url: &str, target: &Path, @@ -82,7 +90,7 @@ impl Git { Ok(release) } - /// For users that have ssh configuration for cloning repositories + /// For users that have ssh configuration for cloning repositories. fn ssh_clone_and_degit(url: Url, target: &Path) -> Result { let ssh_url = GitHub::convert_to_ssh_url(&url); // Prepare callback and fetch options. @@ -123,7 +131,12 @@ impl Git { None } - /// Init a new git repo on creation of a parachain + /// Init a new git repository. + /// + /// # Arguments + /// + /// * `target` - location where the parachain will be created. + /// * `message` - message for first commit. pub fn git_init(target: &Path, message: &str) -> Result<(), git2::Error> { let repo = Repository::init(target)?; let signature = repo.signature()?; @@ -142,6 +155,7 @@ impl Git { } } +/// A helper for handling GitHub operations. pub struct GitHub { pub org: String, pub name: String, @@ -151,6 +165,11 @@ pub struct GitHub { impl GitHub { const GITHUB: &'static str = "github.com"; + /// Parse URL of a github repository. + /// + /// # Arguments + /// + /// * `url` - the URL of the repository to clone. pub fn parse(url: &str) -> Result { let url = Url::parse(url)?; Ok(Self { @@ -167,6 +186,7 @@ impl GitHub { self } + /// Fetch the latest releases of the Github repository. pub async fn get_latest_releases(&self) -> Result> { static APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); @@ -176,6 +196,7 @@ impl GitHub { Ok(response.json::>().await?) } + /// Retrieves the commit hash associated with a specified tag in a GitHub repository. pub async fn get_commit_sha_from_release(&self, tag_name: &str) -> Result { static APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); @@ -229,6 +250,7 @@ impl GitHub { } } +/// Represents the data of a GitHub release. #[derive(Debug, PartialEq, serde::Deserialize)] pub struct Release { pub tag_name: String, diff --git a/crates/pop-parachains/src/utils/helpers.rs b/crates/pop-parachains/src/utils/helpers.rs index 6942a7b4..81574098 100644 --- a/crates/pop-parachains/src/utils/helpers.rs +++ b/crates/pop-parachains/src/utils/helpers.rs @@ -24,6 +24,11 @@ pub(crate) fn sanitize(target: &Path) -> Result<(), Error> { Ok(()) } +/// Check if the initial endowment input by the user is a valid balance. +/// +/// # Arguments +/// +/// * `initial_endowment` - initial endowment amount to be checked for validity. pub fn is_initial_endowment_valid(initial_endowment: &str) -> bool { initial_endowment.parse::().is_ok() || is_valid_bitwise_left_shift(initial_endowment).is_ok()