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