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

refactor: parachain template #4684

Merged
merged 12 commits into from
Jun 18, 2024
13 changes: 13 additions & 0 deletions prdoc/pr_4684.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
title: "Refactor of the parachain template"

doc:
- audience: Runtime Dev
description: |
Introduce the construct runtime V2 to the parachain template runtime. In addition, url links in the parachain pallet
template now direct to the polkadot sdk docs.

crates:
- name: pallet-parachain-template
bump: none
- name: parachain-template-runtime
bump: none
42 changes: 24 additions & 18 deletions templates/parachain/pallets/template/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
#![cfg_attr(not(feature = "std"), no_std)]

/// Edit this file to define custom logic or remove it if it is not needed.
/// Learn more about FRAME and the core library of Substrate FRAME pallets:
/// <https://docs.substrate.io/v3/runtime/frame>
pub use pallet::*;

#[cfg(test)]
Expand All @@ -16,6 +13,12 @@ pub mod weights;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;

// <https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html>
// <https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/guides/your_first_pallet/index.html>
//
// To see a full list of `pallet` macros and their use cases, see:
// <https://paritytech.github.io/polkadot-sdk/master/pallet_example_kitchensink/index.html>
// <https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/index.html>
#[frame_support::pallet]
pub mod pallet {
use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*};
Expand All @@ -25,32 +28,33 @@ pub mod pallet {
#[pallet::config]
pub trait Config: frame_system::Config {
/// Because this pallet emits events, it depends on the runtime's definition of an event.
/// <https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_runtime_types/index.html>
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

/// A type representing the weights required by the dispatchables of this pallet.
type WeightInfo: crate::weights::WeightInfo;
}

#[pallet::pallet]
pub struct Pallet<T>(_);

// The pallet's runtime storage items.
// https://docs.substrate.io/v3/runtime/storage
/// The pallet's storage items.
/// <https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/guides/your_first_pallet/index.html#storage>
/// <https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html>
#[pallet::storage]
// Learn more about declaring storage items:
// https://docs.substrate.io/v3/runtime/storage#declaring-storage-items
pub type Something<T> = StorageValue<_, u32>;

// Pallets use events to inform users when important changes are made.
// https://docs.substrate.io/v3/runtime/events-and-errors
/// Pallets use events to inform users when important changes are made.
/// <https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/guides/your_first_pallet/index.html#event-and-error>
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Event documentation should end with an array that provides descriptive names for event
/// parameters. [something, who]
SomethingStored(u32, T::AccountId),
/// We usually use passive tense for events.
SomethingStored { something: u32, who: T::AccountId },
}

