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