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