referrerpolicy=no-referrer-when-downgrade

polkadot_sdk_docs/polkadot_sdk/
frame_runtime.rs

1//! # FRAME
2//!
3//! ```no_compile
4//!   ______   ______    ________   ___ __ __   ______
5//!  /_____/\ /_____/\  /_______/\ /__//_//_/\ /_____/\
6//!  \::::_\/_\:::_ \ \ \::: _  \ \\::\| \| \ \\::::_\/_
7//!   \:\/___/\\:(_) ) )_\::(_)  \ \\:.      \ \\:\/___/\
8//!    \:::._\/ \: __ `\ \\:: __  \ \\:.\-/\  \ \\::___\/_
9//!     \:\ \    \ \ `\ \ \\:.\ \  \ \\. \  \  \ \\:\____/\
10//!      \_\/     \_\/ \_\/ \__\/\__\/ \__\/ \__\/ \_____\/
11//! ```
12//!
13//! > **F**ramework for **R**untime **A**ggregation of **M**odularized **E**ntities: Substrate's
14//! > State Transition Function (Runtime) Framework.
15//!
16//! ## Introduction
17//!
18//! As described in [`crate::reference_docs::wasm_meta_protocol`], at a high-level Substrate-based
19//! blockchains are composed of two parts:
20//!
21//! 1. A *runtime* which represents the state transition function (i.e. "Business Logic") of a
22//! blockchain, and is encoded as a WASM blob.
23//! 2. A node whose primary purpose is to execute the given runtime.
24#![doc = simple_mermaid::mermaid!("../../../mermaid/substrate_simple.mmd")]
25//!
26//! *FRAME is the Substrate's framework of choice to build a runtime.*
27//!
28//! FRAME is composed of two major components, **pallets** and a **runtime**.
29//!
30//! ## Pallets
31//!
32//! A pallet is a unit of encapsulated logic. It has a clearly defined responsibility and can be
33//! linked to other pallets. In order to be reusable, pallets shipped with FRAME strive to only care
34//! about its own responsibilities and make as few assumptions about the general runtime as
35//! possible. A pallet is analogous to a _module_ in the runtime.
36//!
37//! A pallet is defined as a `mod pallet` wrapped by the [`frame::pallet`] macro. Within this macro,
38//! pallet components/parts can be defined. Most notable of these parts are:
39//!
40//! - [Config](frame::pallet_macros::config), allowing a pallet to make itself configurable and
41//!   generic over types, values and such.
42//! - [Storage](frame::pallet_macros::storage), allowing a pallet to define onchain storage.
43//! - [Dispatchable function](frame::pallet_macros::call), allowing a pallet to define extrinsics
44//!   that are callable by end users, from the outer world.
45//! - [Events](frame::pallet_macros::event), allowing a pallet to emit events.
46//! - [Errors](frame::pallet_macros::error), allowing a pallet to emit well-formed errors.
47//!
48//! Some of these pallet components resemble the building blocks of a smart contract. While both
49//! models are programming state transition functions of blockchains, there are crucial differences
50//! between the two. See [`crate::reference_docs::runtime_vs_smart_contract`] for more.
51//!
52//! Most of these components are defined using macros, the full list of which can be found in
53//! [`frame::pallet_macros`].
54//!
55//! ### Example
56//!
57//! The following example showcases a minimal pallet.
58#![doc = docify::embed!("src/polkadot_sdk/frame_runtime.rs", pallet)]
59//!
60//! ## Runtime
61//!
62//! A runtime is a collection of pallets that are amalgamated together. Each pallet typically has
63//! some configurations (exposed as a `trait Config`) that needs to be *specified* in the runtime.
64//! This is done with [`frame::runtime::prelude::construct_runtime`].
65//!
66//! A (real) runtime that actually wishes to compile to WASM needs to also implement a set of
67//! runtime-apis. These implementation can be specified using the
68//! [`frame::runtime::prelude::impl_runtime_apis`] macro.
69//!
70//! ### Example
71//!
72//! The following example shows a (test) runtime that is composing the pallet demonstrated above,
73//! next to the [`frame::prelude::frame_system`] pallet, into a runtime.
74#![doc = docify::embed!("src/polkadot_sdk/frame_runtime.rs", runtime)]
75//!
76//! ## More Examples
77//!
78//! You can find more FRAME examples that revolve around specific features at [`pallet_examples`].
79//!
80//! ## Alternatives 🌈
81//!
82//! There is nothing in the Substrate's node side code-base that mandates the use of FRAME. While
83//! FRAME makes it very simple to write Substrate-based runtimes, it is by no means intended to be
84//! the only one. At the end of the day, any WASM blob that exposes the right set of runtime APIs is
85//! a valid Runtime form the point of view of a Substrate client (see
86//! [`crate::reference_docs::wasm_meta_protocol`]). Notable examples are:
87//!
88//! * writing a runtime in pure Rust, as done in [this template](https://github.com/JoshOrndorff/frameless-node-template).
89//! * writing a runtime in AssemblyScript, as explored in [this project](https://github.com/LimeChain/subsembly).
90
91/// A FRAME based pallet. This `mod` is the entry point for everything else. All
92/// `#[pallet::xxx]` macros must be defined in this `mod`. Although, frame also provides an
93/// experimental feature to break these parts into different `mod`s. See [`pallet_examples`] for
94/// more.
95#[docify::export]
96#[frame::pallet(dev_mode)]
97pub mod pallet {
98	use frame::prelude::*;
99
100	/// The configuration trait of a pallet. Mandatory. Allows a pallet to receive types at a
101	/// later point from the runtime that wishes to contain it. It allows the pallet to be
102	/// parameterized over both types and values.
103	#[pallet::config]
104	pub trait Config: frame_system::Config {
105		/// A type that is not known now, but the runtime that will contain this pallet will
106		/// know it later, therefore we define it here as an associated type.
107		#[allow(deprecated)]
108		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;
109
110		/// A parameterize-able value that we receive later via the `Get<_>` trait.
111		type ValueParameter: Get<u32>;
112
113		/// Similar to [`Config::ValueParameter`], but using `const`. Both are functionally
114		/// equal, but offer different tradeoffs.
115		const ANOTHER_VALUE_PARAMETER: u32;
116	}
117
118	/// A mandatory struct in each pallet. All functions callable by external users (aka.
119	/// transactions) must be attached to this type (see [`frame::pallet_macros::call`]). For
120	/// convenience, internal (private) functions can also be attached to this type.
121	#[pallet::pallet]
122	pub struct Pallet<T>(PhantomData<T>);
123
124	/// The events that this pallet can emit.
125	#[pallet::event]
126	pub enum Event<T: Config> {}
127
128	/// A storage item that this pallet contains. This will be part of the state root trie
129	/// of the blockchain.
130	#[pallet::storage]
131	pub type Value<T> = StorageValue<Value = u32>;
132
133	/// All *dispatchable* call functions (aka. transactions) are attached to `Pallet` in a
134	/// `impl` block.
135	#[pallet::call]
136	impl<T: Config> Pallet<T> {
137		/// This will be callable by external users, and has two u32s as a parameter.
138		pub fn some_dispatchable(
139			_origin: OriginFor<T>,
140			_param: u32,
141			_other_para: u32,
142		) -> DispatchResult {
143			Ok(())
144		}
145	}
146}
147
148/// A simple runtime that contains the above pallet and `frame_system`, the mandatory pallet of
149/// all runtimes. This runtime is for testing, but it shares a lot of similarities with a *real*
150/// runtime.
151#[docify::export]
152pub mod runtime {
153	use super::pallet as pallet_example;
154	use frame::{prelude::*, testing_prelude::*};
155
156	// The major macro that amalgamates pallets into `enum Runtime`
157	construct_runtime!(
158		pub enum Runtime {
159			System: frame_system,
160			Example: pallet_example,
161		}
162	);
163
164	// These `impl` blocks specify the parameters of each pallet's `trait Config`.
165	#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
166	impl frame_system::Config for Runtime {
167		type Block = MockBlock<Self>;
168	}
169
170	impl pallet_example::Config for Runtime {
171		type RuntimeEvent = RuntimeEvent;
172		type ValueParameter = ConstU32<42>;
173		const ANOTHER_VALUE_PARAMETER: u32 = 42;
174	}
175}