From 7c847f8db6ab9ca9ef990c4cf61275415c78d106 Mon Sep 17 00:00:00 2001
From: Daan van der Plas <93204684+Daanvdplas@users.noreply.github.com>
Date: Tue, 18 Jun 2024 09:51:47 +0200
Subject: [PATCH] refactor: parachain template (#4684)

Update parachain template pallet based on polkadot sdk docs

@kianenigma

---------

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
---
 prdoc/pr_4684.prdoc                           |  13 +++
 .../parachain/pallets/template/src/lib.rs     |  42 ++++---
 .../parachain/pallets/template/src/mock.rs    |  45 +++++---
 .../parachain/pallets/template/src/weights.rs |   2 +-
 templates/parachain/runtime/Cargo.toml        |   2 +-
 templates/parachain/runtime/src/lib.rs        | 107 +++++++++++-------
 6 files changed, 133 insertions(+), 78 deletions(-)
 create mode 100644 prdoc/pr_4684.prdoc

diff --git a/prdoc/pr_4684.prdoc b/prdoc/pr_4684.prdoc
new file mode 100644
index 00000000000..b1c429c5782
--- /dev/null
+++ b/prdoc/pr_4684.prdoc
@@ -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
diff --git a/templates/parachain/pallets/template/src/lib.rs b/templates/parachain/pallets/template/src/lib.rs
index 11587d1df42..0420e2b9082 100644
--- a/templates/parachain/pallets/template/src/lib.rs
+++ b/templates/parachain/pallets/template/src/lib.rs
@@ -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)]
@@ -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::*};
@@ -25,7 +28,9 @@ 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;
 	}
@@ -33,24 +38,23 @@ pub mod pallet {
 	#[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.
@@ -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
@@ -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())
 		}
diff --git a/templates/parachain/pallets/template/src/mock.rs b/templates/parachain/pallets/template/src/mock.rs
index ebb0598df97..46e3117596f 100644
--- a/templates/parachain/pallets/template/src/mock.rs
+++ b/templates/parachain/pallets/template/src/mock.rs
@@ -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 {
@@ -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()
 }
diff --git a/templates/parachain/pallets/template/src/weights.rs b/templates/parachain/pallets/template/src/weights.rs
index 7c42936e09f..5bfe28e8b71 100644
--- a/templates/parachain/pallets/template/src/weights.rs
+++ b/templates/parachain/pallets/template/src/weights.rs
@@ -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:
diff --git a/templates/parachain/runtime/Cargo.toml b/templates/parachain/runtime/Cargo.toml
index 059c7936796..48d9f691289 100644
--- a/templates/parachain/runtime/Cargo.toml
+++ b/templates/parachain/runtime/Cargo.toml
@@ -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 }
diff --git a/templates/parachain/runtime/src/lib.rs b/templates/parachain/runtime/src/lib.rs
index 987b88af844..6e6491a19ad 100644
--- a/templates/parachain/runtime/src/lib.rs
+++ b/templates/parachain/runtime/src/lib.rs
@@ -7,6 +7,8 @@
 include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
 
 pub mod apis;
+#[cfg(feature = "runtime-benchmarks")]
+mod benchmarks;
 mod configs;
 mod weights;
 
@@ -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};
@@ -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
+	#[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;
-- 
GitLab