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