frame_support/lib.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Support code for the runtime.
19//!
20//! ## Note on Tuple Traits
21//!
22//! Many of the traits defined in [`traits`] have auto-implementations on tuples as well. Usually,
23//! the tuple is a function of number of pallets in the runtime. By default, the traits are
24//! implemented for tuples of up to 64 items.
25//
26// If you have more pallets in your runtime, or for any other reason need more, enabled `tuples-96`
27// or the `tuples-128` complication flag. Note that these features *will increase* the compilation
28// of this crate.
29
30#![cfg_attr(not(feature = "std"), no_std)]
31
32/// Export ourself as `frame_support` to make tests happy.
33#[doc(hidden)]
34extern crate self as frame_support;
35
36#[doc(hidden)]
37extern crate alloc;
38
39/// Private exports that are being used by macros.
40///
41/// The exports are not stable and should not be relied on.
42#[doc(hidden)]
43pub mod __private {
44 pub use alloc::{
45 boxed::Box,
46 fmt::Debug,
47 rc::Rc,
48 string::String,
49 vec,
50 vec::{IntoIter, Vec},
51 };
52 pub use codec;
53 pub use frame_metadata as metadata;
54 pub use log;
55 pub use paste;
56 pub use scale_info;
57 pub use serde;
58 pub use serde_json;
59 pub use sp_core::{Get, OpaqueMetadata, Void};
60 pub use sp_crypto_hashing_proc_macro;
61 pub use sp_inherents;
62 #[cfg(feature = "std")]
63 pub use sp_io::TestExternalities;
64 pub use sp_io::{self, hashing, storage::root as storage_root};
65 pub use sp_metadata_ir as metadata_ir;
66 #[cfg(feature = "std")]
67 pub use sp_runtime::{bounded_btree_map, bounded_vec};
68 pub use sp_runtime::{
69 traits::{AsSystemOriginSigner, AsTransactionAuthorizedOrigin, Dispatchable},
70 DispatchError, RuntimeDebug, StateVersion, TransactionOutcome,
71 };
72 #[cfg(feature = "std")]
73 pub use sp_state_machine::BasicExternalities;
74 pub use sp_std;
75 pub use sp_tracing;
76 pub use tt_call::*;
77}
78
79#[macro_use]
80pub mod dispatch;
81pub mod crypto;
82pub mod dispatch_context;
83mod hash;
84pub mod inherent;
85pub mod instances;
86pub mod migrations;
87pub mod storage;
88#[cfg(test)]
89mod tests;
90pub mod traits;
91pub mod view_functions;
92pub mod weights;
93#[doc(hidden)]
94pub mod unsigned {
95 #[doc(hidden)]
96 pub use crate::sp_runtime::traits::ValidateUnsigned;
97 #[doc(hidden)]
98 pub use crate::sp_runtime::transaction_validity::{
99 TransactionSource, TransactionValidity, TransactionValidityError, UnknownTransaction,
100 };
101}
102
103#[cfg(any(feature = "std", feature = "runtime-benchmarks", feature = "try-runtime", test))]
104pub use self::storage::storage_noop_guard::StorageNoopGuard;
105pub use self::{
106 dispatch::{Callable, Parameter},
107 hash::{
108 Blake2_128, Blake2_128Concat, Blake2_256, Hashable, Identity, ReversibleStorageHasher,
109 StorageHasher, Twox128, Twox256, Twox64Concat,
110 },
111 storage::{
112 bounded_btree_map::BoundedBTreeMap,
113 bounded_btree_set::BoundedBTreeSet,
114 bounded_vec::{BoundedSlice, BoundedVec},
115 migration,
116 weak_bounded_vec::WeakBoundedVec,
117 IterableStorageDoubleMap, IterableStorageMap, IterableStorageNMap, StorageDoubleMap,
118 StorageMap, StorageNMap, StoragePrefixedMap, StorageValue,
119 },
120};
121pub use sp_runtime::{
122 self, print, traits::Printable, ConsensusEngineId, MAX_MODULE_ERROR_ENCODED_SIZE,
123};
124
125use codec::{Decode, Encode};
126use scale_info::TypeInfo;
127use sp_runtime::TypeId;
128
129/// A unified log target for support operations.
130pub const LOG_TARGET: &str = "runtime::frame-support";
131
132/// A type that cannot be instantiated.
133#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
134pub enum Never {}
135
136/// A pallet identifier. These are per pallet and should be stored in a registry somewhere.
137#[derive(Clone, Copy, Eq, PartialEq, Encode, Decode, TypeInfo)]
138pub struct PalletId(pub [u8; 8]);
139
140impl TypeId for PalletId {
141 const TYPE_ID: [u8; 4] = *b"modl";
142}
143
144/// Generate a [`#[pallet::storage]`](pallet_macros::storage) alias outside of a pallet.
145///
146/// This storage alias works similarly to the [`#[pallet::storage]`](pallet_macros::storage)
147/// attribute macro. It supports [`StorageValue`](storage::types::StorageValue),
148/// [`StorageMap`](storage::types::StorageMap),
149/// [`StorageDoubleMap`](storage::types::StorageDoubleMap) and
150/// [`StorageNMap`](storage::types::StorageNMap). The main difference to the normal
151/// [`#[pallet::storage]`](pallet_macros::storage) is the flexibility around declaring the
152/// storage prefix to use. The storage prefix determines where to find the value in the
153/// storage. [`#[pallet::storage]`](pallet_macros::storage) uses the name of the pallet as
154/// declared in [`construct_runtime!`].
155///
156/// The flexibility around declaring the storage prefix makes this macro very useful for
157/// writing migrations etc.
158///
159/// # Examples
160///
161/// There are different ways to declare the `prefix` to use. The `prefix` type can either be
162/// declared explicitly by passing it to the macro as an attribute or by letting the macro
163/// guess on what the `prefix` type is. The `prefix` is always passed as the first generic
164/// argument to the type declaration. When using [`#[pallet::storage]`](pallet_macros::storage)
165/// this first generic argument is always `_`. Besides declaring the `prefix`, the rest of the
166/// type declaration works as with [`#[pallet::storage]`](pallet_macros::storage).
167///
168/// 1. Use the `verbatim` prefix type. This prefix type uses the given identifier as the
169/// `prefix`:
170#[doc = docify::embed!("src/tests/storage_alias.rs", verbatim_attribute)]
171///
172/// 2. Use the `pallet_name` prefix type. This prefix type uses the name of the pallet as
173/// configured in [`construct_runtime!`] as the `prefix`:
174#[doc = docify::embed!("src/tests/storage_alias.rs", pallet_name_attribute)]
175/// It requires that the given prefix type implements
176/// [`PalletInfoAccess`](traits::PalletInfoAccess) (which is always the case for FRAME pallet
177/// structs). In the example above, `Pallet<T>` is the prefix type.
178///
179/// 3. Use the `dynamic` prefix type. This prefix type calls [`Get::get()`](traits::Get::get)
180/// to get the `prefix`:
181#[doc = docify::embed!("src/tests/storage_alias.rs", dynamic_attribute)]
182/// It requires that the given prefix type implements [`Get<'static str>`](traits::Get).
183///
184/// 4. Let the macro "guess" what kind of prefix type to use. This only supports verbatim or
185/// pallet name. The macro uses the presence of generic arguments to the prefix type as an
186/// indication that it should use the pallet name as the `prefix`:
187#[doc = docify::embed!("src/tests/storage_alias.rs", storage_alias_guess)]
188pub use frame_support_procedural::storage_alias;
189
190pub use frame_support_procedural::derive_impl;
191
192/// Experimental macros for defining dynamic params that can be used in pallet configs.
193#[cfg(feature = "experimental")]
194pub mod dynamic_params {
195 pub use frame_support_procedural::{
196 dynamic_aggregated_params_internal, dynamic_pallet_params, dynamic_params,
197 };
198}
199
200/// Create new implementations of the [`Get`](crate::traits::Get) trait.
201///
202/// The so-called parameter type can be created in four different ways:
203///
204/// - Using `const` to create a parameter type that provides a `const` getter. It is required that
205/// the `value` is const.
206///
207/// - Declare the parameter type without `const` to have more freedom when creating the value.
208///
209/// - Using `storage` to create a storage parameter type. This type is special as it tries to load
210/// the value from the storage under a fixed key. If the value could not be found in the storage,
211/// the given default value will be returned. It is required that the value implements
212/// [`Encode`](codec::Encode) and [`Decode`](codec::Decode). The key for looking up the value in
213/// the storage is built using the following formula:
214///
215/// `twox_128(":" ++ NAME ++ ":")` where `NAME` is the name that is passed as type name.
216///
217/// - Using `static` to create a static parameter type. Its value is being provided by a static
218/// variable with the equivalent name in `UPPER_SNAKE_CASE`. An additional `set` function is
219/// provided in this case to alter the static variable. **This is intended for testing ONLY and is
220/// ONLY available when `std` is enabled.**
221///
222/// # Examples
223///
224/// ```
225/// # use frame_support::traits::Get;
226/// # use frame_support::parameter_types;
227/// // This function cannot be used in a const context.
228/// fn non_const_expression() -> u64 { 99 }
229///
230/// const FIXED_VALUE: u64 = 10;
231/// parameter_types! {
232/// pub const Argument: u64 = 42 + FIXED_VALUE;
233/// /// Visibility of the type is optional
234/// OtherArgument: u64 = non_const_expression();
235/// pub storage StorageArgument: u64 = 5;
236/// pub static StaticArgument: u32 = 7;
237/// }
238///
239/// trait Config {
240/// type Parameter: Get<u64>;
241/// type OtherParameter: Get<u64>;
242/// type StorageParameter: Get<u64>;
243/// type StaticParameter: Get<u32>;
244/// }
245///
246/// struct Runtime;
247/// impl Config for Runtime {
248/// type Parameter = Argument;
249/// type OtherParameter = OtherArgument;
250/// type StorageParameter = StorageArgument;
251/// type StaticParameter = StaticArgument;
252/// }
253///
254/// // In testing, `StaticArgument` can be altered later: `StaticArgument::set(8)`.
255/// ```
256///
257/// # Invalid example:
258///
259/// ```compile_fail
260/// # use frame_support::traits::Get;
261/// # use frame_support::parameter_types;
262/// // This function cannot be used in a const context.
263/// fn non_const_expression() -> u64 { 99 }
264///
265/// parameter_types! {
266/// pub const Argument: u64 = non_const_expression();
267/// }
268/// ```
269#[macro_export]
270macro_rules! parameter_types {
271 (
272 $( #[ $attr:meta ] )*
273 $vis:vis const $name:ident $(< $($ty_params:ident),* >)?: $type:ty = $value:expr;
274 $( $rest:tt )*
275 ) => (
276 $( #[ $attr ] )*
277 $vis struct $name $(
278 < $($ty_params),* >( $(core::marker::PhantomData<$ty_params>),* )
279 )?;
280 $crate::parameter_types!(IMPL_CONST $name , $type , $value $( $(, $ty_params)* )?);
281 $crate::parameter_types!( $( $rest )* );
282 );
283 (
284 $( #[ $attr:meta ] )*
285 $vis:vis $name:ident $(< $($ty_params:ident),* >)?: $type:ty = $value:expr;
286 $( $rest:tt )*
287 ) => (
288 $( #[ $attr ] )*
289 $vis struct $name $(
290 < $($ty_params),* >( $(core::marker::PhantomData<$ty_params>),* )
291 )?;
292 $crate::parameter_types!(IMPL $name, $type, $value $( $(, $ty_params)* )?);
293 $crate::parameter_types!( $( $rest )* );
294 );
295 (
296 $( #[ $attr:meta ] )*
297 $vis:vis storage $name:ident $(< $($ty_params:ident),* >)?: $type:ty = $value:expr;
298 $( $rest:tt )*
299 ) => (
300 $( #[ $attr ] )*
301 $vis struct $name $(
302 < $($ty_params),* >( $(core::marker::PhantomData<$ty_params>),* )
303 )?;
304 $crate::parameter_types!(IMPL_STORAGE $name, $type, $value $( $(, $ty_params)* )?);
305 $crate::parameter_types!( $( $rest )* );
306 );
307 () => ();
308 (IMPL_CONST $name:ident, $type:ty, $value:expr $(, $ty_params:ident)*) => {
309 impl< $($ty_params),* > $name< $($ty_params),* > {
310 /// Returns the value of this parameter type.
311 pub const fn get() -> $type {
312 $value
313 }
314 }
315
316 impl<_I: From<$type> $(, $ty_params)*> $crate::traits::Get<_I> for $name< $($ty_params),* > {
317 fn get() -> _I {
318 _I::from(Self::get())
319 }
320 }
321
322 impl< $($ty_params),* > $crate::traits::TypedGet for $name< $($ty_params),* > {
323 type Type = $type;
324 fn get() -> $type {
325 Self::get()
326 }
327 }
328 };
329 (IMPL $name:ident, $type:ty, $value:expr $(, $ty_params:ident)*) => {
330 impl< $($ty_params),* > $name< $($ty_params),* > {
331 /// Returns the value of this parameter type.
332 pub fn get() -> $type {
333 $value
334 }
335 }
336
337 impl<_I: From<$type>, $(, $ty_params)*> $crate::traits::Get<_I> for $name< $($ty_params),* > {
338 fn get() -> _I {
339 _I::from(Self::get())
340 }
341 }
342
343 impl< $($ty_params),* > $crate::traits::TypedGet for $name< $($ty_params),* > {
344 type Type = $type;
345 fn get() -> $type {
346 Self::get()
347 }
348 }
349 };
350 (IMPL_STORAGE $name:ident, $type:ty, $value:expr $(, $ty_params:ident)*) => {
351 #[allow(unused)]
352 impl< $($ty_params),* > $name< $($ty_params),* > {
353 /// Returns the key for this parameter type.
354 pub fn key() -> [u8; 16] {
355 $crate::__private::sp_crypto_hashing_proc_macro::twox_128!(b":", $name, b":")
356 }
357
358 /// Set the value of this parameter type in the storage.
359 ///
360 /// This needs to be executed in an externalities provided environment.
361 pub fn set(value: &$type) {
362 $crate::storage::unhashed::put(&Self::key(), value);
363 }
364
365 /// Returns the value of this parameter type.
366 ///
367 /// This needs to be executed in an externalities provided environment.
368 #[allow(unused)]
369 pub fn get() -> $type {
370 $crate::storage::unhashed::get(&Self::key()).unwrap_or_else(|| $value)
371 }
372 }
373
374 impl<_I: From<$type> $(, $ty_params)*> $crate::traits::Get<_I> for $name< $($ty_params),* > {
375 fn get() -> _I {
376 _I::from(Self::get())
377 }
378 }
379
380 impl< $($ty_params),* > $crate::traits::TypedGet for $name< $($ty_params),* > {
381 type Type = $type;
382 fn get() -> $type {
383 Self::get()
384 }
385 }
386 };
387 (
388 $( #[ $attr:meta ] )*
389 $vis:vis static $name:ident: $type:ty = $value:expr;
390 $( $rest:tt )*
391 ) => (
392 $crate::parameter_types_impl_thread_local!(
393 $( #[ $attr ] )*
394 $vis static $name: $type = $value;
395 );
396 $crate::parameter_types!( $( $rest )* );
397 );
398}
399
400#[cfg(not(feature = "std"))]
401#[macro_export]
402macro_rules! parameter_types_impl_thread_local {
403 ( $( $any:tt )* ) => {
404 compile_error!("static parameter types is only available in std and for testing.");
405 };
406}
407
408#[cfg(feature = "std")]
409#[macro_export]
410macro_rules! parameter_types_impl_thread_local {
411 (
412 $(
413 $( #[ $attr:meta ] )*
414 $vis:vis static $name:ident: $type:ty = $value:expr;
415 )*
416 ) => {
417 $crate::parameter_types_impl_thread_local!(
418 IMPL_THREAD_LOCAL $( $vis, $name, $type, $value, )*
419 );
420 $crate::__private::paste::item! {
421 $crate::parameter_types!(
422 $(
423 $( #[ $attr ] )*
424 $vis $name: $type = [<$name:snake:upper>].with(|v| v.borrow().clone());
425 )*
426 );
427 $(
428 impl $name {
429 /// Set the internal value.
430 pub fn set(t: $type) {
431 [<$name:snake:upper>].with(|v| *v.borrow_mut() = t);
432 }
433
434 /// Mutate the internal value in place.
435 #[allow(unused)]
436 pub fn mutate<R, F: FnOnce(&mut $type) -> R>(mutate: F) -> R{
437 let mut current = Self::get();
438 let result = mutate(&mut current);
439 Self::set(current);
440 result
441 }
442
443 /// Get current value and replace with initial value of the parameter type.
444 #[allow(unused)]
445 pub fn take() -> $type {
446 let current = Self::get();
447 Self::set($value);
448 current
449 }
450 }
451 )*
452 }
453 };
454 (IMPL_THREAD_LOCAL $( $vis:vis, $name:ident, $type:ty, $value:expr, )* ) => {
455 $crate::__private::paste::item! {
456 thread_local! {
457 $(
458 pub static [<$name:snake:upper>]: std::cell::RefCell<$type> =
459 std::cell::RefCell::new($value);
460 )*
461 }
462 }
463 };
464}
465
466/// Macro for easily creating a new implementation of both the `Get` and `Contains` traits. Use
467/// exactly as with `parameter_types`, only the type must be `Ord`.
468#[macro_export]
469macro_rules! ord_parameter_types {
470 (
471 $( #[ $attr:meta ] )*
472 $vis:vis const $name:ident: $type:ty = $value:expr;
473 $( $rest:tt )*
474 ) => (
475 $( #[ $attr ] )*
476 $vis struct $name;
477 $crate::parameter_types!{IMPL $name , $type , $value}
478 $crate::ord_parameter_types!{IMPL $name , $type , $value}
479 $crate::ord_parameter_types!{ $( $rest )* }
480 );
481 () => ();
482 (IMPL $name:ident , $type:ty , $value:expr) => {
483 impl $crate::traits::SortedMembers<$type> for $name {
484 fn contains(t: &$type) -> bool { &$value == t }
485 fn sorted_members() -> $crate::__private::Vec<$type> { vec![$value] }
486 fn count() -> usize { 1 }
487 #[cfg(feature = "runtime-benchmarks")]
488 fn add(_: &$type) {}
489 }
490 impl $crate::traits::Contains<$type> for $name {
491 fn contains(t: &$type) -> bool { &$value == t }
492 }
493 }
494}
495
496/// Print out a formatted message.
497///
498/// # Example
499///
500/// ```
501/// frame_support::runtime_print!("my value is {}", 3);
502/// ```
503#[macro_export]
504macro_rules! runtime_print {
505 ($($arg:tt)+) => {
506 {
507 use core::fmt::Write;
508 let mut msg = $crate::__private::String::default();
509 let _ = core::write!(&mut msg, $($arg)+);
510 $crate::__private::sp_io::misc::print_utf8(msg.as_bytes())
511 }
512 }
513}
514
515/// Print out the debuggable type.
516pub fn debug(data: &impl core::fmt::Debug) {
517 runtime_print!("{:?}", data);
518}
519
520#[doc(inline)]
521pub use frame_support_procedural::{
522 construct_runtime, match_and_insert, transactional, PalletError, RuntimeDebugNoBound,
523};
524
525pub use frame_support_procedural::runtime;
526
527#[doc(hidden)]
528pub use frame_support_procedural::{__create_tt_macro, __generate_dummy_part_checker};
529
530/// Derive [`Clone`] but do not bound any generic.
531///
532/// This is useful for type generic over runtime:
533/// ```
534/// # use frame_support::CloneNoBound;
535/// trait Config {
536/// type C: Clone;
537/// }
538///
539/// // Foo implements [`Clone`] because `C` bounds [`Clone`].
540/// // Otherwise compilation will fail with an output telling `c` doesn't implement [`Clone`].
541/// #[derive(CloneNoBound)]
542/// struct Foo<T: Config> {
543/// c: T::C,
544/// }
545/// ```
546pub use frame_support_procedural::CloneNoBound;
547
548/// Derive [`Eq`] but do not bound any generic.
549///
550/// This is useful for type generic over runtime:
551/// ```
552/// # use frame_support::{EqNoBound, PartialEqNoBound};
553/// trait Config {
554/// type C: Eq;
555/// }
556///
557/// // Foo implements [`Eq`] because `C` bounds [`Eq`].
558/// // Otherwise compilation will fail with an output telling `c` doesn't implement [`Eq`].
559/// #[derive(PartialEqNoBound, EqNoBound)]
560/// struct Foo<T: Config> {
561/// c: T::C,
562/// }
563/// ```
564pub use frame_support_procedural::EqNoBound;
565
566/// Derive [`PartialEq`] but do not bound any generic.
567///
568/// This is useful for type generic over runtime:
569/// ```
570/// # use frame_support::PartialEqNoBound;
571/// trait Config {
572/// type C: PartialEq;
573/// }
574///
575/// // Foo implements [`PartialEq`] because `C` bounds [`PartialEq`].
576/// // Otherwise compilation will fail with an output telling `c` doesn't implement [`PartialEq`].
577/// #[derive(PartialEqNoBound)]
578/// struct Foo<T: Config> {
579/// c: T::C,
580/// }
581/// ```
582pub use frame_support_procedural::PartialEqNoBound;
583
584/// Derive [`Ord`] but do not bound any generic.
585///
586/// This is useful for type generic over runtime:
587/// ```
588/// # use frame_support::{OrdNoBound, PartialOrdNoBound, EqNoBound, PartialEqNoBound};
589/// trait Config {
590/// type C: Ord;
591/// }
592///
593/// // Foo implements [`Ord`] because `C` bounds [`Ord`].
594/// // Otherwise compilation will fail with an output telling `c` doesn't implement [`Ord`].
595/// #[derive(EqNoBound, OrdNoBound, PartialEqNoBound, PartialOrdNoBound)]
596/// struct Foo<T: Config> {
597/// c: T::C,
598/// }
599/// ```
600pub use frame_support_procedural::OrdNoBound;
601
602/// Derive [`PartialOrd`] but do not bound any generic.
603///
604/// This is useful for type generic over runtime:
605/// ```
606/// # use frame_support::{OrdNoBound, PartialOrdNoBound, EqNoBound, PartialEqNoBound};
607/// trait Config {
608/// type C: PartialOrd;
609/// }
610///
611/// // Foo implements [`PartialOrd`] because `C` bounds [`PartialOrd`].
612/// // Otherwise compilation will fail with an output telling `c` doesn't implement [`PartialOrd`].
613/// #[derive(PartialOrdNoBound, PartialEqNoBound, EqNoBound)]
614/// struct Foo<T: Config> {
615/// c: T::C,
616/// }
617/// ```
618pub use frame_support_procedural::PartialOrdNoBound;
619
620/// Derive [`Debug`] but do not bound any generic.
621///
622/// This is useful for type generic over runtime:
623/// ```
624/// # use frame_support::DebugNoBound;
625/// # use core::fmt::Debug;
626/// trait Config {
627/// type C: Debug;
628/// }
629///
630/// // Foo implements [`Debug`] because `C` bounds [`Debug`].
631/// // Otherwise compilation will fail with an output telling `c` doesn't implement [`Debug`].
632/// #[derive(DebugNoBound)]
633/// struct Foo<T: Config> {
634/// c: T::C,
635/// }
636/// ```
637pub use frame_support_procedural::DebugNoBound;
638
639/// Derive [`Default`] but do not bound any generic.
640///
641/// This is useful for type generic over runtime:
642/// ```
643/// # use frame_support::DefaultNoBound;
644/// # use core::default::Default;
645/// trait Config {
646/// type C: Default;
647/// }
648///
649/// // Foo implements [`Default`] because `C` bounds [`Default`].
650/// // Otherwise compilation will fail with an output telling `c` doesn't implement [`Default`].
651/// #[derive(DefaultNoBound)]
652/// struct Foo<T: Config> {
653/// c: T::C,
654/// }
655///
656/// // Also works with enums, by specifying the default with #[default]:
657/// #[derive(DefaultNoBound)]
658/// enum Bar<T: Config> {
659/// // Bar will implement Default as long as all of the types within Baz also implement default.
660/// #[default]
661/// Baz(T::C),
662/// Quxx,
663/// }
664/// ```
665pub use frame_support_procedural::DefaultNoBound;
666
667/// Assert the annotated function is executed within a storage transaction.
668///
669/// The assertion is enabled for native execution and when `debug_assertions` are enabled.
670///
671/// # Example
672///
673/// ```
674/// # use frame_support::{
675/// # require_transactional, transactional, dispatch::DispatchResult
676/// # };
677///
678/// #[require_transactional]
679/// fn update_all(value: u32) -> DispatchResult {
680/// // Update multiple storages.
681/// // Return `Err` to indicate should revert.
682/// Ok(())
683/// }
684///
685/// #[transactional]
686/// fn safe_update(value: u32) -> DispatchResult {
687/// // This is safe
688/// update_all(value)
689/// }
690///
691/// fn unsafe_update(value: u32) -> DispatchResult {
692/// // this may panic if unsafe_update is not called within a storage transaction
693/// update_all(value)
694/// }
695/// ```
696pub use frame_support_procedural::require_transactional;
697
698/// Convert the current crate version into a [`CrateVersion`](crate::traits::CrateVersion).
699///
700/// It uses the `CARGO_PKG_VERSION_MAJOR`, `CARGO_PKG_VERSION_MINOR` and
701/// `CARGO_PKG_VERSION_PATCH` environment variables to fetch the crate version.
702/// This means that the [`CrateVersion`](crate::traits::CrateVersion)
703/// object will correspond to the version of the crate the macro is called in!
704///
705/// # Example
706///
707/// ```
708/// # use frame_support::{traits::CrateVersion, crate_to_crate_version};
709/// const Version: CrateVersion = crate_to_crate_version!();
710/// ```
711pub use frame_support_procedural::crate_to_crate_version;
712
713/// Return Err of the expression: `return Err($expression);`.
714///
715/// Used as `fail!(expression)`.
716#[macro_export]
717macro_rules! fail {
718 ( $y:expr ) => {{
719 return Err($y.into());
720 }};
721}
722
723/// Evaluate `$x:expr` and if not true return `Err($y:expr)`.
724///
725/// Used as `ensure!(expression_to_ensure, expression_to_return_on_false)`.
726#[macro_export]
727macro_rules! ensure {
728 ( $x:expr, $y:expr $(,)? ) => {{
729 if !$x {
730 $crate::fail!($y);
731 }
732 }};
733}
734
735/// Evaluate an expression, assert it returns an expected `Err` value and that
736/// runtime storage has not been mutated (i.e. expression is a no-operation).
737///
738/// Used as `assert_noop(expression_to_assert, expected_error_expression)`.
739#[macro_export]
740macro_rules! assert_noop {
741 (
742 $x:expr,
743 $y:expr $(,)?
744 ) => {
745 let h = $crate::__private::storage_root($crate::__private::StateVersion::V1);
746 $crate::assert_err!($x, $y);
747 assert_eq!(
748 h,
749 $crate::__private::storage_root($crate::__private::StateVersion::V1),
750 "storage has been mutated"
751 );
752 };
753}
754
755/// Evaluate any expression and assert that runtime storage has not been mutated
756/// (i.e. expression is a storage no-operation).
757///
758/// Used as `assert_storage_noop(expression_to_assert)`.
759#[macro_export]
760macro_rules! assert_storage_noop {
761 (
762 $x:expr
763 ) => {
764 let h = $crate::__private::storage_root($crate::__private::StateVersion::V1);
765 $x;
766 assert_eq!(h, $crate::__private::storage_root($crate::__private::StateVersion::V1));
767 };
768}
769
770/// Assert an expression returns an error specified.
771///
772/// Used as `assert_err!(expression_to_assert, expected_error_expression)`
773#[macro_export]
774macro_rules! assert_err {
775 ( $x:expr , $y:expr $(,)? ) => {
776 assert_eq!($x, Err($y.into()));
777 };
778}
779
780/// Assert an expression returns an error specified.
781///
782/// This can be used on `DispatchResultWithPostInfo` when the post info should
783/// be ignored.
784#[macro_export]
785macro_rules! assert_err_ignore_postinfo {
786 ( $x:expr , $y:expr $(,)? ) => {
787 $crate::assert_err!($x.map(|_| ()).map_err(|e| e.error), $y);
788 };
789}
790
791/// Assert an expression returns error with the given weight.
792#[macro_export]
793macro_rules! assert_err_with_weight {
794 ($call:expr, $err:expr, $weight:expr $(,)? ) => {
795 if let Err(dispatch_err_with_post) = $call {
796 $crate::assert_err!($call.map(|_| ()).map_err(|e| e.error), $err);
797 assert_eq!(dispatch_err_with_post.post_info.actual_weight, $weight);
798 } else {
799 ::core::panic!("expected Err(_), got Ok(_).")
800 }
801 };
802}
803
804/// Panic if an expression doesn't evaluate to `Ok`.
805///
806/// Used as `assert_ok!(expression_to_assert, expected_ok_expression)`,
807/// or `assert_ok!(expression_to_assert)` which would assert against `Ok(())`.
808#[macro_export]
809macro_rules! assert_ok {
810 ( $x:expr $(,)? ) => {
811 let is = $x;
812 match is {
813 Ok(_) => (),
814 _ => assert!(false, "Expected Ok(_). Got {:#?}", is),
815 }
816 };
817 ( $x:expr, $y:expr $(,)? ) => {
818 assert_eq!($x, Ok($y));
819 };
820}
821
822/// Assert that the maximum encoding size does not exceed the value defined in
823/// [`MAX_MODULE_ERROR_ENCODED_SIZE`] during compilation.
824///
825/// This macro is intended to be used in conjunction with `tt_call!`.
826#[macro_export]
827macro_rules! assert_error_encoded_size {
828 {
829 path = [{ $($path:ident)::+ }]
830 runtime = [{ $runtime:ident }]
831 assert_message = [{ $assert_message:literal }]
832 error = [{ $error:ident }]
833 } => {
834 const _: () = assert!(
835 <
836 $($path::)+$error<$runtime> as $crate::traits::PalletError
837 >::MAX_ENCODED_SIZE <= $crate::MAX_MODULE_ERROR_ENCODED_SIZE,
838 $assert_message
839 );
840 };
841 {
842 path = [{ $($path:ident)::+ }]
843 runtime = [{ $runtime:ident }]
844 assert_message = [{ $assert_message:literal }]
845 } => {};
846}
847
848/// Do something hypothetically by rolling back any changes afterwards.
849///
850/// Returns the original result of the closure.
851#[macro_export]
852#[cfg(feature = "experimental")]
853macro_rules! hypothetically {
854 ( $e:expr ) => {
855 $crate::storage::transactional::with_transaction(|| -> $crate::__private::TransactionOutcome<Result<_, $crate::__private::DispatchError>> {
856 $crate::__private::TransactionOutcome::Rollback(Ok($e))
857 },
858 ).expect("Always returning Ok; qed")
859 };
860}
861
862/// Assert something to be *hypothetically* `Ok`, without actually committing it.
863///
864/// Reverts any storage changes made by the closure.
865#[macro_export]
866#[cfg(feature = "experimental")]
867macro_rules! hypothetically_ok {
868 ($e:expr $(, $args:expr)* $(,)?) => {
869 $crate::assert_ok!($crate::hypothetically!($e) $(, $args)*);
870 };
871}
872
873#[doc(hidden)]
874pub use serde::{Deserialize, Serialize};
875
876#[doc(hidden)]
877pub use macro_magic;
878
879/// Prelude to be used for pallet testing, for ease of use.
880#[cfg(feature = "std")]
881pub mod testing_prelude {
882 pub use super::{
883 assert_err, assert_err_ignore_postinfo, assert_err_with_weight, assert_error_encoded_size,
884 assert_noop, assert_ok, assert_storage_noop, parameter_types, traits::Get,
885 };
886 pub use sp_arithmetic::assert_eq_error_rate;
887 pub use sp_runtime::{bounded_btree_map, bounded_vec};
888}
889
890/// Prelude to be used alongside pallet macro, for ease of use.
891pub mod pallet_prelude {
892 pub use crate::{
893 defensive, defensive_assert,
894 dispatch::{DispatchClass, DispatchResult, DispatchResultWithPostInfo, Parameter, Pays},
895 ensure,
896 inherent::{InherentData, InherentIdentifier, ProvideInherent},
897 storage,
898 storage::{
899 bounded_btree_map::BoundedBTreeMap,
900 bounded_btree_set::BoundedBTreeSet,
901 bounded_vec::BoundedVec,
902 types::{
903 CountedStorageMap, CountedStorageNMap, Key as NMapKey, OptionQuery, ResultQuery,
904 StorageDoubleMap, StorageMap, StorageNMap, StorageValue, ValueQuery,
905 },
906 weak_bounded_vec::WeakBoundedVec,
907 StorageList,
908 },
909 traits::{
910 BuildGenesisConfig, ConstU32, ConstUint, EnsureOrigin, Get, GetDefault,
911 GetStorageVersion, Hooks, IsType, OriginTrait, PalletInfoAccess, StorageInfoTrait,
912 StorageVersion, Task, TypedGet,
913 },
914 Blake2_128, Blake2_128Concat, Blake2_256, CloneNoBound, DebugNoBound, EqNoBound, Identity,
915 PartialEqNoBound, RuntimeDebugNoBound, Twox128, Twox256, Twox64Concat,
916 };
917 pub use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
918 pub use core::marker::PhantomData;
919 pub use frame_support::pallet_macros::*;
920 pub use frame_support_procedural::{inject_runtime_type, register_default_impl};
921 pub use scale_info::TypeInfo;
922 pub use sp_inherents::MakeFatalError;
923 pub use sp_runtime::{
924 traits::{
925 CheckedAdd, CheckedConversion, CheckedDiv, CheckedMul, CheckedShl, CheckedShr,
926 CheckedSub, MaybeSerializeDeserialize, Member, One, ValidateUnsigned, Zero,
927 },
928 transaction_validity::{
929 InvalidTransaction, TransactionLongevity, TransactionPriority, TransactionSource,
930 TransactionTag, TransactionValidity, TransactionValidityError, UnknownTransaction,
931 ValidTransaction,
932 },
933 DispatchError, RuntimeDebug, MAX_MODULE_ERROR_ENCODED_SIZE,
934 };
935 pub use sp_weights::Weight;
936}
937
938/// The pallet macro has 2 purposes:
939///
940/// * [For declaring a pallet as a rust module](#1---pallet-module-declaration)
941/// * [For declaring the `struct` placeholder of a
942/// pallet](#2---pallet-struct-placeholder-declaration)
943///
944/// # 1 - Pallet module declaration
945///
946/// The module to declare a pallet is organized as follows:
947/// ```
948/// #[frame_support::pallet] // <- the macro
949/// mod pallet {
950/// #[pallet::pallet]
951/// pub struct Pallet<T>(_);
952///
953/// #[pallet::config]
954/// pub trait Config: frame_system::Config {}
955///
956/// #[pallet::call]
957/// impl<T: Config> Pallet<T> {
958/// }
959///
960/// /* ... */
961/// }
962/// ```
963///
964/// The documentation for each individual part can be found at [frame_support::pallet_macros]
965///
966/// ## Dev Mode (`#[pallet(dev_mode)]`)
967///
968/// Syntax:
969///
970/// ```
971/// #[frame_support::pallet(dev_mode)]
972/// mod pallet {
973/// # #[pallet::pallet]
974/// # pub struct Pallet<T>(_);
975/// # #[pallet::config]
976/// # pub trait Config: frame_system::Config {}
977/// /* ... */
978/// }
979/// ```
980///
981/// Specifying the argument `dev_mode` will allow you to enable dev mode for a pallet. The
982/// aim of dev mode is to loosen some of the restrictions and requirements placed on
983/// production pallets for easy tinkering and development. Dev mode pallets should not be
984/// used in production. Enabling dev mode has the following effects:
985///
986/// * Weights no longer need to be specified on every `#[pallet::call]` declaration. By
987/// default, dev mode pallets will assume a weight of zero (`0`) if a weight is not
988/// specified. This is equivalent to specifying `#[weight(0)]` on all calls that do not
989/// specify a weight.
990/// * Call indices no longer need to be specified on every `#[pallet::call]` declaration. By
991/// default, dev mode pallets will assume a call index based on the order of the call.
992/// * All storages are marked as unbounded, meaning you do not need to implement
993/// [`MaxEncodedLen`](frame_support::pallet_prelude::MaxEncodedLen) on storage types. This is
994/// equivalent to specifying `#[pallet::unbounded]` on all storage type definitions.
995/// * Storage hashers no longer need to be specified and can be replaced by `_`. In dev mode,
996/// these will be replaced by `Blake2_128Concat`. In case of explicit key-binding, `Hasher`
997/// can simply be ignored when in `dev_mode`.
998///
999/// Note that the `dev_mode` argument can only be supplied to the `#[pallet]` or
1000/// `#[frame_support::pallet]` attribute macro that encloses your pallet module. This
1001/// argument cannot be specified anywhere else, including but not limited to the
1002/// `#[pallet::pallet]` attribute macro.
1003///
1004/// <div class="example-wrap" style="display:inline-block"><pre class="compile_fail"
1005/// style="white-space:normal;font:inherit;">
1006/// <strong>WARNING</strong>:
1007/// You should never deploy or use dev mode pallets in production. Doing so can break your
1008/// chain. Once you are done tinkering, you should
1009/// remove the 'dev_mode' argument from your #[pallet] declaration and fix any compile
1010/// errors before attempting to use your pallet in a production scenario.
1011/// </pre></div>
1012///
1013/// # 2 - Pallet struct placeholder declaration
1014///
1015/// The pallet struct placeholder `#[pallet::pallet]` is mandatory and allows you to
1016/// specify pallet information.
1017///
1018/// The struct must be defined as follows:
1019/// ```
1020/// #[frame_support::pallet]
1021/// mod pallet {
1022/// #[pallet::pallet] // <- the macro
1023/// pub struct Pallet<T>(_); // <- the struct definition
1024///
1025/// #[pallet::config]
1026/// pub trait Config: frame_system::Config {}
1027/// }
1028/// ```
1029//
1030/// I.e. a regular struct definition named `Pallet`, with generic T and no where clause.
1031///
1032/// ## Macro expansion:
1033///
1034/// The macro adds this attribute to the Pallet struct definition:
1035/// ```ignore
1036/// #[derive(
1037/// frame_support::CloneNoBound,
1038/// frame_support::EqNoBound,
1039/// frame_support::PartialEqNoBound,
1040/// frame_support::RuntimeDebugNoBound,
1041/// )]
1042/// ```
1043/// and replaces the type `_` with `PhantomData<T>`.
1044///
1045/// It also implements on the pallet:
1046///
1047/// * [`GetStorageVersion`](frame_support::traits::GetStorageVersion)
1048/// * [`OnGenesis`](frame_support::traits::OnGenesis): contains some logic to write the pallet
1049/// version into storage.
1050/// * [`PalletInfoAccess`](frame_support::traits::PalletInfoAccess) to ease access to pallet
1051/// information given by [`frame_support::traits::PalletInfo`]. (The implementation uses the
1052/// associated type [`frame_support::traits::PalletInfo`]).
1053/// * [`StorageInfoTrait`](frame_support::traits::StorageInfoTrait) to give information about
1054/// storages.
1055///
1056/// If the attribute `set_storage_max_encoded_len` is set then the macro calls
1057/// [`StorageInfoTrait`](frame_support::traits::StorageInfoTrait) for each storage in the
1058/// implementation of [`StorageInfoTrait`](frame_support::traits::StorageInfoTrait) for the
1059/// pallet. Otherwise, it implements
1060/// [`StorageInfoTrait`](frame_support::traits::StorageInfoTrait) for the pallet using the
1061/// [`PartialStorageInfoTrait`](frame_support::traits::PartialStorageInfoTrait)
1062/// implementation of storages.
1063///
1064/// ## Note on deprecation.
1065///
1066/// - Usage of `deprecated` attribute will propagate deprecation information to the pallet
1067/// metadata.
1068/// - For general usage examples of `deprecated` attribute please refer to <https://doc.rust-lang.org/nightly/reference/attributes/diagnostics.html#the-deprecated-attribute>
1069pub use frame_support_procedural::pallet;
1070
1071/// Contains macro stubs for all of the `pallet::` macros
1072pub mod pallet_macros {
1073 /// Declare the storage as whitelisted from benchmarking.
1074 ///
1075 /// Doing so will exclude reads of that value's storage key from counting towards weight
1076 /// calculations during benchmarking.
1077 ///
1078 /// This attribute should only be attached to storages that are known to be
1079 /// read/used in every block. This will result in a more accurate benchmarking weight.
1080 ///
1081 /// ### Example
1082 /// ```
1083 /// #[frame_support::pallet]
1084 /// mod pallet {
1085 /// # use frame_support::pallet_prelude::*;
1086 /// #
1087 /// #[pallet::pallet]
1088 /// pub struct Pallet<T>(_);
1089 ///
1090 /// #[pallet::storage]
1091 /// #[pallet::whitelist_storage]
1092 /// pub type MyStorage<T> = StorageValue<_, u32>;
1093 /// #
1094 /// # #[pallet::config]
1095 /// # pub trait Config: frame_system::Config {}
1096 /// }
1097 /// ```
1098 pub use frame_support_procedural::whitelist_storage;
1099
1100 /// Allows specifying the weight of a call.
1101 ///
1102 /// Each dispatchable needs to define a weight.
1103 /// This attribute allows to define a weight using the expression:
1104 /// `#[pallet::weight($expr)]` Note that argument of the call are available inside the
1105 /// expression.
1106 ///
1107 /// If not defined explicitly, the weight can be implicitly inferred from the weight info
1108 /// defined in the attribute `pallet::call`: `#[pallet::call(weight = $WeightInfo)]`.
1109 /// Or it can be simply ignored when the pallet is in `dev_mode`.
1110 ///
1111 /// ## Example
1112 ///
1113 /// ```
1114 /// #[frame_support::pallet]
1115 /// mod pallet {
1116 /// use frame_support::pallet_prelude::*;
1117 /// use frame_system::pallet_prelude::*;
1118 ///
1119 /// #[pallet::pallet]
1120 /// pub struct Pallet<T>(_);
1121 ///
1122 /// #[pallet::config]
1123 /// pub trait Config: frame_system::Config {
1124 /// /// Type for specifying dispatchable weights.
1125 /// type WeightInfo: WeightInfo;
1126 /// }
1127 ///
1128 /// #[pallet::call(weight = <T as Config>::WeightInfo)]
1129 /// impl<T: Config> Pallet<T> {
1130 /// // Explicit weight definition
1131 /// #[pallet::weight(<T as Config>::WeightInfo::do_something())]
1132 /// #[pallet::call_index(0)]
1133 /// pub fn do_something(
1134 /// origin: OriginFor<T>,
1135 /// foo: u32,
1136 /// ) -> DispatchResult {
1137 /// Ok(())
1138 /// }
1139 ///
1140 /// // Implicit weight definition, the macro looks up to the weight info defined in
1141 /// // `#[pallet::call(weight = $WeightInfo)]` attribute. Then use
1142 /// // `$WeightInfo::do_something_else` as the weight function.
1143 /// #[pallet::call_index(1)]
1144 /// pub fn do_something_else(
1145 /// origin: OriginFor<T>,
1146 /// bar: u64,
1147 /// ) -> DispatchResult {
1148 /// Ok(())
1149 /// }
1150 /// }
1151 ///
1152 /// /// The `WeightInfo` trait defines weight functions for dispatchable calls.
1153 /// pub trait WeightInfo {
1154 /// fn do_something() -> Weight;
1155 /// fn do_something_else() -> Weight;
1156 /// }
1157 /// }
1158 /// ```
1159 pub use frame_support_procedural::weight;
1160
1161 /// Allows whitelisting a storage item from decoding during try-runtime checks.
1162 ///
1163 /// The optional attribute `#[pallet::disable_try_decode_storage]` will declare the
1164 /// storage as whitelisted from decoding during try-runtime checks. This should only be
1165 /// attached to transient storage which cannot be migrated during runtime upgrades.
1166 ///
1167 /// ### Example
1168 /// ```
1169 /// #[frame_support::pallet]
1170 /// mod pallet {
1171 /// # use frame_support::pallet_prelude::*;
1172 /// #
1173 /// #[pallet::pallet]
1174 /// pub struct Pallet<T>(_);
1175 ///
1176 /// #[pallet::storage]
1177 /// #[pallet::disable_try_decode_storage]
1178 /// pub type MyStorage<T> = StorageValue<_, u32>;
1179 /// #
1180 /// # #[pallet::config]
1181 /// # pub trait Config: frame_system::Config {}
1182 /// }
1183 /// ```
1184 pub use frame_support_procedural::disable_try_decode_storage;
1185
1186 /// Declares a storage as unbounded in potential size.
1187 ///
1188 /// When implementing the storage info (when `#[pallet::generate_storage_info]` is
1189 /// specified on the pallet struct placeholder), the size of the storage will be declared
1190 /// as unbounded. This can be useful for storage which can never go into PoV (Proof of
1191 /// Validity).
1192 ///
1193 /// ## Example
1194 ///
1195 /// ```
1196 /// #[frame_support::pallet]
1197 /// mod pallet {
1198 /// # use frame_support::pallet_prelude::*;
1199 /// #
1200 /// #[pallet::pallet]
1201 /// pub struct Pallet<T>(_);
1202 ///
1203 /// #[pallet::storage]
1204 /// #[pallet::unbounded]
1205 /// pub type MyStorage<T> = StorageValue<_, u32>;
1206 /// #
1207 /// # #[pallet::config]
1208 /// # pub trait Config: frame_system::Config {}
1209 /// }
1210 /// ```
1211 pub use frame_support_procedural::unbounded;
1212
1213 /// Defines what storage prefix to use for a storage item when building the trie.
1214 ///
1215 /// This is helpful if you wish to rename the storage field but don't want to perform a
1216 /// migration.
1217 ///
1218 /// ## Example
1219 ///
1220 /// ```
1221 /// #[frame_support::pallet]
1222 /// mod pallet {
1223 /// # use frame_support::pallet_prelude::*;
1224 /// #
1225 /// #[pallet::pallet]
1226 /// pub struct Pallet<T>(_);
1227 ///
1228 /// #[pallet::storage]
1229 /// #[pallet::storage_prefix = "foo"]
1230 /// pub type MyStorage<T> = StorageValue<_, u32>;
1231 /// #
1232 /// # #[pallet::config]
1233 /// # pub trait Config: frame_system::Config {}
1234 /// }
1235 /// ```
1236 pub use frame_support_procedural::storage_prefix;
1237
1238 /// Ensures the generated `DefaultConfig` will not have any bounds for
1239 /// that trait item.
1240 ///
1241 /// Attaching this attribute to a trait item ensures that the generated trait
1242 /// `DefaultConfig` will not have any bounds for this trait item.
1243 ///
1244 /// As an example, if you have a trait item `type AccountId: SomeTrait;` in your `Config`
1245 /// trait, the generated `DefaultConfig` will only have `type AccountId;` with no trait
1246 /// bound.
1247 pub use frame_support_procedural::no_default_bounds;
1248
1249 /// Ensures the trait item will not be used as a default with the
1250 /// `#[derive_impl(..)]` attribute macro.
1251 ///
1252 /// The optional attribute `#[pallet::no_default]` can be attached to trait items within a
1253 /// `Config` trait impl that has [`#[pallet::config(with_default)]`](`config`)
1254 /// attached.
1255 pub use frame_support_procedural::no_default;
1256
1257 /// Declares a module as importable into a pallet via
1258 /// [`#[import_section]`](`import_section`).
1259 ///
1260 /// Note that sections are imported by their module name/ident, and should be referred to
1261 /// by their _full path_ from the perspective of the target pallet. Do not attempt to make
1262 /// use of `use` statements to bring pallet sections into scope, as this will not work
1263 /// (unless you do so as part of a wildcard import, in which case it will work).
1264 ///
1265 /// ## Naming Logistics
1266 ///
1267 /// Also note that because of how `#[pallet_section]` works, pallet section names must be
1268 /// globally unique _within the crate in which they are defined_. For more information on
1269 /// why this must be the case, see macro_magic's
1270 /// [`#[export_tokens]`](https://docs.rs/macro_magic/latest/macro_magic/attr.export_tokens.html) macro.
1271 ///
1272 /// Optionally, you may provide an argument to `#[pallet_section]` such as
1273 /// `#[pallet_section(some_ident)]`, in the event that there is another pallet section in
1274 /// same crate with the same ident/name. The ident you specify can then be used instead of
1275 /// the module's ident name when you go to import it via
1276 /// [`#[import_section]`](`import_section`).
1277 pub use frame_support_procedural::pallet_section;
1278
1279 /// The `#[pallet::inherent]` attribute allows the pallet to provide
1280 /// [inherents](https://docs.substrate.io/fundamentals/transaction-types/#inherent-transactions).
1281 ///
1282 /// An inherent is some piece of data that is inserted by a block authoring node at block
1283 /// creation time and can either be accepted or rejected by validators based on whether the
1284 /// data falls within an acceptable range.
1285 ///
1286 /// The most common inherent is the `timestamp` that is inserted into every block. Since
1287 /// there is no way to validate timestamps, validators simply check that the timestamp
1288 /// reported by the block authoring node falls within an acceptable range.
1289 ///
1290 /// Example usage:
1291 ///
1292 /// ```
1293 /// #[frame_support::pallet]
1294 /// mod pallet {
1295 /// # use frame_support::pallet_prelude::*;
1296 /// # use frame_support::inherent::IsFatalError;
1297 /// # use sp_timestamp::InherentError;
1298 /// # use core::result;
1299 /// #
1300 /// // Example inherent identifier
1301 /// pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"timstap0";
1302 ///
1303 /// #[pallet::pallet]
1304 /// pub struct Pallet<T>(_);
1305 ///
1306 /// #[pallet::inherent]
1307 /// impl<T: Config> ProvideInherent for Pallet<T> {
1308 /// type Call = Call<T>;
1309 /// type Error = InherentError;
1310 /// const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
1311 ///
1312 /// fn create_inherent(data: &InherentData) -> Option<Self::Call> {
1313 /// unimplemented!()
1314 /// }
1315 ///
1316 /// fn check_inherent(
1317 /// call: &Self::Call,
1318 /// data: &InherentData,
1319 /// ) -> result::Result<(), Self::Error> {
1320 /// unimplemented!()
1321 /// }
1322 ///
1323 /// fn is_inherent(call: &Self::Call) -> bool {
1324 /// unimplemented!()
1325 /// }
1326 /// }
1327 /// #
1328 /// # #[pallet::config]
1329 /// # pub trait Config: frame_system::Config {}
1330 /// }
1331 /// ```
1332 ///
1333 /// I.e. a trait implementation with bound `T: Config`, of trait `ProvideInherent` for type
1334 /// `Pallet<T>`, and some optional where clause.
1335 ///
1336 /// ## Macro expansion
1337 ///
1338 /// The macro currently makes no use of this information, but it might use this information
1339 /// in the future to give information directly to `construct_runtime`.
1340 pub use frame_support_procedural::inherent;
1341
1342 /// Splits a pallet declaration into multiple parts.
1343 ///
1344 /// An attribute macro that can be attached to a module declaration. Doing so will
1345 /// import the contents of the specified external pallet section that is defined
1346 /// elsewhere using [`#[pallet_section]`](`pallet_section`).
1347 ///
1348 /// ## Example
1349 /// ```
1350 /// # use frame_support::pallet_macros::pallet_section;
1351 /// # use frame_support::pallet_macros::import_section;
1352 /// #
1353 /// /// A [`pallet_section`] that defines the events for a pallet.
1354 /// /// This can later be imported into the pallet using [`import_section`].
1355 /// #[pallet_section]
1356 /// mod events {
1357 /// #[pallet::event]
1358 /// #[pallet::generate_deposit(pub(super) fn deposit_event)]
1359 /// pub enum Event<T: Config> {
1360 /// /// Event documentation should end with an array that provides descriptive names for event
1361 /// /// parameters. [something, who]
1362 /// SomethingStored { something: u32, who: T::AccountId },
1363 /// }
1364 /// }
1365 ///
1366 /// #[import_section(events)]
1367 /// #[frame_support::pallet]
1368 /// mod pallet {
1369 /// # use frame_support::pallet_prelude::*;
1370 /// #
1371 /// #[pallet::pallet]
1372 /// pub struct Pallet<T>(_);
1373 /// #
1374 /// # #[pallet::config]
1375 /// # pub trait Config: frame_system::Config {
1376 /// # type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
1377 /// # }
1378 /// }
1379 /// ```
1380 ///
1381 /// This will result in the contents of `some_section` being _verbatim_ imported into
1382 /// the pallet above. Note that since the tokens for `some_section` are essentially
1383 /// copy-pasted into the target pallet, you cannot refer to imports that don't also
1384 /// exist in the target pallet, but this is easily resolved by including all relevant
1385 /// `use` statements within your pallet section, so they are imported as well, or by
1386 /// otherwise ensuring that you have the same imports on the target pallet.
1387 ///
1388 /// It is perfectly permissible to import multiple pallet sections into the same pallet,
1389 /// which can be done by having multiple `#[import_section(something)]` attributes
1390 /// attached to the pallet.
1391 ///
1392 /// Note that sections are imported by their module name/ident, and should be referred to
1393 /// by their _full path_ from the perspective of the target pallet.
1394 pub use frame_support_procedural::import_section;
1395
1396 /// Allows defining getter functions on `Pallet` storage.
1397 ///
1398 /// ## Example
1399 ///
1400 /// ```
1401 /// #[frame_support::pallet]
1402 /// mod pallet {
1403 /// # use frame_support::pallet_prelude::*;
1404 /// #
1405 /// #[pallet::pallet]
1406 /// pub struct Pallet<T>(_);
1407 ///
1408 /// #[pallet::storage]
1409 /// #[pallet::getter(fn my_getter_fn_name)]
1410 /// pub type MyStorage<T> = StorageValue<_, u32>;
1411 /// #
1412 /// # #[pallet::config]
1413 /// # pub trait Config: frame_system::Config {}
1414 /// }
1415 /// ```
1416 ///
1417 /// See [`pallet::storage`](`frame_support::pallet_macros::storage`) for more info.
1418 pub use frame_support_procedural::getter;
1419
1420 /// Defines constants that are added to the constant field of
1421 /// [`PalletMetadata`](frame_metadata::v15::PalletMetadata) struct for this pallet.
1422 ///
1423 /// Must be defined like:
1424 ///
1425 /// ```
1426 /// #[frame_support::pallet]
1427 /// mod pallet {
1428 /// # use frame_support::pallet_prelude::*;
1429 /// #
1430 /// #[pallet::pallet]
1431 /// pub struct Pallet<T>(_);
1432 ///
1433 /// # #[pallet::config]
1434 /// # pub trait Config: frame_system::Config {}
1435 /// #
1436 /// #[pallet::extra_constants]
1437 /// impl<T: Config> Pallet<T> // $optional_where_clause
1438 /// {
1439 /// #[pallet::constant_name(SomeU32ConstantName)]
1440 /// /// Some doc
1441 /// fn some_u32_constant() -> u32 {
1442 /// 100u32
1443 /// }
1444 /// }
1445 /// }
1446 /// ```
1447 ///
1448 /// I.e. a regular rust `impl` block with some optional where clause and functions with 0
1449 /// args, 0 generics, and some return type.
1450 pub use frame_support_procedural::extra_constants;
1451
1452 #[rustfmt::skip]
1453 /// Allows bypassing the `frame_system::Config` supertrait check.
1454 ///
1455 /// To bypass the syntactic `frame_system::Config` supertrait check, use the attribute
1456 /// `pallet::disable_frame_system_supertrait_check`.
1457 ///
1458 /// Note this bypass is purely syntactic, and does not actually remove the requirement that your
1459 /// pallet implements `frame_system::Config`. When using this check, your config is still required to implement
1460 /// `frame_system::Config` either via
1461 /// - Implementing a trait that itself implements `frame_system::Config`
1462 /// - Tightly coupling it with another pallet which itself implements `frame_system::Config`
1463 ///
1464 /// e.g.
1465 ///
1466 /// ```
1467 /// #[frame_support::pallet]
1468 /// mod pallet {
1469 /// # use frame_support::pallet_prelude::*;
1470 /// # use frame_system::pallet_prelude::*;
1471 /// trait OtherTrait: frame_system::Config {}
1472 ///
1473 /// #[pallet::pallet]
1474 /// pub struct Pallet<T>(_);
1475 ///
1476 /// #[pallet::config]
1477 /// #[pallet::disable_frame_system_supertrait_check]
1478 /// pub trait Config: OtherTrait {}
1479 /// }
1480 /// ```
1481 ///
1482 /// To learn more about supertraits, see the
1483 /// [trait_based_programming](../../polkadot_sdk_docs/reference_docs/trait_based_programming/index.html)
1484 /// reference doc.
1485 pub use frame_support_procedural::disable_frame_system_supertrait_check;
1486
1487 /// The mandatory attribute allowing definition of configurable types for the pallet.
1488 ///
1489 /// Item must be defined as:
1490 ///
1491 /// ```
1492 /// #[frame_support::pallet]
1493 /// mod pallet {
1494 /// # use frame_support::pallet_prelude::*;
1495 /// #
1496 /// #[pallet::pallet]
1497 /// pub struct Pallet<T>(_);
1498 ///
1499 /// #[pallet::config]
1500 /// pub trait Config: frame_system::Config // + $optionally_some_other_supertraits
1501 /// // $optional_where_clause
1502 /// {
1503 /// // config items here
1504 /// }
1505 /// }
1506 /// ```
1507 ///
1508 /// I.e. a regular trait definition named `Config`, with the supertrait
1509 /// [`frame_system::pallet::Config`](../../frame_system/pallet/trait.Config.html), and
1510 /// optionally other supertraits and a where clause. (Specifying other supertraits here is
1511 /// known as [tight coupling](https://docs.substrate.io/reference/how-to-guides/pallet-design/use-tight-coupling/))
1512 ///
1513 /// The associated type `RuntimeEvent` is reserved. If defined, it must have the bounds
1514 /// `From<Event>` and `IsType<<Self as frame_system::Config>::RuntimeEvent>`.
1515 ///
1516 /// [`#[pallet::event]`](`event`) must be present if `RuntimeEvent`
1517 /// exists as a config item in your `#[pallet::config]`.
1518 ///
1519 /// ## Optional: `with_default`
1520 ///
1521 /// An optional `with_default` argument may also be specified. Doing so will automatically
1522 /// generate a `DefaultConfig` trait inside your pallet which is suitable for use with
1523 /// [`#[derive_impl(..)`](`frame_support::derive_impl`) to derive a default testing
1524 /// config:
1525 ///
1526 /// ```
1527 /// #[frame_support::pallet]
1528 /// mod pallet {
1529 /// # use frame_support::pallet_prelude::*;
1530 /// # use frame_system::pallet_prelude::*;
1531 /// # use core::fmt::Debug;
1532 /// # use frame_support::traits::Contains;
1533 /// #
1534 /// # pub trait SomeMoreComplexBound {}
1535 /// #
1536 /// #[pallet::pallet]
1537 /// pub struct Pallet<T>(_);
1538 ///
1539 /// #[pallet::config(with_default)] // <- with_default is optional
1540 /// pub trait Config: frame_system::Config {
1541 /// /// The overarching event type.
1542 /// #[pallet::no_default_bounds] // Default with bounds is not supported for RuntimeEvent
1543 /// type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
1544 ///
1545 /// /// A more complex type.
1546 /// #[pallet::no_default] // Example of type where no default should be provided
1547 /// type MoreComplexType: SomeMoreComplexBound;
1548 ///
1549 /// /// A simple type.
1550 /// // Default with bounds is supported for simple types
1551 /// type SimpleType: From<u32>;
1552 /// }
1553 ///
1554 /// #[pallet::event]
1555 /// pub enum Event<T: Config> {
1556 /// SomeEvent(u16, u32),
1557 /// }
1558 /// }
1559 /// ```
1560 ///
1561 /// As shown above:
1562 /// * you may attach the [`#[pallet::no_default]`](`no_default`)
1563 /// attribute to specify that a particular trait item _cannot_ be used as a default when a
1564 /// test `Config` is derived using the [`#[derive_impl(..)]`](`frame_support::derive_impl`)
1565 /// attribute macro. This will cause that particular trait item to simply not appear in
1566 /// default testing configs based on this config (the trait item will not be included in
1567 /// `DefaultConfig`).
1568 /// * you may attach the [`#[pallet::no_default_bounds]`](`no_default_bounds`)
1569 /// attribute to specify that a particular trait item can be used as a default when a
1570 /// test `Config` is derived using the [`#[derive_impl(..)]`](`frame_support::derive_impl`)
1571 /// attribute macro. But its bounds cannot be enforced at this point and should be
1572 /// discarded when generating the default config trait.
1573 /// * you may not specify any attribute to generate a trait item in the default config
1574 /// trait.
1575 ///
1576 /// In case origin of error is not clear it is recommended to disable all default with
1577 /// [`#[pallet::no_default]`](`no_default`) and enable them one by one.
1578 ///
1579 /// ### `DefaultConfig` Caveats
1580 ///
1581 /// The auto-generated `DefaultConfig` trait:
1582 /// - is always a _subset_ of your pallet's `Config` trait.
1583 /// - can only contain items that don't rely on externalities, such as
1584 /// `frame_system::Config`.
1585 ///
1586 /// Trait items that _do_ rely on externalities should be marked with
1587 /// [`#[pallet::no_default]`](`no_default`)
1588 ///
1589 /// Consequently:
1590 /// - Any items that rely on externalities _must_ be marked with
1591 /// [`#[pallet::no_default]`](`no_default`) or your trait will fail to compile when used
1592 /// with [`derive_impl`](`frame_support::derive_impl`).
1593 /// - Items marked with [`#[pallet::no_default]`](`no_default`) are entirely excluded from
1594 /// the `DefaultConfig` trait, and therefore any impl of `DefaultConfig` doesn't need to
1595 /// implement such items.
1596 ///
1597 /// For more information, see:
1598 /// * [`frame_support::derive_impl`].
1599 /// * [`#[pallet::no_default]`](`no_default`)
1600 /// * [`#[pallet::no_default_bounds]`](`no_default_bounds`)
1601 ///
1602 /// ## Optional: `without_automatic_metadata`
1603 ///
1604 /// By default, the associated types of the `Config` trait that require the `TypeInfo` or
1605 /// `Parameter` bounds are included in the metadata of the pallet.
1606 ///
1607 /// The optional `without_automatic_metadata` argument can be used to exclude these
1608 /// associated types from the metadata collection.
1609 ///
1610 /// Furthermore, the `without_automatic_metadata` argument can be used in combination with
1611 /// the [`#[pallet::include_metadata]`](`include_metadata`) attribute to selectively
1612 /// include only certain associated types in the metadata collection.
1613 ///
1614 /// ```
1615 /// #[frame_support::pallet]
1616 /// mod pallet {
1617 /// # use frame_support::pallet_prelude::*;
1618 /// # use frame_system::pallet_prelude::*;
1619 /// # use core::fmt::Debug;
1620 /// # use frame_support::traits::Contains;
1621 /// #
1622 /// # pub trait SomeMoreComplexBound {}
1623 /// #
1624 /// #[pallet::pallet]
1625 /// pub struct Pallet<T>(_);
1626 ///
1627 /// #[pallet::config(with_default, without_automatic_metadata)] // <- with_default and without_automatic_metadata are optional
1628 /// pub trait Config: frame_system::Config {
1629 /// /// The overarching event type.
1630 /// #[pallet::no_default_bounds] // Default with bounds is not supported for RuntimeEvent
1631 /// type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
1632 ///
1633 /// /// A simple type.
1634 /// // Type that would have been included in metadata, but is now excluded.
1635 /// type SimpleType: From<u32> + TypeInfo;
1636 ///
1637 /// // The `pallet::include_metadata` is used to selectively include this type in metadata.
1638 /// #[pallet::include_metadata]
1639 /// type SelectivelyInclude: From<u32> + TypeInfo;
1640 /// }
1641 ///
1642 /// #[pallet::event]
1643 /// pub enum Event<T: Config> {
1644 /// SomeEvent(u16, u32),
1645 /// }
1646 /// }
1647 /// ```
1648 pub use frame_support_procedural::config;
1649
1650 /// Allows defining an enum that gets composed as an aggregate enum by `construct_runtime`.
1651 ///
1652 /// The `#[pallet::composite_enum]` attribute allows you to define an enum that gets
1653 /// composed as an aggregate enum by `construct_runtime`. This is similar in principle with
1654 /// [frame_support_procedural::event] and [frame_support_procedural::error].
1655 ///
1656 /// The attribute currently only supports enum definitions, and identifiers that are named
1657 /// `FreezeReason`, `HoldReason`, `LockId` or `SlashReason`. Arbitrary identifiers for the
1658 /// enum are not supported. The aggregate enum generated by
1659 /// [`frame_support::construct_runtime`] will have the name of `RuntimeFreezeReason`,
1660 /// `RuntimeHoldReason`, `RuntimeLockId` and `RuntimeSlashReason` respectively.
1661 ///
1662 /// NOTE: The aggregate enum generated by `construct_runtime` generates a conversion
1663 /// function from the pallet enum to the aggregate enum, and automatically derives the
1664 /// following traits:
1665 ///
1666 /// ```ignore
1667 /// Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, MaxEncodedLen, TypeInfo,
1668 /// RuntimeDebug
1669 /// ```
1670 ///
1671 /// For ease of usage, when no `#[derive]` attributes are found for the enum under
1672 /// [`#[pallet::composite_enum]`](composite_enum), the aforementioned traits are
1673 /// automatically derived for it. The inverse is also true: if there are any `#[derive]`
1674 /// attributes found for the enum, then no traits will automatically be derived for it.
1675 ///
1676 /// e.g, defining `HoldReason` in a pallet
1677 ///
1678 /// ```
1679 /// #[frame_support::pallet]
1680 /// mod pallet {
1681 /// # use frame_support::pallet_prelude::*;
1682 /// #
1683 /// #[pallet::pallet]
1684 /// pub struct Pallet<T>(_);
1685 ///
1686 /// #[pallet::composite_enum]
1687 /// pub enum HoldReason {
1688 /// /// The NIS Pallet has reserved it for a non-fungible receipt.
1689 /// #[codec(index = 0)]
1690 /// SomeHoldReason,
1691 /// #[codec(index = 1)]
1692 /// SomeOtherHoldReason,
1693 /// }
1694 /// #
1695 /// # #[pallet::config]
1696 /// # pub trait Config: frame_system::Config {}
1697 /// }
1698 pub use frame_support_procedural::composite_enum;
1699
1700 /// Allows the pallet to validate unsigned transactions.
1701 ///
1702 /// Item must be defined as:
1703 ///
1704 /// ```
1705 /// #[frame_support::pallet]
1706 /// mod pallet {
1707 /// # use frame_support::pallet_prelude::*;
1708 /// #
1709 /// #[pallet::pallet]
1710 /// pub struct Pallet<T>(_);
1711 ///
1712 /// #[pallet::validate_unsigned]
1713 /// impl<T: Config> sp_runtime::traits::ValidateUnsigned for Pallet<T> {
1714 /// type Call = Call<T>;
1715 ///
1716 /// fn validate_unsigned(_source: TransactionSource, _call: &Self::Call) -> TransactionValidity {
1717 /// // Your implementation details here
1718 /// unimplemented!()
1719 /// }
1720 /// }
1721 /// #
1722 /// # #[pallet::config]
1723 /// # pub trait Config: frame_system::Config {}
1724 /// }
1725 /// ```
1726 ///
1727 /// I.e. a trait implementation with bound `T: Config`, of trait
1728 /// [`ValidateUnsigned`](frame_support::pallet_prelude::ValidateUnsigned) for
1729 /// type `Pallet<T>`, and some optional where clause.
1730 ///
1731 /// NOTE: There is also the [`sp_runtime::traits::TransactionExtension`] trait that can be
1732 /// used to add some specific logic for transaction validation.
1733 ///
1734 /// ## Macro expansion
1735 ///
1736 /// The macro currently makes no use of this information, but it might use this information
1737 /// in the future to give information directly to [`frame_support::construct_runtime`].
1738 pub use frame_support_procedural::validate_unsigned;
1739
1740 /// Allows defining view functions on a pallet.
1741 ///
1742 /// A pallet view function is a read-only function providing access to the state of the
1743 /// pallet from both outside and inside the runtime. It should provide a _stable_ interface
1744 /// for querying the state of the pallet, avoiding direct storage access and upgrading
1745 /// along with the runtime.
1746 ///
1747 /// ## Syntax
1748 /// View functions methods must be read-only and always return some output. A
1749 /// `view_functions_experimental` impl block only allows methods to be defined inside of
1750 /// it.
1751 ///
1752 /// ## Example
1753 /// ```
1754 /// #[frame_support::pallet]
1755 /// pub mod pallet {
1756 /// use frame_support::pallet_prelude::*;
1757 ///
1758 /// #[pallet::config]
1759 /// pub trait Config: frame_system::Config {}
1760 ///
1761 /// #[pallet::pallet]
1762 /// pub struct Pallet<T>(_);
1763 ///
1764 /// #[pallet::storage]
1765 /// pub type SomeMap<T: Config> = StorageMap<_, Twox64Concat, u32, u32, OptionQuery>;
1766 ///
1767 /// #[pallet::view_functions_experimental]
1768 /// impl<T: Config> Pallet<T> {
1769 /// /// Retrieve a map storage value by key.
1770 /// pub fn get_value_with_arg(key: u32) -> Option<u32> {
1771 /// SomeMap::<T>::get(key)
1772 /// }
1773 /// }
1774 /// }
1775 /// ```
1776 ///
1777 ///
1778 /// ## Usage and implementation details
1779 /// To allow outside access to pallet view functions, you need to add a runtime API that
1780 /// accepts view function queries and dispatches them to the right pallet. You can do that
1781 /// by implementing the
1782 /// [`RuntimeViewFunction`](frame_support::view_functions::runtime_api::RuntimeViewFunction)
1783 /// trait for the runtime inside an [`impl_runtime_apis!`](sp_api::impl_runtime_apis)
1784 /// block.
1785 ///
1786 /// The `RuntimeViewFunction` trait implements a hashing-based dispatching mechanism to
1787 /// dispatch view functions to the right method in the right pallet based on their IDs. A
1788 /// view function ID depends both on its pallet and on its method signature, so it remains
1789 /// stable as long as those two elements are not modified. In general, pallet view
1790 /// functions should expose a _stable_ interface and changes to the method signature are
1791 /// strongly discouraged. For more details on the dispatching mechanism, see the
1792 /// [`DispatchViewFunction`](frame_support::view_functions::DispatchViewFunction) trait.
1793 pub use frame_support_procedural::view_functions_experimental;
1794
1795 /// Allows defining a struct implementing the [`Get`](frame_support::traits::Get) trait to
1796 /// ease the use of storage types.
1797 ///
1798 /// This attribute is meant to be used alongside [`#[pallet::storage]`](`storage`) to
1799 /// define a storage's default value. This attribute can be used multiple times.
1800 ///
1801 /// Item must be defined as:
1802 ///
1803 /// ```
1804 /// #[frame_support::pallet]
1805 /// mod pallet {
1806 /// # use sp_runtime::FixedU128;
1807 /// # use frame_support::pallet_prelude::*;
1808 /// #
1809 /// #[pallet::pallet]
1810 /// pub struct Pallet<T>(_);
1811 ///
1812 /// #[pallet::storage]
1813 /// pub(super) type SomeStorage<T: Config> =
1814 /// StorageValue<_, FixedU128, ValueQuery, DefaultForSomeValue>;
1815 ///
1816 /// // Define default for ParachainId
1817 /// #[pallet::type_value]
1818 /// pub fn DefaultForSomeValue() -> FixedU128 {
1819 /// FixedU128::from_u32(1)
1820 /// }
1821 /// #
1822 /// # #[pallet::config]
1823 /// # pub trait Config: frame_system::Config {}
1824 /// }
1825 /// ```
1826 ///
1827 /// ## Macro expansion
1828 ///
1829 /// The macro renames the function to some internal name, generates a struct with the
1830 /// original name of the function and its generic, and implements `Get<$ReturnType>` by
1831 /// calling the user defined function.
1832 pub use frame_support_procedural::type_value;
1833
1834 /// Allows defining a storage version for the pallet.
1835 ///
1836 /// Because the `pallet::pallet` macro implements
1837 /// [`GetStorageVersion`](frame_support::traits::GetStorageVersion), the current storage
1838 /// version needs to be communicated to the macro. This can be done by using the
1839 /// `pallet::storage_version` attribute:
1840 ///
1841 /// ```
1842 /// #[frame_support::pallet]
1843 /// mod pallet {
1844 /// # use frame_support::pallet_prelude::StorageVersion;
1845 /// # use frame_support::traits::GetStorageVersion;
1846 /// #
1847 /// const STORAGE_VERSION: StorageVersion = StorageVersion::new(5);
1848 ///
1849 /// #[pallet::pallet]
1850 /// #[pallet::storage_version(STORAGE_VERSION)]
1851 /// pub struct Pallet<T>(_);
1852 /// #
1853 /// # #[pallet::config]
1854 /// # pub trait Config: frame_system::Config {}
1855 /// }
1856 /// ```
1857 ///
1858 /// If not present, the current storage version is set to the default value.
1859 pub use frame_support_procedural::storage_version;
1860
1861 /// The `#[pallet::hooks]` attribute allows you to specify a
1862 /// [`frame_support::traits::Hooks`] implementation for `Pallet` that specifies
1863 /// pallet-specific logic.
1864 ///
1865 /// The item the attribute attaches to must be defined as follows:
1866 ///
1867 /// ```
1868 /// #[frame_support::pallet]
1869 /// mod pallet {
1870 /// # use frame_support::pallet_prelude::*;
1871 /// # use frame_system::pallet_prelude::*;
1872 /// #
1873 /// #[pallet::pallet]
1874 /// pub struct Pallet<T>(_);
1875 ///
1876 /// #[pallet::hooks]
1877 /// impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
1878 /// // Implement hooks here
1879 /// }
1880 /// #
1881 /// # #[pallet::config]
1882 /// # pub trait Config: frame_system::Config {}
1883 /// }
1884 /// ```
1885 /// I.e. a regular trait implementation with generic bound: `T: Config`, for the trait
1886 /// `Hooks<BlockNumberFor<T>>` (they are defined in preludes), for the type `Pallet<T>`.
1887 ///
1888 /// Optionally, you could add a where clause.
1889 ///
1890 /// ## Macro expansion
1891 ///
1892 /// The macro implements the traits
1893 /// [`OnInitialize`](frame_support::traits::OnInitialize),
1894 /// [`OnIdle`](frame_support::traits::OnIdle),
1895 /// [`OnFinalize`](frame_support::traits::OnFinalize),
1896 /// [`OnRuntimeUpgrade`](frame_support::traits::OnRuntimeUpgrade),
1897 /// [`OffchainWorker`](frame_support::traits::OffchainWorker), and
1898 /// [`IntegrityTest`](frame_support::traits::IntegrityTest) using
1899 /// the provided [`Hooks`](frame_support::traits::Hooks) implementation.
1900 ///
1901 /// NOTE: `OnRuntimeUpgrade` is implemented with `Hooks::on_runtime_upgrade` and some
1902 /// additional logic. E.g. logic to write the pallet version into storage.
1903 ///
1904 /// NOTE: The macro also adds some tracing logic when implementing the above traits. The
1905 /// following hooks emit traces: `on_initialize`, `on_finalize` and `on_runtime_upgrade`.
1906 pub use frame_support_procedural::hooks;
1907
1908 /// Generates a helper function on `Pallet` that handles deposit events.
1909 ///
1910 /// NOTE: For instantiable pallets, the event must be generic over `T` and `I`.
1911 ///
1912 /// ## Macro expansion
1913 ///
1914 /// The macro will add on enum `Event` the attributes:
1915 /// * `#[derive(`[`frame_support::CloneNoBound`]`)]`
1916 /// * `#[derive(`[`frame_support::EqNoBound`]`)]`
1917 /// * `#[derive(`[`frame_support::PartialEqNoBound`]`)]`
1918 /// * `#[derive(`[`frame_support::RuntimeDebugNoBound`]`)]`
1919 /// * `#[derive(`[`codec::Encode`]`)]`
1920 /// * `#[derive(`[`codec::Decode`]`)]`
1921 ///
1922 /// The macro implements `From<Event<..>>` for ().
1923 ///
1924 /// The macro implements a metadata function on `Event` returning the `EventMetadata`.
1925 ///
1926 /// If `#[pallet::generate_deposit]` is present then the macro implements `fn
1927 /// deposit_event` on `Pallet`.
1928 pub use frame_support_procedural::generate_deposit;
1929
1930 /// Allows defining logic to make an extrinsic call feeless.
1931 ///
1932 /// Each dispatchable may be annotated with the `#[pallet::feeless_if($closure)]`
1933 /// attribute, which explicitly defines the condition for the dispatchable to be feeless.
1934 ///
1935 /// The arguments for the closure must be the referenced arguments of the dispatchable
1936 /// function.
1937 ///
1938 /// The closure must return `bool`.
1939 ///
1940 /// ### Example
1941 ///
1942 /// ```
1943 /// #[frame_support::pallet(dev_mode)]
1944 /// mod pallet {
1945 /// # use frame_support::pallet_prelude::*;
1946 /// # use frame_system::pallet_prelude::*;
1947 /// #
1948 /// #[pallet::pallet]
1949 /// pub struct Pallet<T>(_);
1950 ///
1951 /// #[pallet::call]
1952 /// impl<T: Config> Pallet<T> {
1953 /// #[pallet::call_index(0)]
1954 /// /// Marks this call as feeless if `foo` is zero.
1955 /// #[pallet::feeless_if(|_origin: &OriginFor<T>, foo: &u32| -> bool {
1956 /// *foo == 0
1957 /// })]
1958 /// pub fn something(
1959 /// _: OriginFor<T>,
1960 /// foo: u32,
1961 /// ) -> DispatchResult {
1962 /// unimplemented!()
1963 /// }
1964 /// }
1965 /// #
1966 /// # #[pallet::config]
1967 /// # pub trait Config: frame_system::Config {}
1968 /// }
1969 /// ```
1970 ///
1971 /// Please note that this only works for signed dispatchables and requires a transaction
1972 /// extension such as [`pallet_skip_feeless_payment::SkipCheckIfFeeless`] to wrap the
1973 /// existing payment extension. Else, this is completely ignored and the dispatchable is
1974 /// still charged.
1975 ///
1976 /// Also this will not allow accountless caller to send a transaction if some transaction
1977 /// extension such as `frame_system::CheckNonce` is used.
1978 /// Extensions such as `frame_system::CheckNonce` require a funded account to validate
1979 /// the transaction.
1980 ///
1981 /// ### Macro expansion
1982 ///
1983 /// The macro implements the [`pallet_skip_feeless_payment::CheckIfFeeless`] trait on the
1984 /// dispatchable and calls the corresponding closure in the implementation.
1985 ///
1986 /// [`pallet_skip_feeless_payment::SkipCheckIfFeeless`]: ../../pallet_skip_feeless_payment/struct.SkipCheckIfFeeless.html
1987 /// [`pallet_skip_feeless_payment::CheckIfFeeless`]: ../../pallet_skip_feeless_payment/struct.SkipCheckIfFeeless.html
1988 pub use frame_support_procedural::feeless_if;
1989
1990 /// Allows defining an error enum that will be returned from the dispatchable when an error
1991 /// occurs.
1992 ///
1993 /// The information for this error type is then stored in runtime metadata.
1994 ///
1995 /// Item must be defined as so:
1996 ///
1997 /// ```
1998 /// #[frame_support::pallet(dev_mode)]
1999 /// mod pallet {
2000 /// #[pallet::pallet]
2001 /// pub struct Pallet<T>(_);
2002 ///
2003 /// #[pallet::error]
2004 /// pub enum Error<T> {
2005 /// /// SomeFieldLessVariant doc
2006 /// SomeFieldLessVariant,
2007 /// /// SomeVariantWithOneField doc
2008 /// SomeVariantWithOneField(u32),
2009 /// }
2010 /// #
2011 /// # #[pallet::config]
2012 /// # pub trait Config: frame_system::Config {}
2013 /// }
2014 /// ```
2015 /// I.e. a regular enum named `Error`, with generic `T` and fieldless or multiple-field
2016 /// variants.
2017 ///
2018 /// Any field type in the enum variants must implement [`scale_info::TypeInfo`] in order to
2019 /// be properly used in the metadata, and its encoded size should be as small as possible,
2020 /// preferably 1 byte in size in order to reduce storage size. The error enum itself has an
2021 /// absolute maximum encoded size specified by
2022 /// [`frame_support::MAX_MODULE_ERROR_ENCODED_SIZE`].
2023 ///
2024 /// (1 byte can still be 256 different errors. The more specific the error, the easier it
2025 /// is to diagnose problems and give a better experience to the user. Don't skimp on having
2026 /// lots of individual error conditions.)
2027 ///
2028 /// Field types in enum variants must also implement [`frame_support::PalletError`],
2029 /// otherwise the pallet will fail to compile. Rust primitive types have already
2030 /// implemented the [`frame_support::PalletError`] trait along with some commonly used
2031 /// stdlib types such as [`Option`] and [`core::marker::PhantomData`], and hence
2032 /// in most use cases, a manual implementation is not necessary and is discouraged.
2033 ///
2034 /// The generic `T` must not bound anything and a `where` clause is not allowed. That said,
2035 /// bounds and/or a where clause should not needed for any use-case.
2036 ///
2037 /// ## Macro expansion
2038 ///
2039 /// The macro implements the [`Debug`] trait and functions `as_u8` using variant position,
2040 /// and `as_str` using variant doc.
2041 ///
2042 /// The macro also implements `From<Error<T>>` for `&'static str` and `From<Error<T>>` for
2043 /// `DispatchError`.
2044 ///
2045 /// ## Note on deprecation of Errors
2046 ///
2047 /// - Usage of `deprecated` attribute will propagate deprecation information to the pallet
2048 /// metadata where the item was declared.
2049 /// - For general usage examples of `deprecated` attribute please refer to <https://doc.rust-lang.org/nightly/reference/attributes/diagnostics.html#the-deprecated-attribute>
2050 /// - It's possible to deprecated either certain variants inside the `Error` or the whole
2051 /// `Error` itself. If both the `Error` and its variants are deprecated a compile error
2052 /// will be returned.
2053 pub use frame_support_procedural::error;
2054
2055 /// Allows defining pallet events.
2056 ///
2057 /// Pallet events are stored under the `system` / `events` key when the block is applied
2058 /// (and then replaced when the next block writes it's events).
2059 ///
2060 /// The Event enum can be defined as follows:
2061 ///
2062 /// ```
2063 /// #[frame_support::pallet(dev_mode)]
2064 /// mod pallet {
2065 /// # use frame_support::pallet_prelude::IsType;
2066 /// #
2067 /// #[pallet::pallet]
2068 /// pub struct Pallet<T>(_);
2069 ///
2070 /// #[pallet::event]
2071 /// #[pallet::generate_deposit(fn deposit_event)] // Optional
2072 /// pub enum Event<T> {
2073 /// /// SomeEvent doc
2074 /// SomeEvent(u16, u32), // SomeEvent with two fields
2075 /// }
2076 ///
2077 /// #[pallet::config]
2078 /// pub trait Config: frame_system::Config {
2079 /// /// The overarching runtime event type.
2080 /// type RuntimeEvent: From<Event<Self>>
2081 /// + IsType<<Self as frame_system::Config>::RuntimeEvent>;
2082 /// }
2083 /// }
2084 /// ```
2085 ///
2086 /// I.e. an enum (with named or unnamed fields variant), named `Event`, with generic: none
2087 /// or `T` or `T: Config`, and optional w here clause.
2088 ///
2089 /// `RuntimeEvent` must be defined in the `Config`, as shown in the example.
2090 ///
2091 /// Each field must implement [`Clone`], [`Eq`], [`PartialEq`], [`codec::Encode`],
2092 /// [`codec::Decode`], and [`Debug`] (on std only). For ease of use, bound by the trait
2093 /// `Member`, available in [`frame_support::pallet_prelude`].
2094 ///
2095 /// ## Note on deprecation of Events
2096 ///
2097 /// - Usage of `deprecated` attribute will propagate deprecation information to the pallet
2098 /// metadata where the item was declared.
2099 /// - For general usage examples of `deprecated` attribute please refer to <https://doc.rust-lang.org/nightly/reference/attributes/diagnostics.html#the-deprecated-attribute>
2100 /// - It's possible to deprecated either certain variants inside the `Event` or the whole
2101 /// `Event` itself. If both the `Event` and its variants are deprecated a compile error
2102 /// will be returned.
2103 pub use frame_support_procedural::event;
2104
2105 /// Selectively includes associated types in the metadata.
2106 ///
2107 /// The optional attribute allows you to selectively include associated types in the
2108 /// metadata. This can be attached to trait items that implement `TypeInfo`.
2109 ///
2110 /// By default all collectable associated types are included in the metadata.
2111 ///
2112 /// This attribute can be used in combination with the
2113 /// [`#[pallet::config(without_automatic_metadata)]`](`config`).
2114 pub use frame_support_procedural::include_metadata;
2115
2116 /// Allows a pallet to declare a set of functions as a *dispatchable extrinsic*.
2117 ///
2118 /// In slightly simplified terms, this macro declares the set of "transactions" of a
2119 /// pallet.
2120 ///
2121 /// > The exact definition of **extrinsic** can be found in
2122 /// > [`sp_runtime::generic::UncheckedExtrinsic`].
2123 ///
2124 /// A **dispatchable** is a common term in FRAME, referring to process of constructing a
2125 /// function, and dispatching it with the correct inputs. This is commonly used with
2126 /// extrinsics, for example "an extrinsic has been dispatched". See
2127 /// [`sp_runtime::traits::Dispatchable`] and [`crate::traits::UnfilteredDispatchable`].
2128 ///
2129 /// ## Call Enum
2130 ///
2131 /// The macro is called `call` (rather than `#[pallet::extrinsics]`) because of the
2132 /// generation of a `enum Call`. This enum contains only the encoding of the function
2133 /// arguments of the dispatchable, alongside the information needed to route it to the
2134 /// correct function.
2135 ///
2136 /// ```
2137 /// #[frame_support::pallet(dev_mode)]
2138 /// pub mod custom_pallet {
2139 /// # use frame_support::pallet_prelude::*;
2140 /// # use frame_system::pallet_prelude::*;
2141 /// # #[pallet::config]
2142 /// # pub trait Config: frame_system::Config {}
2143 /// # #[pallet::pallet]
2144 /// # pub struct Pallet<T>(_);
2145 /// # use frame_support::traits::BuildGenesisConfig;
2146 /// #[pallet::call]
2147 /// impl<T: Config> Pallet<T> {
2148 /// pub fn some_dispatchable(_origin: OriginFor<T>, _input: u32) -> DispatchResult {
2149 /// Ok(())
2150 /// }
2151 /// pub fn other(_origin: OriginFor<T>, _input: u64) -> DispatchResult {
2152 /// Ok(())
2153 /// }
2154 /// }
2155 ///
2156 /// // generates something like:
2157 /// // enum Call<T: Config> {
2158 /// // some_dispatchable { input: u32 }
2159 /// // other { input: u64 }
2160 /// // }
2161 /// }
2162 ///
2163 /// fn main() {
2164 /// # use frame_support::{derive_impl, construct_runtime};
2165 /// # use frame_support::__private::codec::Encode;
2166 /// # use frame_support::__private::TestExternalities;
2167 /// # use frame_support::traits::UnfilteredDispatchable;
2168 /// # impl custom_pallet::Config for Runtime {}
2169 /// # #[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
2170 /// # impl frame_system::Config for Runtime {
2171 /// # type Block = frame_system::mocking::MockBlock<Self>;
2172 /// # }
2173 /// construct_runtime! {
2174 /// pub enum Runtime {
2175 /// System: frame_system,
2176 /// Custom: custom_pallet
2177 /// }
2178 /// }
2179 ///
2180 /// # TestExternalities::new_empty().execute_with(|| {
2181 /// let origin: RuntimeOrigin = frame_system::RawOrigin::Signed(10).into();
2182 /// // calling into a dispatchable from within the runtime is simply a function call.
2183 /// let _ = custom_pallet::Pallet::<Runtime>::some_dispatchable(origin.clone(), 10);
2184 ///
2185 /// // calling into a dispatchable from the outer world involves constructing the bytes of
2186 /// let call = custom_pallet::Call::<Runtime>::some_dispatchable { input: 10 };
2187 /// let _ = call.clone().dispatch_bypass_filter(origin);
2188 ///
2189 /// // the routing of a dispatchable is simply done through encoding of the `Call` enum,
2190 /// // which is the index of the variant, followed by the arguments.
2191 /// assert_eq!(call.encode(), vec![0u8, 10, 0, 0, 0]);
2192 ///
2193 /// // notice how in the encoding of the second function, the first byte is different and
2194 /// // referring to the second variant of `enum Call`.
2195 /// let call = custom_pallet::Call::<Runtime>::other { input: 10 };
2196 /// assert_eq!(call.encode(), vec![1u8, 10, 0, 0, 0, 0, 0, 0, 0]);
2197 /// # });
2198 /// }
2199 /// ```
2200 ///
2201 /// Further properties of dispatchable functions are as follows:
2202 ///
2203 /// - Unless if annotated by `dev_mode`, it must contain [`weight`] to denote the
2204 /// pre-dispatch weight consumed.
2205 /// - The dispatchable must declare its index via [`call_index`], which can override the
2206 /// position of a function in `enum Call`.
2207 /// - The first argument is always an `OriginFor` (or `T::RuntimeOrigin`).
2208 /// - The return type is always [`crate::dispatch::DispatchResult`] (or
2209 /// [`crate::dispatch::DispatchResultWithPostInfo`]).
2210 ///
2211 /// **WARNING**: modifying dispatchables, changing their order (i.e. using [`call_index`]),
2212 /// removing some, etc., must be done with care. This will change the encoding of the call,
2213 /// and the call can be stored on-chain (e.g. in `pallet-scheduler`). Thus, migration
2214 /// might be needed. This is why the use of `call_index` is mandatory by default in FRAME.
2215 ///
2216 /// ## Weight info
2217 ///
2218 /// Each call needs to define a weight.
2219 /// * The weight can be defined explicitly using the attribute `#[pallet::weight($expr)]`
2220 /// (Note that argument of the call are available inside the expression).
2221 /// * Or it can be defined implicitly, the weight info for the calls needs to be specified
2222 /// in the call attribute: `#[pallet::call(weight = $WeightInfo)]`, then each call that
2223 /// doesn't have explicit weight will use `$WeightInfo::$call_name` as the weight.
2224 ///
2225 /// * Or it can be simply ignored when the pallet is in `dev_mode`.
2226 ///
2227 /// ```
2228 /// #[frame_support::pallet]
2229 /// mod pallet {
2230 /// use frame_support::pallet_prelude::*;
2231 /// use frame_system::pallet_prelude::*;
2232 ///
2233 /// #[pallet::pallet]
2234 /// pub struct Pallet<T>(_);
2235 ///
2236 /// #[pallet::config]
2237 /// pub trait Config: frame_system::Config {
2238 /// /// Type for specifying dispatchable weights.
2239 /// type WeightInfo: WeightInfo;
2240 /// }
2241 ///
2242 /// /// The `WeightInfo` trait defines weight functions for dispatchable calls.
2243 /// pub trait WeightInfo {
2244 /// fn do_something() -> Weight;
2245 /// fn do_something_else() -> Weight;
2246 /// }
2247 ///
2248 /// #[pallet::call(weight = <T as Config>::WeightInfo)]
2249 /// impl<T: Config> Pallet<T> {
2250 /// // Explicit weight definition using `#[pallet::weight(...)]`
2251 /// #[pallet::weight(<T as Config>::WeightInfo::do_something())]
2252 /// #[pallet::call_index(0)]
2253 /// pub fn do_something(
2254 /// origin: OriginFor<T>,
2255 /// foo: u32,
2256 /// ) -> DispatchResult {
2257 /// // Function logic here
2258 /// Ok(())
2259 /// }
2260 ///
2261 /// // Implicit weight definition, the macro looks up to the weight info defined in
2262 /// // `#[pallet::call(weight = $WeightInfo)]` attribute. Then use
2263 /// // `$WeightInfo::do_something_else` as the weight function.
2264 /// #[pallet::call_index(1)]
2265 /// pub fn do_something_else(
2266 /// origin: OriginFor<T>,
2267 /// bar: u64,
2268 /// ) -> DispatchResult {
2269 /// // Function logic here
2270 /// Ok(())
2271 /// }
2272 /// }
2273 /// }
2274 /// ```
2275 ///
2276 /// ## Default Behavior
2277 ///
2278 /// If no `#[pallet::call]` exists, then a default implementation corresponding to the
2279 /// following code is automatically generated:
2280 ///
2281 /// ```
2282 /// #[frame_support::pallet(dev_mode)]
2283 /// mod pallet {
2284 /// #[pallet::pallet]
2285 /// pub struct Pallet<T>(_);
2286 ///
2287 /// #[pallet::call] // <- automatically generated
2288 /// impl<T: Config> Pallet<T> {} // <- automatically generated
2289 ///
2290 /// #[pallet::config]
2291 /// pub trait Config: frame_system::Config {}
2292 /// }
2293 /// ```
2294 ///
2295 /// ## Note on deprecation of Calls
2296 ///
2297 /// - Usage of `deprecated` attribute will propagate deprecation information to the pallet
2298 /// metadata where the item was declared.
2299 /// - For general usage examples of `deprecated` attribute please refer to <https://doc.rust-lang.org/nightly/reference/attributes/diagnostics.html#the-deprecated-attribute>
2300 pub use frame_support_procedural::call;
2301
2302 /// Enforce the index of a variant in the generated `enum Call`.
2303 ///
2304 /// See [`call`] for more information.
2305 ///
2306 /// All call indexes start from 0, until it encounters a dispatchable function with a
2307 /// defined call index. The dispatchable function that lexically follows the function with
2308 /// a defined call index will have that call index, but incremented by 1, e.g. if there are
2309 /// 3 dispatchable functions `fn foo`, `fn bar` and `fn qux` in that order, and only `fn
2310 /// bar` has a call index of 10, then `fn qux` will have an index of 11, instead of 1.
2311 pub use frame_support_procedural::call_index;
2312
2313 /// Declares the arguments of a [`call`] function to be encoded using
2314 /// [`codec::Compact`].
2315 ///
2316 /// This will results in smaller extrinsic encoding.
2317 ///
2318 /// A common example of `compact` is for numeric values that are often times far far away
2319 /// from their theoretical maximum. For example, in the context of a crypto-currency, the
2320 /// balance of an individual account is oftentimes way less than what the numeric type
2321 /// allows. In all such cases, using `compact` is sensible.
2322 ///
2323 /// ```
2324 /// #[frame_support::pallet(dev_mode)]
2325 /// pub mod custom_pallet {
2326 /// # use frame_support::pallet_prelude::*;
2327 /// # use frame_system::pallet_prelude::*;
2328 /// # #[pallet::config]
2329 /// # pub trait Config: frame_system::Config {}
2330 /// # #[pallet::pallet]
2331 /// # pub struct Pallet<T>(_);
2332 /// # use frame_support::traits::BuildGenesisConfig;
2333 /// #[pallet::call]
2334 /// impl<T: Config> Pallet<T> {
2335 /// pub fn some_dispatchable(_origin: OriginFor<T>, #[pallet::compact] _input: u32) -> DispatchResult {
2336 /// Ok(())
2337 /// }
2338 /// }
2339 /// }
2340 pub use frame_support_procedural::compact;
2341
2342 /// Allows you to define the genesis configuration for the pallet.
2343 ///
2344 /// Item is defined as either an enum or a struct. It needs to be public and implement the
2345 /// trait [`frame_support::traits::BuildGenesisConfig`].
2346 ///
2347 /// See [`genesis_build`] for an example.
2348 pub use frame_support_procedural::genesis_config;
2349
2350 /// Allows you to define how the state of your pallet at genesis is built. This
2351 /// takes as input the `GenesisConfig` type (as `self`) and constructs the pallet's initial
2352 /// state.
2353 ///
2354 /// The fields of the `GenesisConfig` can in turn be populated by the chain-spec.
2355 ///
2356 /// ## Example
2357 ///
2358 /// ```
2359 /// #[frame_support::pallet]
2360 /// pub mod pallet {
2361 /// # #[pallet::config]
2362 /// # pub trait Config: frame_system::Config {}
2363 /// # #[pallet::pallet]
2364 /// # pub struct Pallet<T>(_);
2365 /// # use frame_support::traits::BuildGenesisConfig;
2366 /// #[pallet::genesis_config]
2367 /// #[derive(frame_support::DefaultNoBound)]
2368 /// pub struct GenesisConfig<T: Config> {
2369 /// foo: Vec<T::AccountId>
2370 /// }
2371 ///
2372 /// #[pallet::genesis_build]
2373 /// impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
2374 /// fn build(&self) {
2375 /// // use &self to access fields.
2376 /// let foo = &self.foo;
2377 /// todo!()
2378 /// }
2379 /// }
2380 /// }
2381 /// ```
2382 ///
2383 /// ## Former Usage
2384 ///
2385 /// Prior to <https://github.com/paritytech/substrate/pull/14306>, the following syntax was used.
2386 /// This is deprecated and will soon be removed.
2387 ///
2388 /// ```
2389 /// #[frame_support::pallet]
2390 /// pub mod pallet {
2391 /// # #[pallet::config]
2392 /// # pub trait Config: frame_system::Config {}
2393 /// # #[pallet::pallet]
2394 /// # pub struct Pallet<T>(_);
2395 /// # use frame_support::traits::GenesisBuild;
2396 /// #[pallet::genesis_config]
2397 /// #[derive(frame_support::DefaultNoBound)]
2398 /// pub struct GenesisConfig<T: Config> {
2399 /// foo: Vec<T::AccountId>
2400 /// }
2401 ///
2402 /// #[pallet::genesis_build]
2403 /// impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
2404 /// fn build(&self) {
2405 /// todo!()
2406 /// }
2407 /// }
2408 /// }
2409 /// ```
2410 pub use frame_support_procedural::genesis_build;
2411
2412 /// Allows adding an associated type trait bounded by
2413 /// [`Get`](frame_support::pallet_prelude::Get) from [`pallet::config`](`macro@config`)
2414 /// into metadata.
2415 ///
2416 /// ## Example
2417 ///
2418 /// ```
2419 /// #[frame_support::pallet]
2420 /// mod pallet {
2421 /// use frame_support::pallet_prelude::*;
2422 /// # #[pallet::pallet]
2423 /// # pub struct Pallet<T>(_);
2424 /// #[pallet::config]
2425 /// pub trait Config: frame_system::Config {
2426 /// /// This is like a normal `Get` trait, but it will be added into metadata.
2427 /// #[pallet::constant]
2428 /// type Foo: Get<u32>;
2429 /// }
2430 /// }
2431 /// ```
2432 ///
2433 /// ## Note on deprecation of constants
2434 ///
2435 /// - Usage of `deprecated` attribute will propagate deprecation information to the pallet
2436 /// metadata where the item was declared.
2437 /// - For general usage examples of `deprecated` attribute please refer to <https://doc.rust-lang.org/nightly/reference/attributes/diagnostics.html#the-deprecated-attribute>
2438 pub use frame_support_procedural::constant;
2439
2440 /// Declares a type alias as a storage item.
2441 ///
2442 /// Storage items are pointers to data stored on-chain (the *blockchain state*), under a
2443 /// specific key. The exact key is dependent on the type of the storage.
2444 ///
2445 /// > From the perspective of this pallet, the entire blockchain state is abstracted behind
2446 /// > a key-value api, namely [`sp_io::storage`].
2447 ///
2448 /// ## Storage Types
2449 ///
2450 /// The following storage types are supported by the `#[storage]` macro. For specific
2451 /// information about each storage type, refer to the documentation of the respective type.
2452 ///
2453 /// * [`StorageValue`](crate::storage::types::StorageValue)
2454 /// * [`StorageMap`](crate::storage::types::StorageMap)
2455 /// * [`CountedStorageMap`](crate::storage::types::CountedStorageMap)
2456 /// * [`StorageDoubleMap`](crate::storage::types::StorageDoubleMap)
2457 /// * [`StorageNMap`](crate::storage::types::StorageNMap)
2458 /// * [`CountedStorageNMap`](crate::storage::types::CountedStorageNMap)
2459 ///
2460 /// ## Storage Type Usage
2461 ///
2462 /// The following details are relevant to all of the aforementioned storage types.
2463 /// Depending on the exact storage type, it may require the following generic parameters:
2464 ///
2465 /// * [`Prefix`](#prefixes) - Used to give the storage item a unique key in the underlying
2466 /// storage.
2467 /// * `Key` - Type of the keys used to store the values,
2468 /// * `Value` - Type of the value being stored,
2469 /// * [`Hasher`](#hashers) - Used to ensure the keys of a map are uniformly distributed,
2470 /// * [`QueryKind`](#querykind) - Used to configure how to handle queries to the underlying
2471 /// storage,
2472 /// * `OnEmpty` - Used to handle missing values when querying the underlying storage,
2473 /// * `MaxValues` - _not currently used_.
2474 ///
2475 /// Each `Key` type requires its own designated `Hasher` declaration, so that
2476 /// [`StorageDoubleMap`](frame_support::storage::types::StorageDoubleMap) needs two of
2477 /// each, and [`StorageNMap`](frame_support::storage::types::StorageNMap) needs `N` such
2478 /// pairs. Since [`StorageValue`](frame_support::storage::types::StorageValue) only stores
2479 /// a single element, no configuration of hashers is needed.
2480 ///
2481 /// ### Syntax
2482 ///
2483 /// Two general syntaxes are supported, as demonstrated below:
2484 ///
2485 /// 1. Named type parameters, e.g., `type Foo<T> = StorageValue<Value = u32>`.
2486 /// 2. Positional type parameters, e.g., `type Foo<T> = StorageValue<_, u32>`.
2487 ///
2488 /// In both instances, declaring the generic parameter `<T>` is mandatory. Optionally, it
2489 /// can also be explicitly declared as `<T: Config>`. In the compiled code, `T` will
2490 /// automatically include the trait bound `Config`.
2491 ///
2492 /// Note that in positional syntax, the first generic type parameter must be `_`.
2493 ///
2494 /// #### Example
2495 ///
2496 /// ```
2497 /// #[frame_support::pallet]
2498 /// mod pallet {
2499 /// # use frame_support::pallet_prelude::*;
2500 /// # #[pallet::config]
2501 /// # pub trait Config: frame_system::Config {}
2502 /// # #[pallet::pallet]
2503 /// # pub struct Pallet<T>(_);
2504 /// /// Positional syntax, without bounding `T`.
2505 /// #[pallet::storage]
2506 /// pub type Foo<T> = StorageValue<_, u32>;
2507 ///
2508 /// /// Positional syntax, with bounding `T`.
2509 /// #[pallet::storage]
2510 /// pub type Bar<T: Config> = StorageValue<_, u32>;
2511 ///
2512 /// /// Named syntax.
2513 /// #[pallet::storage]
2514 /// pub type Baz<T> = StorageMap<Hasher = Blake2_128Concat, Key = u32, Value = u32>;
2515 /// }
2516 /// ```
2517 ///
2518 /// ### Value Trait Bounds
2519 ///
2520 /// To use a type as the value of a storage type, be it `StorageValue`, `StorageMap` or
2521 /// anything else, you need to meet a number of trait bound constraints.
2522 ///
2523 /// See: <https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_storage_derives/index.html>.
2524 ///
2525 /// Notably, all value types need to implement `Encode`, `Decode`, `MaxEncodedLen` and
2526 /// `TypeInfo`, and possibly `Default`, if
2527 /// [`ValueQuery`](frame_support::storage::types::ValueQuery) is used, explained in the
2528 /// next section.
2529 ///
2530 /// ### QueryKind
2531 ///
2532 /// Every storage type mentioned above has a generic type called
2533 /// [`QueryKind`](frame_support::storage::types::QueryKindTrait) that determines its
2534 /// "query" type. This refers to the kind of value returned when querying the storage, for
2535 /// instance, through a `::get()` method.
2536 ///
2537 /// There are three types of queries:
2538 ///
2539 /// 1. [`OptionQuery`](frame_support::storage::types::OptionQuery): The default query type.
2540 /// It returns `Some(V)` if the value is present, or `None` if it isn't, where `V` is
2541 /// the value type.
2542 /// 2. [`ValueQuery`](frame_support::storage::types::ValueQuery): Returns the value itself
2543 /// if present; otherwise, it returns `Default::default()`. This behavior can be
2544 /// adjusted with the `OnEmpty` generic parameter, which defaults to `OnEmpty =
2545 /// GetDefault`.
2546 /// 3. [`ResultQuery`](frame_support::storage::types::ResultQuery): Returns `Result<V, E>`,
2547 /// where `V` is the value type.
2548 ///
2549 /// See [`QueryKind`](frame_support::storage::types::QueryKindTrait) for further examples.
2550 ///
2551 /// ### Optimized Appending
2552 ///
2553 /// All storage items — such as
2554 /// [`StorageValue`](frame_support::storage::types::StorageValue),
2555 /// [`StorageMap`](frame_support::storage::types::StorageMap), and their variants—offer an
2556 /// `::append()` method optimized for collections. Using this method avoids the
2557 /// inefficiency of decoding and re-encoding entire collections when adding items. For
2558 /// instance, consider the storage declaration `type MyVal<T> = StorageValue<_, Vec<u8>,
2559 /// ValueQuery>`. With `MyVal` storing a large list of bytes, `::append()` lets you
2560 /// directly add bytes to the end in storage without processing the full list. Depending on
2561 /// the storage type, additional key specifications may be needed.
2562 ///
2563 /// #### Example
2564 #[doc = docify::embed!("src/lib.rs", example_storage_value_append)]
2565 /// Similarly, there also exists a `::try_append()` method, which can be used when handling
2566 /// types where an append operation might fail, such as a
2567 /// [`BoundedVec`](frame_support::BoundedVec).
2568 ///
2569 /// #### Example
2570 #[doc = docify::embed!("src/lib.rs", example_storage_value_try_append)]
2571 /// ### Optimized Length Decoding
2572 ///
2573 /// All storage items — such as
2574 /// [`StorageValue`](frame_support::storage::types::StorageValue),
2575 /// [`StorageMap`](frame_support::storage::types::StorageMap), and their counterparts —
2576 /// incorporate the `::decode_len()` method. This method allows for efficient retrieval of
2577 /// a collection's length without the necessity of decoding the entire dataset.
2578 /// #### Example
2579 #[doc = docify::embed!("src/lib.rs", example_storage_value_decode_len)]
2580 /// ### Hashers
2581 ///
2582 /// For all storage types, except
2583 /// [`StorageValue`](frame_support::storage::types::StorageValue), a set of hashers needs
2584 /// to be specified. The choice of hashers is crucial, especially in production chains. The
2585 /// purpose of storage hashers in maps is to ensure the keys of a map are
2586 /// uniformly distributed. An unbalanced map/trie can lead to inefficient performance.
2587 ///
2588 /// In general, hashers are categorized as either cryptographically secure or not. The
2589 /// former is slower than the latter. `Blake2` and `Twox` serve as examples of each,
2590 /// respectively.
2591 ///
2592 /// As a rule of thumb:
2593 ///
2594 /// 1. If the map keys are not controlled by end users, or are cryptographically secure by
2595 /// definition (e.g., `AccountId`), then the use of cryptographically secure hashers is NOT
2596 /// required.
2597 /// 2. If the map keys are controllable by the end users, cryptographically secure hashers
2598 /// should be used.
2599 ///
2600 /// For more information, look at the types that implement
2601 /// [`frame_support::StorageHasher`](frame_support::StorageHasher).
2602 ///
2603 /// Lastly, it's recommended for hashers with "concat" to have reversible hashes. Refer to
2604 /// the implementors section of
2605 /// [`hash::ReversibleStorageHasher`](frame_support::hash::ReversibleStorageHasher).
2606 ///
2607 /// ### Prefixes
2608 ///
2609 /// Internally, every storage type generates a "prefix". This prefix serves as the initial
2610 /// segment of the key utilized to store values in the on-chain state (i.e., the final key
2611 /// used in [`sp_io::storage`](sp_io::storage)). For all storage types, the following rule
2612 /// applies:
2613 ///
2614 /// > The storage prefix begins with `twox128(pallet_prefix) ++ twox128(STORAGE_PREFIX)`,
2615 /// > where
2616 /// > `pallet_prefix` is the name assigned to the pallet instance in
2617 /// > [`frame_support::construct_runtime`](frame_support::construct_runtime), and
2618 /// > `STORAGE_PREFIX` is the name of the `type` aliased to a particular storage type, such
2619 /// > as
2620 /// > `Foo` in `type Foo<T> = StorageValue<..>`.
2621 ///
2622 /// For [`StorageValue`](frame_support::storage::types::StorageValue), no additional key is
2623 /// required. For map types, the prefix is extended with one or more keys defined by the
2624 /// map.
2625 ///
2626 /// #### Example
2627 #[doc = docify::embed!("src/lib.rs", example_storage_value_map_prefixes)]
2628 /// ## Related Macros
2629 ///
2630 /// The following attribute macros can be used in conjunction with the `#[storage]` macro:
2631 ///
2632 /// * [`macro@getter`]: Creates a custom getter function.
2633 /// * [`macro@storage_prefix`]: Overrides the default prefix of the storage item.
2634 /// * [`macro@unbounded`]: Declares the storage item as unbounded.
2635 /// * [`macro@disable_try_decode_storage`]: Declares that try-runtime checks should not
2636 /// attempt to decode the storage item.
2637 ///
2638 /// #### Example
2639 /// ```
2640 /// #[frame_support::pallet]
2641 /// mod pallet {
2642 /// # use frame_support::pallet_prelude::*;
2643 /// # #[pallet::config]
2644 /// # pub trait Config: frame_system::Config {}
2645 /// # #[pallet::pallet]
2646 /// # pub struct Pallet<T>(_);
2647 /// /// A kitchen-sink StorageValue, with all possible additional attributes.
2648 /// #[pallet::storage]
2649 /// #[pallet::getter(fn foo)]
2650 /// #[pallet::storage_prefix = "OtherFoo"]
2651 /// #[pallet::unbounded]
2652 /// #[pallet::disable_try_decode_storage]
2653 /// pub type Foo<T> = StorageValue<_, u32, ValueQuery>;
2654 /// }
2655 /// ```
2656 ///
2657 /// ## Note on deprecation of storage items
2658 ///
2659 /// - Usage of `deprecated` attribute will propagate deprecation information to the pallet
2660 /// metadata where the storage item was declared.
2661 /// - For general usage examples of `deprecated` attribute please refer to <https://doc.rust-lang.org/nightly/reference/attributes/diagnostics.html#the-deprecated-attribute>
2662 pub use frame_support_procedural::storage;
2663
2664 pub use frame_support_procedural::{
2665 task_condition, task_index, task_list, task_weight, tasks_experimental,
2666 };
2667
2668 /// Allows a pallet to declare a type as an origin.
2669 ///
2670 /// If defined as such, this type will be amalgamated at the runtime level into
2671 /// `RuntimeOrigin`, very similar to [`call`], [`error`] and [`event`]. See
2672 /// [`composite_enum`] for similar cases.
2673 ///
2674 /// Origin is a complex FRAME topics and is further explained in `polkadot_sdk_docs`.
2675 ///
2676 /// ## Syntax Variants
2677 ///
2678 /// ```
2679 /// #[frame_support::pallet]
2680 /// mod pallet {
2681 /// # use frame_support::pallet_prelude::*;
2682 /// # #[pallet::config]
2683 /// # pub trait Config: frame_system::Config {}
2684 /// # #[pallet::pallet]
2685 /// # pub struct Pallet<T>(_);
2686 /// /// On the spot declaration.
2687 /// #[pallet::origin]
2688 /// #[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)]
2689 /// pub enum Origin {
2690 /// Foo,
2691 /// Bar,
2692 /// }
2693 /// }
2694 /// ```
2695 ///
2696 /// Or, more commonly used:
2697 ///
2698 /// ```
2699 /// #[frame_support::pallet]
2700 /// mod pallet {
2701 /// # use frame_support::pallet_prelude::*;
2702 /// # #[pallet::config]
2703 /// # pub trait Config: frame_system::Config {}
2704 /// # #[pallet::pallet]
2705 /// # pub struct Pallet<T>(_);
2706 /// #[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)]
2707 /// pub enum RawOrigin {
2708 /// Foo,
2709 /// Bar,
2710 /// }
2711 ///
2712 /// #[pallet::origin]
2713 /// pub type Origin = RawOrigin;
2714 /// }
2715 /// ```
2716 ///
2717 /// ## Warning
2718 ///
2719 /// Modifying any pallet's origin type will cause the runtime level origin type to also
2720 /// change in encoding. If stored anywhere on-chain, this will require a data migration.
2721 ///
2722 /// Read more about origins at the [Origin Reference
2723 /// Docs](../../polkadot_sdk_docs/reference_docs/frame_origin/index.html).
2724 pub use frame_support_procedural::origin;
2725}
2726
2727#[deprecated(note = "Will be removed after July 2023; Use `sp_runtime::traits` directly instead.")]
2728pub mod error {
2729 #[doc(hidden)]
2730 pub use sp_runtime::traits::{BadOrigin, LookupError};
2731}
2732
2733#[doc(inline)]
2734pub use frame_support_procedural::register_default_impl;
2735
2736// Generate a macro that will enable/disable code based on `std` feature being active.
2737sp_core::generate_feature_enabled_macro!(std_enabled, feature = "std", $);
2738// Generate a macro that will enable/disable code based on `try-runtime` feature being active.
2739sp_core::generate_feature_enabled_macro!(try_runtime_enabled, feature = "try-runtime", $);
2740sp_core::generate_feature_enabled_macro!(try_runtime_or_std_enabled, any(feature = "try-runtime", feature = "std"), $);
2741sp_core::generate_feature_enabled_macro!(try_runtime_and_std_not_enabled, all(not(feature = "try-runtime"), not(feature = "std")), $);
2742
2743/// Helper for implementing GenesisBuilder runtime API
2744pub mod genesis_builder_helper;
2745
2746/// Helper for generating the `RuntimeGenesisConfig` instance for presets.
2747pub mod generate_genesis_config;
2748
2749#[cfg(test)]
2750mod test {
2751 // use super::*;
2752 use crate::{
2753 hash::*,
2754 storage::types::{StorageMap, StorageValue, ValueQuery},
2755 traits::{ConstU32, StorageInstance},
2756 BoundedVec,
2757 };
2758 use sp_io::{hashing::twox_128, TestExternalities};
2759
2760 struct Prefix;
2761 impl StorageInstance for Prefix {
2762 fn pallet_prefix() -> &'static str {
2763 "test"
2764 }
2765 const STORAGE_PREFIX: &'static str = "foo";
2766 }
2767
2768 struct Prefix1;
2769 impl StorageInstance for Prefix1 {
2770 fn pallet_prefix() -> &'static str {
2771 "test"
2772 }
2773 const STORAGE_PREFIX: &'static str = "MyVal";
2774 }
2775 struct Prefix2;
2776 impl StorageInstance for Prefix2 {
2777 fn pallet_prefix() -> &'static str {
2778 "test"
2779 }
2780 const STORAGE_PREFIX: &'static str = "MyMap";
2781 }
2782
2783 #[docify::export]
2784 #[test]
2785 pub fn example_storage_value_try_append() {
2786 type MyVal = StorageValue<Prefix, BoundedVec<u8, ConstU32<10>>, ValueQuery>;
2787
2788 TestExternalities::default().execute_with(|| {
2789 MyVal::set(BoundedVec::try_from(vec![42, 43]).unwrap());
2790 assert_eq!(MyVal::get(), vec![42, 43]);
2791 // Try to append a single u32 to BoundedVec stored in `MyVal`
2792 assert_ok!(MyVal::try_append(40));
2793 assert_eq!(MyVal::get(), vec![42, 43, 40]);
2794 });
2795 }
2796
2797 #[docify::export]
2798 #[test]
2799 pub fn example_storage_value_append() {
2800 type MyVal = StorageValue<Prefix, Vec<u8>, ValueQuery>;
2801
2802 TestExternalities::default().execute_with(|| {
2803 MyVal::set(vec![42, 43]);
2804 assert_eq!(MyVal::get(), vec![42, 43]);
2805 // Append a single u32 to Vec stored in `MyVal`
2806 MyVal::append(40);
2807 assert_eq!(MyVal::get(), vec![42, 43, 40]);
2808 });
2809 }
2810
2811 #[docify::export]
2812 #[test]
2813 pub fn example_storage_value_decode_len() {
2814 type MyVal = StorageValue<Prefix, BoundedVec<u8, ConstU32<10>>, ValueQuery>;
2815
2816 TestExternalities::default().execute_with(|| {
2817 MyVal::set(BoundedVec::try_from(vec![42, 43]).unwrap());
2818 assert_eq!(MyVal::decode_len().unwrap(), 2);
2819 });
2820 }
2821
2822 #[docify::export]
2823 #[test]
2824 pub fn example_storage_value_map_prefixes() {
2825 type MyVal = StorageValue<Prefix1, u32, ValueQuery>;
2826 type MyMap = StorageMap<Prefix2, Blake2_128Concat, u16, u32, ValueQuery>;
2827 TestExternalities::default().execute_with(|| {
2828 // This example assumes `pallet_prefix` to be "test"
2829 // Get storage key for `MyVal` StorageValue
2830 assert_eq!(
2831 MyVal::hashed_key().to_vec(),
2832 [twox_128(b"test"), twox_128(b"MyVal")].concat()
2833 );
2834 // Get storage key for `MyMap` StorageMap and `key` = 1
2835 let mut k: Vec<u8> = vec![];
2836 k.extend(&twox_128(b"test"));
2837 k.extend(&twox_128(b"MyMap"));
2838 k.extend(&1u16.blake2_128_concat());
2839 assert_eq!(MyMap::hashed_key_for(1).to_vec(), k);
2840 });
2841 }
2842}