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