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