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