Improvements in minimal template (#4119)

This PR makes a few improvements in the docs for the minimal template.

---------

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
This commit is contained in:
gupnik
2024-04-30 11:09:08 +05:30
committed by GitHub
parent 1fb058b791
commit 31dc8bb1de
13 changed files with 208 additions and 19 deletions
Generated
+13
View File
@@ -8474,6 +8474,19 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "minimal-template"
version = "0.0.0"
dependencies = [
"docify",
"minimal-template-node",
"minimal-template-runtime",
"pallet-minimal-template",
"polkadot-sdk-docs",
"polkadot-sdk-frame",
"simple-mermaid",
]
[[package]] [[package]]
name = "minimal-template-node" name = "minimal-template-node"
version = "0.0.0" version = "0.0.0"
+1
View File
@@ -513,6 +513,7 @@ members = [
"substrate/utils/substrate-bip39", "substrate/utils/substrate-bip39",
"substrate/utils/wasm-builder", "substrate/utils/wasm-builder",
"templates/minimal",
"templates/minimal/node", "templates/minimal/node",
"templates/minimal/pallets/template", "templates/minimal/pallets/template",
"templates/minimal/runtime", "templates/minimal/runtime",
@@ -66,6 +66,7 @@ pub fn expand_outer_dispatch(
quote! { quote! {
#( #query_call_part_macros )* #( #query_call_part_macros )*
/// The aggregated runtime call type.
#[derive( #[derive(
Clone, PartialEq, Eq, Clone, PartialEq, Eq,
#scrate::__private::codec::Encode, #scrate::__private::codec::Encode,
@@ -533,6 +533,7 @@ pub(crate) fn decl_all_pallets<'a>(
for pallet_declaration in pallet_declarations { for pallet_declaration in pallet_declarations {
let type_name = &pallet_declaration.name; let type_name = &pallet_declaration.name;
let pallet = &pallet_declaration.path; let pallet = &pallet_declaration.path;
let docs = &pallet_declaration.docs;
let mut generics = vec![quote!(#runtime)]; let mut generics = vec![quote!(#runtime)];
generics.extend(pallet_declaration.instance.iter().map(|name| quote!(#pallet::#name))); generics.extend(pallet_declaration.instance.iter().map(|name| quote!(#pallet::#name)));
let mut attrs = Vec::new(); let mut attrs = Vec::new();
@@ -541,6 +542,7 @@ pub(crate) fn decl_all_pallets<'a>(
attrs.extend(TokenStream2::from_str(&feat).expect("was parsed successfully; qed")); attrs.extend(TokenStream2::from_str(&feat).expect("was parsed successfully; qed"));
} }
let type_decl = quote!( let type_decl = quote!(
#( #[doc = #docs] )*
#(#attrs)* #(#attrs)*
pub type #type_name = #pallet::Pallet <#(#generics),*>; pub type #type_name = #pallet::Pallet <#(#generics),*>;
); );
@@ -605,6 +605,8 @@ pub struct Pallet {
pub pallet_parts: Vec<PalletPart>, pub pallet_parts: Vec<PalletPart>,
/// Expressions specified inside of a #[cfg] attribute. /// Expressions specified inside of a #[cfg] attribute.
pub cfg_pattern: Vec<cfg_expr::Expression>, pub cfg_pattern: Vec<cfg_expr::Expression>,
/// The doc literals
pub docs: Vec<syn::Expr>,
} }
impl Pallet { impl Pallet {
@@ -774,6 +776,7 @@ fn convert_pallets(pallets: Vec<PalletDeclaration>) -> syn::Result<PalletsConver
instance: pallet.instance, instance: pallet.instance,
cfg_pattern, cfg_pattern,
pallet_parts, pallet_parts,
docs: vec![],
}) })
}) })
.collect::<Result<Vec<_>>>()?; .collect::<Result<Vec<_>>>()?;
@@ -198,9 +198,9 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream {
macro_rules! #default_parts_unique_id_v2 { macro_rules! #default_parts_unique_id_v2 {
{ {
$caller:tt $caller:tt
frame_support = [{ $($frame_support:ident)::* }] your_tt_return = [{ $my_tt_return:path }]
} => { } => {
$($frame_support)*::__private::tt_return! { $my_tt_return! {
$caller $caller
tokens = [{ tokens = [{
+ Pallet #call_part_v2 #storage_part_v2 #event_part_v2 #error_part_v2 #origin_part_v2 #config_part_v2 + Pallet #call_part_v2 #storage_part_v2 #event_part_v2 #error_part_v2 #origin_part_v2 #config_part_v2
@@ -93,7 +93,7 @@ fn construct_runtime_implicit_to_explicit(
let frame_support = generate_access_from_frame_or_crate("frame-support")?; let frame_support = generate_access_from_frame_or_crate("frame-support")?;
let attr = if legacy_ordering { quote!((legacy_ordering)) } else { quote!() }; let attr = if legacy_ordering { quote!((legacy_ordering)) } else { quote!() };
let mut expansion = quote::quote!( let mut expansion = quote::quote!(
#[frame_support::runtime #attr] #[#frame_support::runtime #attr]
#input #input
); );
for pallet in definition.pallet_decls.iter() { for pallet in definition.pallet_decls.iter() {
@@ -103,7 +103,7 @@ fn construct_runtime_implicit_to_explicit(
expansion = quote::quote!( expansion = quote::quote!(
#frame_support::__private::tt_call! { #frame_support::__private::tt_call! {
macro = [{ #pallet_path::tt_default_parts_v2 }] macro = [{ #pallet_path::tt_default_parts_v2 }]
frame_support = [{ #frame_support }] your_tt_return = [{ #frame_support::__private::tt_return }]
~~> #frame_support::match_and_insert! { ~~> #frame_support::match_and_insert! {
target = [{ #expansion }] target = [{ #expansion }]
pattern = [{ #pallet_name = #pallet_path #pallet_instance }] pattern = [{ #pallet_name = #pallet_path #pallet_instance }]
@@ -16,6 +16,7 @@
// limitations under the License. // limitations under the License.
use crate::construct_runtime::parse::{Pallet, PalletPart, PalletPartKeyword, PalletPath}; use crate::construct_runtime::parse::{Pallet, PalletPart, PalletPartKeyword, PalletPath};
use frame_support_procedural_tools::get_doc_literals;
use quote::ToTokens; use quote::ToTokens;
use syn::{punctuated::Punctuated, spanned::Spanned, token, Error, Ident, PathArguments}; use syn::{punctuated::Punctuated, spanned::Spanned, token, Error, Ident, PathArguments};
@@ -86,6 +87,8 @@ impl Pallet {
let cfg_pattern = vec![]; let cfg_pattern = vec![];
let docs = get_doc_literals(&item.attrs);
Ok(Pallet { Ok(Pallet {
is_expanded: true, is_expanded: true,
name, name,
@@ -94,6 +97,7 @@ impl Pallet {
instance, instance,
cfg_pattern, cfg_pattern,
pallet_parts, pallet_parts,
docs,
}) })
} }
} }
@@ -21,13 +21,14 @@ use syn::{spanned::Spanned, Attribute, Ident, PathArguments};
/// The declaration of a pallet. /// The declaration of a pallet.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct PalletDeclaration { pub struct PalletDeclaration {
/// The name of the pallet, e.g.`System` in `System: frame_system`. /// The name of the pallet, e.g.`System` in `pub type System = frame_system`.
pub name: Ident, pub name: Ident,
/// Optional attributes tagged right above a pallet declaration. /// Optional attributes tagged right above a pallet declaration.
pub attrs: Vec<Attribute>, pub attrs: Vec<Attribute>,
/// The path of the pallet, e.g. `frame_system` in `System: frame_system`. /// The path of the pallet, e.g. `frame_system` in `pub type System = frame_system`.
pub path: syn::Path, pub path: syn::Path,
/// The instance of the pallet, e.g. `Instance1` in `Council: pallet_collective::<Instance1>`. /// The instance of the pallet, e.g. `Instance1` in `pub type Council =
/// pallet_collective<Instance1>`.
pub instance: Option<Ident>, pub instance: Option<Ident>,
} }
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "minimal-template"
description = "A minimal template built with Substrate, part of Polkadot Sdk."
version = "0.0.0"
license = "MIT-0"
authors.workspace = true
homepage.workspace = true
repository.workspace = true
edition.workspace = true
publish = false
[lints]
workspace = true
[dependencies]
minimal-template-node = { path = "./node" }
minimal-template-runtime = { path = "./runtime" }
pallet-minimal-template = { path = "./pallets/template" }
polkadot-sdk-docs = { path = "../../docs/sdk" }
frame = { package = "polkadot-sdk-frame", path = "../../substrate/frame" }
# How we build docs in rust-docs
simple-mermaid = "0.1.1"
docify = "0.2.7"
+13
View File
@@ -0,0 +1,13 @@
# Minimal Template
This is a minimal template for creating a blockchain using the Polkadot SDK.
# Docs
You can generate and view the [Rust
Docs](https://doc.rust-lang.org/cargo/commands/cargo-doc.html) for this template
with this command:
```sh
cargo doc -p minimal-template --open
```
+62 -11
View File
@@ -15,6 +15,8 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//! A minimal runtime that includes the template [`pallet`](`pallet_minimal_template`).
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
// Make the WASM binary available. // Make the WASM binary available.
@@ -24,6 +26,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use frame::{ use frame::{
deps::frame_support::{ deps::frame_support::{
genesis_builder_helper::{build_state, get_preset}, genesis_builder_helper::{build_state, get_preset},
runtime,
weights::{FixedFee, NoFee}, weights::{FixedFee, NoFee},
}, },
prelude::*, prelude::*,
@@ -36,6 +39,7 @@ use frame::{
}, },
}; };
/// The runtime version.
#[runtime_version] #[runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion { pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("minimal-template-runtime"), spec_name: create_runtime_str!("minimal-template-runtime"),
@@ -54,61 +58,108 @@ pub fn native_version() -> NativeVersion {
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
} }
/// The signed extensions that are added to the runtime.
type SignedExtra = ( type SignedExtra = (
// Checks that the sender is not the zero address.
frame_system::CheckNonZeroSender<Runtime>, frame_system::CheckNonZeroSender<Runtime>,
// Checks that the runtime version is correct.
frame_system::CheckSpecVersion<Runtime>, frame_system::CheckSpecVersion<Runtime>,
// Checks that the transaction version is correct.
frame_system::CheckTxVersion<Runtime>, frame_system::CheckTxVersion<Runtime>,
// Checks that the genesis hash is correct.
frame_system::CheckGenesis<Runtime>, frame_system::CheckGenesis<Runtime>,
// Checks that the era is valid.
frame_system::CheckEra<Runtime>, frame_system::CheckEra<Runtime>,
// Checks that the nonce is valid.
frame_system::CheckNonce<Runtime>, frame_system::CheckNonce<Runtime>,
// Checks that the weight is valid.
frame_system::CheckWeight<Runtime>, frame_system::CheckWeight<Runtime>,
// Ensures that the sender has enough funds to pay for the transaction
// and deducts the fee from the sender's account.
pallet_transaction_payment::ChargeTransactionPayment<Runtime>, pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
); );
construct_runtime!( // Composes the runtime by adding all the used pallets and deriving necessary types.
pub enum Runtime { #[runtime]
System: frame_system, mod runtime {
Timestamp: pallet_timestamp, /// The main runtime type.
#[runtime::runtime]
#[runtime::derive(
RuntimeCall,
RuntimeEvent,
RuntimeError,
RuntimeOrigin,
RuntimeFreezeReason,
RuntimeHoldReason,
RuntimeSlashReason,
RuntimeLockId,
RuntimeTask
)]
pub struct Runtime;
Balances: pallet_balances, /// Mandatory system pallet that should always be included in a FRAME runtime.
Sudo: pallet_sudo, #[runtime::pallet_index(0)]
TransactionPayment: pallet_transaction_payment, pub type System = frame_system;
// our local pallet /// Provides a way for consensus systems to set and check the onchain time.
Template: pallet_minimal_template, #[runtime::pallet_index(1)]
pub type Timestamp = pallet_timestamp;
/// Provides the ability to keep track of balances.
#[runtime::pallet_index(2)]
pub type Balances = pallet_balances;
/// Provides a way to execute privileged functions.
#[runtime::pallet_index(3)]
pub type Sudo = pallet_sudo;
/// Provides the ability to charge for extrinsic execution.
#[runtime::pallet_index(4)]
pub type TransactionPayment = pallet_transaction_payment;
/// A minimal pallet template.
#[runtime::pallet_index(5)]
pub type Template = pallet_minimal_template;
} }
);
parameter_types! { parameter_types! {
pub const Version: RuntimeVersion = VERSION; pub const Version: RuntimeVersion = VERSION;
} }
/// Implements the types required for the system pallet.
#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig)] #[derive_impl(frame_system::config_preludes::SolochainDefaultConfig)]
impl frame_system::Config for Runtime { impl frame_system::Config for Runtime {
type Block = Block; type Block = Block;
type Version = Version; type Version = Version;
type BlockHashCount = ConstU32<1024>; // Use the account data from the balances pallet
type AccountData = pallet_balances::AccountData<<Runtime as pallet_balances::Config>::Balance>; type AccountData = pallet_balances::AccountData<<Runtime as pallet_balances::Config>::Balance>;
} }
// Implements the types required for the balances pallet.
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Runtime { impl pallet_balances::Config for Runtime {
type AccountStore = System; type AccountStore = System;
} }
// Implements the types required for the sudo pallet.
#[derive_impl(pallet_sudo::config_preludes::TestDefaultConfig)] #[derive_impl(pallet_sudo::config_preludes::TestDefaultConfig)]
impl pallet_sudo::Config for Runtime {} impl pallet_sudo::Config for Runtime {}
// Implements the types required for the sudo pallet.
#[derive_impl(pallet_timestamp::config_preludes::TestDefaultConfig)] #[derive_impl(pallet_timestamp::config_preludes::TestDefaultConfig)]
impl pallet_timestamp::Config for Runtime {} impl pallet_timestamp::Config for Runtime {}
// Implements the types required for the transaction payment pallet.
#[derive_impl(pallet_transaction_payment::config_preludes::TestDefaultConfig)] #[derive_impl(pallet_transaction_payment::config_preludes::TestDefaultConfig)]
impl pallet_transaction_payment::Config for Runtime { impl pallet_transaction_payment::Config for Runtime {
type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>; type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>;
// Setting fee as independent of the weight of the extrinsic for demo purposes
type WeightToFee = NoFee<<Self as pallet_balances::Config>::Balance>; type WeightToFee = NoFee<<Self as pallet_balances::Config>::Balance>;
// Setting fee as fixed for any length of the call data for demo purposes
type LengthToFee = FixedFee<1, <Self as pallet_balances::Config>::Balance>; type LengthToFee = FixedFee<1, <Self as pallet_balances::Config>::Balance>;
} }
// Implements the types required for the template pallet.
impl pallet_minimal_template::Config for Runtime {} impl pallet_minimal_template::Config for Runtime {}
type Block = frame::runtime::types_common::BlockOf<Runtime, SignedExtra>; type Block = frame::runtime::types_common::BlockOf<Runtime, SignedExtra>;
+75
View File
@@ -0,0 +1,75 @@
//! # Minimal Template
//!
//! This is a minimal template for creating a blockchain using the Polkadot SDK.
//!
//! ## Components
//!
//! The template consists of the following components:
//!
//! ### Node
//!
//! A minimal blockchain [`node`](`minimal_template_node`) that is capable of running a
//! runtime. It uses a simple chain specification, provides an option to choose Manual or
//! InstantSeal for consensus and exposes a few commands to interact with the node.
//!
//! ### Runtime
//!
//! A minimal [`runtime`](`minimal_template_runtime`) (or a state transition function) that
//! is capable of being run on the node. It is built using the [`FRAME`](`frame`) framework
//! that enables the composition of the core logic via separate modules called "pallets".
//! FRAME defines a complete DSL for building such pallets and the runtime itself.
//!
//! #### Transaction Fees
//!
//! The runtime charges a transaction fee for every transaction that is executed. The fee is
//! calculated based on the weight of the transaction (accouting for the execution time) and
//! length of the call data. Please refer to
//! [`benchmarking docs`](`polkadot_sdk_docs::reference_docs::frame_benchmarking_weight`) for
//! more information on how the weight is calculated.
//!
//! This template sets the fee as independent of the weight of the extrinsic and fixed for any
//! length of the call data for demo purposes.
//!
//! ### Pallet
//!
//! A minimal [`pallet`](`pallet_minimal_template`) that is built using FRAME. It is a unit of
//! encapsulated logic that has a clearly defined responsibility and can be linked to other pallets.
//!
//! ## Getting Started
//!
//! To get started with the template, follow the steps below:
//!
//! ### Build the Node
//!
//! Build the node using the following command:
//!
//! ```bash
//! cargo build -p minimal-template-node --release
//! ```
//!
//! ### Run the Node
//!
//! Run the node using the following command:
//!
//! ```bash
//! ./target/release/minimal-template-node --dev
//! ```
//!
//! ### CLI Options
//!
//! The node exposes a few options that can be used to interact with the node. To see the list of
//! available options, run the following command:
//!
//! ```bash
//! ./target/release/minimal-template-node --help
//! ```
//!
//! #### Consensus Algorithm
//!
//! In order to run the node with a specific consensus algorithm, use the `--consensus` flag. For
//! example, to run the node with ManualSeal consensus with a block time of 5000ms, use the
//! following command:
//!
//! ```bash
//! ./target/release/minimal-template-node --dev --consensus manual-seal-5000
//! ```