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