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