referrerpolicy=no-referrer-when-downgrade

polkadot_sdk_docs/reference_docs/
frame_origin.rs

1//! # FRAME Origin
2//!
3//! Let's start by clarifying a common wrong assumption about Origin:
4//!
5//! **ORIGIN IS NOT AN ACCOUNT ID**.
6//!
7//! FRAME's origin abstractions allow you to convey meanings far beyond just an account-id being the
8//! caller of an extrinsic. Nonetheless, an account-id having signed an extrinsic is one of the
9//! meanings that an origin can convey. This is the commonly used [`frame_system::ensure_signed`],
10//! where the return value happens to be an account-id.
11//!
12//! Instead, let's establish the following as the correct definition of an origin:
13//!
14//! > The origin type represents the privilege level of the caller of an extrinsic.
15//!
16//! That is, an extrinsic, through checking the origin, can *express what privilege level it wishes
17//! to impose on the caller of the extrinsic*. One of those checks can be as simple as "*any account
18//! that has signed a statement can pass*".
19//!
20//! But the origin system can also express more abstract and complicated privilege levels. For
21//! example:
22//!
23//! * If the majority of token holders agreed upon this. This is more or less what the
24//!   [`pallet_democracy`] does under the hood ([reference](https://github.com/paritytech/polkadot-sdk/blob/edd95b3749754d2ed0c5738588e872c87be91624/substrate/frame/democracy/src/lib.rs#L1603-L1633)).
25//! * If a specific ratio of an instance of [`pallet_collective`]/DAO agrees upon this.
26//! * If another consensus system, for example a bridged network or a parachain, agrees upon this.
27//! * If the majority of validator/authority set agrees upon this[^1].
28//! * If caller holds a particular NFT.
29//!
30//! and many more.
31//!
32//! ## Context
33//!
34//! First, let's look at where the `origin` type is encountered in a typical pallet. The `origin:
35//! OriginFor<T>` has to be the first argument of any given callable extrinsic in FRAME:
36#![doc = docify::embed!("./src/reference_docs/frame_origin.rs", call_simple)]
37//!
38//! Typically, the code of an extrinsic starts with an origin check, such as
39//! [`frame_system::ensure_signed`].
40//!
41//! Note that [`OriginFor`](frame_system::pallet_prelude::OriginFor) is merely a shorthand for
42//! [`frame_system::Config::RuntimeOrigin`]. Given the name prefix `Runtime`, we can learn that
43//! `RuntimeOrigin` is similar to `RuntimeCall` and others, a runtime composite enum that is
44//! amalgamated at the runtime level. Read [`crate::reference_docs::frame_runtime_types`] to
45//! familiarize yourself with these types.
46//!
47//! To understand this better, we will next create a pallet with a custom origin, which will add a
48//! new variant to `RuntimeOrigin`.
49//!
50//! ## Adding Custom Pallet Origin to the Runtime
51//!
52//! For example, given a pallet that defines the following custom origin:
53#![doc = docify::embed!("./src/reference_docs/frame_origin.rs", custom_origin)]
54//!
55//! And a runtime with the following pallets:
56#![doc = docify::embed!("./src/reference_docs/frame_origin.rs", runtime_exp)]
57//!
58//! The type [`crate::reference_docs::frame_origin::runtime_for_origin::RuntimeOrigin`] is expanded.
59//! This `RuntimeOrigin` contains a variant for the [`frame_system::RawOrigin`] and the custom
60//! origin of the pallet.
61//!
62//! > Notice how the [`frame_system::ensure_signed`] is nothing more than a `match` statement. If
63//! > you want to know where the actual origin of an extrinsic is set (and the signature
64//! > verification happens, if any), see
65//! > [`sp_runtime::generic::CheckedExtrinsic#trait-implementations`], specifically
66//! > [`sp_runtime::traits::Applyable`]'s implementation.
67//!
68//! ## Asserting on a Custom Internal Origin
69//!
70//! In order to assert on a custom origin that is defined within your pallet, we need a way to first
71//! convert the `<T as frame_system::Config>::RuntimeOrigin` into the local `enum Origin` of the
72//! current pallet. This is a common process that is explained in
73//! [`crate::reference_docs::frame_runtime_types#
74//! adding-further-constraints-to-runtime-composite-enums`].
75//!
76//! We use the same process here to express that `RuntimeOrigin` has a number of additional bounds,
77//! as follows.
78//!
79//! 1. Defining a custom `RuntimeOrigin` with further bounds in the pallet.
80#![doc = docify::embed!("./src/reference_docs/frame_origin.rs", custom_origin_bound)]
81//!
82//! 2. Using it in the pallet.
83#![doc = docify::embed!("./src/reference_docs/frame_origin.rs", custom_origin_usage)]
84//!
85//! ## Asserting on a Custom External Origin
86//!
87//! Very often, a pallet wants to have a parameterized origin that is **NOT** defined within the
88//! pallet. In other words, a pallet wants to delegate an origin check to something that is
89//! specified later at the runtime level. Like many other parameterizations in FRAME, this implies
90//! adding a new associated type to `trait Config`.
91#![doc = docify::embed!("./src/reference_docs/frame_origin.rs", external_origin_def)]
92//!
93//! Then, within the pallet, we can simply use this "unknown" origin check type:
94#![doc = docify::embed!("./src/reference_docs/frame_origin.rs", external_origin_usage)]
95//!
96//! Finally, at the runtime, any implementation of [`frame::traits::EnsureOrigin`] can be passed.
97#![doc = docify::embed!("./src/reference_docs/frame_origin.rs", external_origin_provide)]
98//!
99//! Indeed, some of these implementations of [`frame::traits::EnsureOrigin`] are similar to the ones
100//! that we know about: [`frame::runtime::prelude::EnsureSigned`],
101//! [`frame::runtime::prelude::EnsureSignedBy`], [`frame::runtime::prelude::EnsureRoot`],
102//! [`frame::runtime::prelude::EnsureNone`], etc. But, there are also many more that are not known
103//! to us, and are defined in other pallets.
104//!
105//! For example, [`pallet_collective`] defines [`pallet_collective::EnsureMember`] and
106//! [`pallet_collective::EnsureProportionMoreThan`] and many more, which is exactly what we alluded
107//! to earlier in this document.
108//!
109//! Make sure to check the full list of [implementors of
110//! `EnsureOrigin`](frame::traits::EnsureOrigin#implementors) for more inspiration.
111//!
112//! ## Obtaining Abstract Origins
113//!
114//! So far we have learned that FRAME pallets can assert on custom and abstract origin types,
115//! whether they are defined within the pallet or not. But how can we obtain these abstract origins?
116//!
117//! > All extrinsics that come from the outer world can generally only be obtained as either
118//! > `signed` or `none` origin.
119//!
120//! Generally, these abstract origins are only obtained within the runtime, when a call is
121//! dispatched within the runtime.
122//!
123//! ## Further References
124//!
125//! - [Gavin Wood's speech about FRAME features at Protocol Berg 2023.](https://youtu.be/j7b8Upipmeg?si=83_XUgYuJxMwWX4g&t=195)
126//! - [A related StackExchange question.](https://substrate.stackexchange.com/questions/10992/how-do-you-find-the-public-key-for-the-medium-spender-track-origin)
127//!
128//! [^1]: Inherents are essentially unsigned extrinsics that need an [`frame_system::ensure_none`]
129//! origin check, and through the virtue of being an inherent, are agreed upon by all validators.
130
131use frame::prelude::*;
132
133#[frame::pallet(dev_mode)]
134pub mod pallet_for_origin {
135	use super::*;
136
137	#[pallet::config]
138	pub trait Config: frame_system::Config {}
139
140	#[pallet::pallet]
141	pub struct Pallet<T>(_);
142
143	#[docify::export(call_simple)]
144	#[pallet::call]
145	impl<T: Config> Pallet<T> {
146		pub fn do_something(_origin: OriginFor<T>) -> DispatchResult {
147			//              ^^^^^^^^^^^^^^^^^^^^^
148			todo!();
149		}
150	}
151}
152
153#[frame::pallet(dev_mode)]
154pub mod pallet_with_custom_origin {
155	use super::*;
156
157	#[docify::export(custom_origin_bound)]
158	#[pallet::config]
159	pub trait Config: frame_system::Config {
160		type RuntimeOrigin: From<<Self as frame_system::Config>::RuntimeOrigin>
161			+ Into<Result<Origin, <Self as Config>::RuntimeOrigin>>;
162	}
163
164	#[pallet::pallet]
165	pub struct Pallet<T>(_);
166
167	#[docify::export(custom_origin)]
168	/// A dummy custom origin.
169	#[pallet::origin]
170	#[derive(
171		PartialEq,
172		Eq,
173		Clone,
174		RuntimeDebug,
175		Encode,
176		Decode,
177		DecodeWithMemTracking,
178		TypeInfo,
179		MaxEncodedLen,
180	)]
181	pub enum Origin {
182		/// If all holders of a particular NFT have agreed upon this.
183		AllNftHolders,
184		/// If all validators have agreed upon this.
185		ValidatorSet,
186	}
187
188	#[docify::export(custom_origin_usage)]
189	#[pallet::call]
190	impl<T: Config> Pallet<T> {
191		pub fn only_validators(origin: OriginFor<T>) -> DispatchResult {
192			// first, we convert from `<T as frame_system::Config>::RuntimeOrigin` to `<T as
193			// Config>::RuntimeOrigin`
194			let local_runtime_origin = <<T as Config>::RuntimeOrigin as From<
195				<T as frame_system::Config>::RuntimeOrigin,
196			>>::from(origin);
197			// then we convert to `origin`, if possible
198			let local_origin =
199				local_runtime_origin.into().map_err(|_| "invalid origin type provided")?;
200			ensure!(matches!(local_origin, Origin::ValidatorSet), "Not authorized");
201			todo!();
202		}
203	}
204}
205
206pub mod runtime_for_origin {
207	use super::pallet_with_custom_origin;
208	use frame::{runtime::prelude::*, testing_prelude::*};
209
210	#[docify::export(runtime_exp)]
211	construct_runtime!(
212		pub struct Runtime {
213			System: frame_system,
214			PalletWithCustomOrigin: pallet_with_custom_origin,
215		}
216	);
217
218	#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
219	impl frame_system::Config for Runtime {
220		type Block = MockBlock<Self>;
221	}
222
223	impl pallet_with_custom_origin::Config for Runtime {
224		type RuntimeOrigin = RuntimeOrigin;
225	}
226}
227
228#[frame::pallet(dev_mode)]
229pub mod pallet_with_external_origin {
230	use super::*;
231	#[docify::export(external_origin_def)]
232	#[pallet::config]
233	pub trait Config: frame_system::Config {
234		type ExternalOrigin: EnsureOrigin<Self::RuntimeOrigin>;
235	}
236
237	#[pallet::pallet]
238	pub struct Pallet<T>(_);
239
240	#[docify::export(external_origin_usage)]
241	#[pallet::call]
242	impl<T: Config> Pallet<T> {
243		pub fn externally_checked_ext(origin: OriginFor<T>) -> DispatchResult {
244			T::ExternalOrigin::ensure_origin(origin)?;
245			todo!();
246		}
247	}
248}
249
250pub mod runtime_for_external_origin {
251	use super::*;
252	use frame::{runtime::prelude::*, testing_prelude::*};
253
254	construct_runtime!(
255		pub struct Runtime {
256			System: frame_system,
257			PalletWithExternalOrigin: pallet_with_external_origin,
258		}
259	);
260
261	#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
262	impl frame_system::Config for Runtime {
263		type Block = MockBlock<Self>;
264	}
265
266	#[docify::export(external_origin_provide)]
267	impl pallet_with_external_origin::Config for Runtime {
268		type ExternalOrigin = EnsureSigned<<Self as frame_system::Config>::AccountId>;
269	}
270}