// Errors inform users that something went wrong.
/// Errors inform users that something went wrong.
/// <https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/guides/your_first_pallet/index.html#event-and-error>
#[pallet::error]
pub enum Error<T> {
/// Error names should be descriptive.
Expand All @@ -62,9 +66,10 @@ pub mod pallet {
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}

// Dispatchable functions allows users to interact with the pallet and invoke state changes.
// These functions materialize as "extrinsics", which are often compared to transactions.
// Dispatchable functions must be annotated with a weight and must return a DispatchResult.
/// Dispatchable functions allows users to interact with the pallet and invoke state changes.
/// These functions materialize as "extrinsics", which are often compared to transactions.
/// Dispatchable functions must be annotated with a weight and must return a DispatchResult.
/// <https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/guides/your_first_pallet/index.html#dispatchables>
#[pallet::call]
impl<T: Config> Pallet<T> {
/// An example dispatchable that takes a singles value as a parameter, writes the value to
Expand All @@ -74,14 +79,15 @@ pub mod pallet {
pub fn do_something(origin: OriginFor<T>, something: u32) -> DispatchResultWithPostInfo {
// Check that the extrinsic was signed and get the signer.
// This function will return an error if the extrinsic is not signed.
// https://docs.substrate.io/v3/runtime/origins
// <https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_origin/index.html>
let who = ensure_signed(origin)?;

// Update storage.
<Something<T>>::put(something);

// Emit an event.
Self::deposit_event(Event::SomethingStored(something, who));
Self::deposit_event(Event::SomethingStored { something, who });

// Return a successful DispatchResultWithPostInfo
Ok(().into())
}
Expand Down
45 changes: 28 additions & 17 deletions templates/parachain/pallets/template/src/mock.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,36 @@
use frame_support::{derive_impl, parameter_types};
use frame_system as system;
use sp_runtime::BuildStorage;

type Block = frame_system::mocking::MockBlock<Test>;
use frame_support::{derive_impl, weights::constants::RocksDbWeight};
use frame_system::{mocking::MockBlock, GenesisConfig};
use sp_runtime::{traits::ConstU64, BuildStorage};

// Configure a mock runtime to test the pallet.
frame_support::construct_runtime!(
pub enum Test
{
System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
TemplateModule: crate::{Pallet, Call, Storage, Event<T>},
}
);
#[frame_support::runtime]
mod test_runtime {
#[runtime::runtime]
#[runtime::derive(
RuntimeCall,
RuntimeEvent,
RuntimeError,
RuntimeOrigin,
RuntimeFreezeReason,
RuntimeHoldReason,
RuntimeSlashReason,
RuntimeLockId,
RuntimeTask
)]
pub struct Test;

parameter_types! {
pub const SS58Prefix: u8 = 42;
#[runtime::pallet_index(0)]
pub type System = frame_system;
#[runtime::pallet_index(1)]
pub type TemplateModule = crate;
}

#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl system::Config for Test {
type Block = Block;
impl frame_system::Config for Test {
type Nonce = u64;
type Block = MockBlock<Test>;
type BlockHashCount = ConstU64<250>;
type DbWeight = RocksDbWeight;
}

impl crate::Config for Test {
Expand All @@ -29,5 +40,5 @@ impl crate::Config for Test {

// Build genesis storage according to the mock runtime.
pub fn new_test_ext() -> sp_io::TestExternalities {
system::GenesisConfig::<Test>::default().build_storage().unwrap().into()
GenesisConfig::<Test>::default().build_storage().unwrap().into()
}
2 changes: 1 addition & 1 deletion templates/parachain/pallets/template/src/weights.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2023-04-06, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `Alexs-MacBook-Pro-2.local`, CPU: `<UNKNOWN>`
//! HOSTNAME: `_`, CPU: `<UNKNOWN>`
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024

// Executed Command:
Expand Down
2 changes: 1 addition & 1 deletion templates/parachain/runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pallet-parachain-template = { path = "../pallets/template", default-features = f
frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true }
frame-executive = { path = "../../../substrate/frame/executive", default-features = false }
frame-metadata-hash-extension = { path = "../../../substrate/frame/metadata-hash-extension", default-features = false }
frame-support = { path = "../../../substrate/frame/support", default-features = false }
frame-support = { path = "../../../substrate/frame/support", default-features = false, features = ["experimental"] }
frame-system = { path = "../../../substrate/frame/system", default-features = false }
frame-system-benchmarking = { path = "../../../substrate/frame/system/benchmarking", default-features = false, optional = true }
frame-system-rpc-runtime-api = { path = "../../../substrate/frame/system/rpc/runtime-api", default-features = false }
Expand Down
107 changes: 66 additions & 41 deletions templates/parachain/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

pub mod apis;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarks;
gupnik marked this conversation as resolved.
Show resolved Hide resolved
mod configs;
mod weights;

Expand All @@ -22,12 +24,9 @@ use sp_std::prelude::*;
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;

use frame_support::{
construct_runtime,
weights::{
constants::WEIGHT_REF_TIME_PER_SECOND, Weight, WeightToFeeCoefficient,
WeightToFeeCoefficients, WeightToFeePolynomial,
},
use frame_support::weights::{
constants::WEIGHT_REF_TIME_PER_SECOND, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients,
WeightToFeePolynomial,
};
pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
pub use sp_runtime::{MultiAddress, Perbill, Permill};
Expand Down Expand Up @@ -232,43 +231,69 @@ pub fn native_version() -> NativeVersion {
}

// Create the runtime by composing the FRAME pallets that were previously configured.
construct_runtime!(
pub enum Runtime {
// System support stuff.
System: frame_system = 0,
ParachainSystem: cumulus_pallet_parachain_system = 1,
Timestamp: pallet_timestamp = 2,
ParachainInfo: parachain_info = 3,

// Monetary stuff.
Balances: pallet_balances = 10,
TransactionPayment: pallet_transaction_payment = 11,

// Governance
Sudo: pallet_sudo = 15,

// Collator support. The order of these 4 are important and shall not change.
Authorship: pallet_authorship = 20,
CollatorSelection: pallet_collator_selection = 21,
Session: pallet_session = 22,
Aura: pallet_aura = 23,
AuraExt: cumulus_pallet_aura_ext = 24,

// XCM helpers.
XcmpQueue: cumulus_pallet_xcmp_queue = 30,
PolkadotXcm: pallet_xcm = 31,
CumulusXcm: cumulus_pallet_xcm = 32,
MessageQueue: pallet_message_queue = 33,

// Template
TemplatePallet: pallet_parachain_template = 50,
}
);
#[frame_support::runtime]
mod runtime {
#[runtime::runtime]
#[runtime::derive(
RuntimeCall,
RuntimeEvent,
RuntimeError,
RuntimeOrigin,
RuntimeFreezeReason,
RuntimeHoldReason,
RuntimeSlashReason,
RuntimeLockId,
RuntimeTask
)]
pub struct Runtime;

#[runtime::pallet_index(0)]
pub type System = frame_system;
#[runtime::pallet_index(1)]
pub type ParachainSystem = cumulus_pallet_parachain_system;
#[runtime::pallet_index(2)]
pub type Timestamp = pallet_timestamp;
#[runtime::pallet_index(3)]
pub type ParachainInfo = parachain_info;

// Monetary stuff.
#[runtime::pallet_index(10)]
pub type Balances = pallet_balances;
#[runtime::pallet_index(11)]
pub type TransactionPayment = pallet_transaction_payment;

// Governance
#[runtime::pallet_index(15)]
pub type Sudo = pallet_sudo;

// Collator support. The order of these 4 are important and shall not change.
#[runtime::pallet_index(20)]
pub type Authorship = pallet_authorship;
#[runtime::pallet_index(21)]
pub type CollatorSelection = pallet_collator_selection;
#[runtime::pallet_index(22)]
pub type Session = pallet_session;
#[runtime::pallet_index(23)]
pub type Aura = pallet_aura;
#[runtime::pallet_index(24)]
pub type AuraExt = cumulus_pallet_aura_ext;

// XCM helpers.
#[runtime::pallet_index(30)]
pub type XcmpQueue = cumulus_pallet_xcmp_queue;
#[runtime::pallet_index(31)]
pub type PolkadotXcm = pallet_xcm;
#[runtime::pallet_index(32)]
pub type CumulusXcm = cumulus_pallet_xcm;
#[runtime::pallet_index(33)]
pub type MessageQueue = pallet_message_queue;

// Template
gupnik marked this conversation as resolved.
Show resolved Hide resolved
#[runtime::pallet_index(50)]
pub type TemplatePallet = pallet_parachain_template;
}

cumulus_pallet_parachain_system::register_validate_block! {
Runtime = Runtime,
BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
}

#[cfg(feature = "runtime-benchmarks")]
mod benchmarks;
Loading