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