Enrich metadata with type information (#8615)

* Cargo.lock after merge

* Restore scale-info feature

* Fully qualify TypeInfo derive

* Skip PendingSwap T

* Add missing skip_type_params attr

* metadata docs features

* Reduce pallet event attribute to struct

* Cargo.lock

* Update frame/balances/src/tests_composite.rs

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>

* Line widths check

* Cargo.lock

* Add scale-info/std

* Update frame/system/src/lib.rs

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>

* Use `skip_type_params` to remove `TypeInfo` requirements on checks

* Revert "Remove unused Call metadata stuff"

This reverts commit 41311f85

* Skip BalanceSwapAction type parameter

* Remove unused event metadata macro

* Update frame-metadata

* Update primitives/npos-elections/compact/src/codec.rs

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>

* Manual TypeInfo for Header

* Remove TypeInfo requirement for consts in BoundedVec etc.

* Another TypeInfo bound removed

* review: fix indentation

* TypeInfo impls for Identity types

* Add some todos to add custom TypeInfo impls

* Update frame/support/procedural/src/pallet/expand/pallet_struct.rs

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>

* Add some todos to add custom TypeInfo impls

* Add a test for manual Data TypeInfo impl

* Add custom TypeInfo impl for Vote

* Era custom TypeInfo crimes

* Revert finality-grandpa version to 0.14.z

* review: renamed module to pallet_constants_metadata

* New line at end of file

* Add missing scale-info/std

* Update frame/support/src/storage/types/mod.rs

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>

* Remove StorageEntryType::Map unused flag

* Add missing scale-info dependency after merge

* SignedExtension::AdditionalSigned metadata

* Update frame-metadata, use abbreviated docs and args fields

* Update frame/example/Cargo.toml

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* Add scale_info/std and remove unused scale-info dependency

* Remove scale-info dependency

* Remove treasury pallet::metadata

* Remove redundant Event test

* Add back scale-info as dev dependency

* fix error metadata when no error defined in decl_module

* Add Module3 to tests

* Fix metadata test

* Add docs feature to frame-support test

* WIP fixing pallet metadata test

* Remove redundant FunctionMetadata, FunctionArgumentMetadata as per https://github.com/paritytech/frame-metadata/pull/20

* Use main branch of frame-metadata

* Use patch of scale-info for latest changes

* Use latest patched scale-info

* Manual TypeInfo for DigestItem

* Manual TypeInfo for DigestItem

* Update scale-info

* Skip __Ignore variants for Error, depends on https://github.com/paritytech/scale-info/pull/117

* Named fields for FRAME v2 pallet Call variants

* Named fields for FRAME v1 pallet Call variants

* Add missing scale-info dependency

* WIP expand benchmark call variant

* fix benchmark with new function

create a new function for each variant of a pallet call.
This function is called by benchmarking macro in order not to break call
creation with unnamed argument

* fix tests

* more fix

* Fix staking tests

* Fix offchain workers calls

* Cherry pick rustfmt.toml from master

* cargo +nightly-2021-06-22 fmt --all

* Update to new call variant structs

* More call variant struct updates

* Remove unused import

* More call variant structs

* More call variant structs

* Even more call variant structs

* Mooar variant structs

* Evermore variant structs

* Call variant structs ad infinitum

* Fmt

* More call variants

* Last call variant

* Call variants all done?

* Fix SS58Prefix type

* Potential workaround for BitFlags<IdentityFields> TypeInfo

* Enable docs capturing for Call, Event, and Error types

* Fix IdentityFields TypeInfo

* Remove metadata-docs feature

* Add capture_docs = true for legacy Call, Event and Error types

* Fmt

* Fix metadata test type

* Update benchmarks with call struct variants

* Fmt

* More test fixes

* Fmt

* Fix benches

* Use latest capture_docs attr

* Latest scale_info

* Fmt

* review: change &Vec to &[]

* Remove pallet metadata attr

* review: remove commented out test code

* review: skip_type_params trailing comma suggestion

* Update to scale-info 0.10.0

* Update construct_runtime ui tests, different because of metadata TypeInfo impls

* Add some TypeInfo derives for UI tests

* Update storage ensure span ui stderrs

* Update call argument bound ui tests

Possibly changed because change from tuple to struct variants?

* Add scale-info dev dependency

* Update to latest finality-grandpa release

* review: missing newline

* review: missing scale-info/std

* review: remove duplicate scale-info/std

* review: remove fully qualified TypeInfo

* review: add missing scale-info/std

* review: remove unnecessary imports.

* Fmt

* Use crates.io RC version of frame-metadata

* Remove scale-info/std because it is a dev dependency

* Add missing scale_info dev-dependency for test

* Delete empty metadata folder

* Fix sp_std import

* review: improve manual UncheckedExtrinsic TypeInfo impl

* review: use full scale-info for dev-dependency

* Remove DefaultByteGetter impl

* review: derive TypeInfo for generic header

* Fmt

* Update primitives/runtime/src/generic/unchecked_extrinsic.rs

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* Update primitives/runtime/src/generic/unchecked_extrinsic.rs

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* Update bin/node/executor/Cargo.toml

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/identity/src/types.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/support/src/dispatch.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Remove redundant derive

* Simplify scale-info dependency

* Strip underscore prefix from call variant struct names

* Another underscore field

* More underscore fields

* Another underscore field

* Update to frame-metadata 14.0.0-rc.2 with combined StorageEntryType::Map

* Fmt

* Revert weights formatting

* Fix up some tests

* Fix up some tests for StorageEntryTypeMetadata

* scale-info dev dependency

* Fix test error

* Add missing TypeInfo derives

* Add back missing scale-info dependency

* Add back missing scale-info dependency

* Fix npos compact impls

* Cargo.lock

* Fmt

* Fix errors

* Fmt

* Fix renamed raw_solution field

* Fix error

* Fmt

* Fix some benchmarks

* Fmt

* Stray R

* Fix

* Add missing TypeInfos

* ui test fix

* Fix line widths

* Revert "ui test fix"

This reverts commit 2d15ec058a216e3f92d713f1174603a2bb1eac65.

* Upgrade to scale-info 0.11.0

* Revert "Upgrade to scale-info 0.11.0"

This reverts commit 047bb179085a0059c36cd20ab405f55cf0867e28.

* Add Runtime type

* Update to scale-info 0.12

* Update to scale-info 1.0

* Update frame-metadata to version 14.0.0

* Patch finality-grandpa until release available

* Fix metadata tests

* Fix metadata tests

* Fmt

* Remove patched finality-grandpa

* Fix tests, use scale_info imports

* Fix pallet tests

* Add BlockNumber TypeInfo bound

* ui test fix

* Cargo.lock

* Remove pallet metadata

* Cargo.lock

* Add missing scale-info dependency

* Remove pallet event metadata

* Fix error

* Fix collective errors

* Semicolol

* Fmt

* Remove another metadata attribute

* Add new variant to custom digest TypeInfo

* Fmt

* Cargo.lock from master

* Remove comma lol

* Fix example call error

* Fix example call error properly

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>
Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>
Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>
Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
This commit is contained in:
Andrew Jones
2021-09-15 12:40:41 +01:00
committed by GitHub
parent ebe78a4c1b
commit 49b6dfd2e5
305 changed files with 4015 additions and 3947 deletions
+115 -238
View File
@@ -33,10 +33,6 @@ pub use crate::{
TransactionPriority, WeighData, Weight, WithPostDispatchInfo,
},
};
pub use frame_metadata::{
DecodeDifferent, DecodeDifferentArray, DefaultByte, DefaultByteGetter, ErrorMetadata,
FunctionArgumentMetadata, FunctionMetadata, ModuleConstantMetadata, ModuleErrorMetadata,
};
pub use sp_runtime::{traits::Dispatchable, DispatchError};
/// The return type of a `Dispatchable` in frame. When returned explicitly from
@@ -67,8 +63,8 @@ pub type CallableCallFor<A, R> = <A as Callable<R>>::Call;
/// A type that can be used as a parameter in a dispatchable function.
///
/// When using `decl_module` all arguments for call functions must implement this trait.
pub trait Parameter: Codec + EncodeLike + Clone + Eq + fmt::Debug {}
impl<T> Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {}
pub trait Parameter: Codec + EncodeLike + Clone + Eq + fmt::Debug + scale_info::TypeInfo {}
impl<T> Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug + scale_info::TypeInfo {}
/// Declares a `Module` struct and a `Call` enum, which implements the dispatch logic.
///
@@ -1169,7 +1165,7 @@ macro_rules! decl_module {
{ $( $on_finalize )* }
{ $( $offchain )* }
{ $( $constants )* }
{ &'static str }
{ __NO_ERROR_DEFINED }
{ $( $integrity_test )* }
{ $( $storage_version )* }
[ $($t)* ]
@@ -1239,7 +1235,7 @@ macro_rules! decl_module {
{ $( $on_finalize:tt )* }
{ $( $offchain:tt )* }
{ $( $constants:tt )* }
{ $error_type:ty }
{ $( $error_type:tt )* }
{ $( $integrity_test:tt )* }
{ $( $storage_version:tt )* }
[ $( $dispatchables:tt )* ]
@@ -1265,8 +1261,8 @@ macro_rules! decl_module {
{ $( $on_finalize )* }
{ $( $offchain )* }
{ $( $constants )* }
{ $error_type }
{ $( $integrity_test )* }
{ $( $error_type )* }
{ $( $integrity_test)* }
{ $( $storage_version )* }
[
$( $dispatchables )*
@@ -1750,7 +1746,6 @@ macro_rules! decl_module {
(@impl_function
$module:ident<$trait_instance:ident: $trait_name:ident$(<I>, $instance:ident: $instantiable:path)?>;
$origin_ty:ty;
$error_type:ty;
$ignore:ident;
$(#[$fn_attr:meta])*
$vis:vis fn $name:ident (
@@ -1772,7 +1767,6 @@ macro_rules! decl_module {
(@impl_function
$module:ident<$trait_instance:ident: $trait_name:ident$(<I>, $instance:ident: $instantiable:path)?>;
$origin_ty:ty;
$error_type:ty;
$ignore:ident;
$(#[$fn_attr:meta])*
$vis:vis fn $name:ident (
@@ -1796,7 +1790,7 @@ macro_rules! decl_module {
variant $fn_name:ident;
$( #[doc = $doc_attr:tt] )*
#[compact]
$type:ty;
$name:ident : $type:ty;
$( $rest:tt )*
) => {
$crate::decl_module! {
@@ -1808,7 +1802,7 @@ macro_rules! decl_module {
{
$( $current_params )*
#[codec(compact)]
$type,
$name: $type,
}
variant $fn_name;
$( #[doc = $doc_attr] )*
@@ -1825,7 +1819,7 @@ macro_rules! decl_module {
{ $( $current_params:tt )* }
variant $fn_name:ident;
$(#[doc = $doc_attr:tt])*
$type:ty;
$name:ident : $type:ty;
$( $rest:tt )*
) => {
$crate::decl_module! {
@@ -1836,7 +1830,7 @@ macro_rules! decl_module {
{ $( $generated_variants )* }
{
$( $current_params )*
$type,
$name: $type,
}
variant $fn_name;
$( #[doc = $doc_attr] )*
@@ -1866,9 +1860,9 @@ macro_rules! decl_module {
$( $generated_variants )*
#[allow(non_camel_case_types)]
$(#[doc = $doc_attr])*
$fn_name (
$fn_name {
$( $current_params )*
),
},
}
{}
$(
@@ -1888,7 +1882,8 @@ macro_rules! decl_module {
/// Dispatchable calls.
///
/// Each variant of this enum maps to a dispatchable function from the associated module.
#[derive($crate::codec::Encode, $crate::codec::Decode)]
#[derive($crate::codec::Encode, $crate::codec::Decode, $crate::scale_info::TypeInfo)]
#[scale_info(skip_type_params($trait_instance $(, $instance)?), capture_docs = "always")]
pub enum $call_type<$trait_instance: $trait_name$(<I>, $instance: $instantiable $( = $module_default_instance)?)?>
where $( $other_where_bounds )*
{
@@ -1965,7 +1960,7 @@ macro_rules! decl_module {
{ $( $on_finalize:tt )* }
{ $( $offchain:tt )* }
{ $( $constants:tt )* }
{ $error_type:ty }
{ $( $error_type:tt )* }
{ $( $integrity_test:tt )* }
{ $( $storage_version:tt )* }
) => {
@@ -2051,7 +2046,6 @@ macro_rules! decl_module {
@impl_function
$mod_type<$trait_instance: $trait_name $(<I>, $fn_instance: $fn_instantiable)?>;
$origin_type;
$error_type;
$from;
$(#[doc = $doc_attr])*
///
@@ -2076,11 +2070,28 @@ macro_rules! decl_module {
$(#[doc = $doc_attr])*
$(
$(#[$codec_attr])*
$param;
$param_name : $param;
)*
)*
}
$crate::paste::paste! {
impl<$trait_instance: $trait_name $(<I>, $instance: $instantiable)?>
$call_type<$trait_instance $(, $instance)?> where $( $other_where_bounds )*
{
$(
#[doc = "Create a call with the variant `" $fn_name "`."]
pub fn [< new_call_variant_ $fn_name >](
$( $param_name: $param ),*
) -> Self {
Self::$fn_name {
$( $param_name ),*
}
}
)*
}
}
$crate::decl_module! {
@impl_get_storage_version
$mod_type<$trait_instance: $trait_name $(<I>, $instance: $instantiable)?>;
@@ -2095,7 +2106,7 @@ macro_rules! decl_module {
fn get_dispatch_info(&self) -> $crate::dispatch::DispatchInfo {
match *self {
$(
$call_type::$fn_name( $( ref $param_name ),* ) => {
$call_type::$fn_name { $( ref $param_name ),* } => {
let __pallet_base_weight = $weight;
let __pallet_weight = <dyn $crate::dispatch::WeighData<( $( & $param, )* )>>::weigh_data(
&__pallet_base_weight,
@@ -2149,7 +2160,7 @@ macro_rules! decl_module {
fn get_call_name(&self) -> &'static str {
match *self {
$(
$call_type::$fn_name( $( ref $param_name ),* ) => {
$call_type::$fn_name { $( ref $param_name ),* } => {
// Don't generate any warnings for unused variables
let _ = ( $( $param_name ),* );
stringify!($fn_name)
@@ -2186,8 +2197,8 @@ macro_rules! decl_module {
fn clone(&self) -> Self {
match *self {
$(
$call_type::$fn_name( $( ref $param_name ),* ) =>
$call_type::$fn_name( $( (*$param_name).clone() ),* )
$call_type::$fn_name { $( ref $param_name ),* } =>
$call_type::$fn_name { $( $param_name: (*$param_name).clone() ),* }
,)*
_ => unreachable!(),
}
@@ -2200,9 +2211,9 @@ macro_rules! decl_module {
fn eq(&self, _other: &Self) -> bool {
match *self {
$(
$call_type::$fn_name( $( ref $param_name ),* ) => {
$call_type::$fn_name { $( ref $param_name ),* } => {
let self_params = ( $( $param_name, )* );
if let $call_type::$fn_name( $( ref $param_name ),* ) = *_other {
if let $call_type::$fn_name { $( ref $param_name ),* } = *_other {
self_params == ( $( $param_name, )* )
} else {
match *_other {
@@ -2230,7 +2241,7 @@ macro_rules! decl_module {
) -> $crate::dispatch::result::Result<(), $crate::dispatch::fmt::Error> {
match *self {
$(
$call_type::$fn_name( $( ref $param_name ),* ) =>
$call_type::$fn_name { $( ref $param_name ),* } =>
write!(_f, "{}{:?}",
stringify!($fn_name),
( $( $param_name.clone(), )* )
@@ -2248,7 +2259,7 @@ macro_rules! decl_module {
fn dispatch_bypass_filter(self, _origin: Self::Origin) -> $crate::dispatch::DispatchResultWithPostInfo {
match self {
$(
$call_type::$fn_name( $( $param_name ),* ) => {
$call_type::$fn_name { $( $param_name ),* } => {
$crate::decl_module!(
@call
$from
@@ -2277,20 +2288,17 @@ macro_rules! decl_module {
)*
}
}
$crate::__impl_error_metadata! {
$mod_type<$trait_instance: $trait_name $(<I>, $instance: $instantiable)?>
{ $( $other_where_bounds )* }
$( $error_type )*
}
$crate::__impl_module_constants_metadata ! {
$mod_type<$trait_instance: $trait_name $(<I>, $instance: $instantiable)?>
{ $( $other_where_bounds )* }
$( $constants )*
}
impl<$trait_instance: $trait_name $(<I>, $instance: $instantiable)?> $crate::dispatch::ModuleErrorMetadata
for $mod_type<$trait_instance $(, $instance)?> where $( $other_where_bounds )*
{
fn metadata() -> &'static [$crate::dispatch::ErrorMetadata] {
<$error_type as $crate::dispatch::ModuleErrorMetadata>::metadata()
}
}
$crate::__generate_dummy_part_checker!();
}
}
@@ -2302,6 +2310,7 @@ macro_rules! __dispatch_impl_metadata {
(
$mod_type:ident<$trait_instance:ident: $trait_name:ident$(<I>, $instance:ident: $instantiable:path)?>
{ $( $other_where_bounds:tt )* }
$call_type:ident
$($rest:tt)*
) => {
impl<$trait_instance: $trait_name $(<I>, $instance: $instantiable)?> $mod_type<$trait_instance $(, $instance)?>
@@ -2309,13 +2318,51 @@ macro_rules! __dispatch_impl_metadata {
{
#[doc(hidden)]
#[allow(dead_code)]
pub fn call_functions() -> &'static [$crate::dispatch::FunctionMetadata] {
$crate::__call_to_functions!($($rest)*)
pub fn call_functions() -> $crate::metadata::PalletCallMetadata {
$crate::scale_info::meta_type::<$call_type<$trait_instance $(, $instance)?>>().into()
}
}
}
}
/// Implement metadata for pallet error.
#[macro_export]
#[doc(hidden)]
macro_rules! __impl_error_metadata {
(
$mod_type:ident<$trait_instance:ident: $trait_name:ident$(<I>, $instance:ident: $instantiable:path)?>
{ $( $other_where_bounds:tt )* }
__NO_ERROR_DEFINED
) => {
impl<$trait_instance: $trait_name $(<I>, $instance: $instantiable)?> $mod_type<$trait_instance $(, $instance)?>
where $( $other_where_bounds )*
{
#[doc(hidden)]
#[allow(dead_code)]
pub fn error_metadata() -> Option<$crate::metadata::PalletErrorMetadata> {
None
}
}
};
(
$mod_type:ident<$trait_instance:ident: $trait_name:ident$(<I>, $instance:ident: $instantiable:path)?>
{ $( $other_where_bounds:tt )* }
$( $error_type:tt )*
) => {
impl<$trait_instance: $trait_name $(<I>, $instance: $instantiable)?> $mod_type<$trait_instance $(, $instance)?>
where $( $other_where_bounds )*
{
#[doc(hidden)]
#[allow(dead_code)]
pub fn error_metadata() -> Option<$crate::metadata::PalletErrorMetadata> {
Some($crate::metadata::PalletErrorMetadata {
ty: $crate::scale_info::meta_type::<$( $error_type )*>()
})
}
}
};
}
/// Implement metadata for module constants.
#[macro_export]
#[doc(hidden)]
@@ -2383,7 +2430,7 @@ macro_rules! __impl_module_constants_metadata {
{
#[doc(hidden)]
#[allow(dead_code)]
pub fn module_constants_metadata() -> &'static [$crate::dispatch::ModuleConstantMetadata] {
pub fn pallet_constants_metadata() -> $crate::sp_std::vec::Vec<$crate::metadata::PalletConstantMetadata> {
// Create the `ByteGetter`s
$(
#[allow(non_upper_case_types)]
@@ -2397,40 +2444,23 @@ macro_rules! __impl_module_constants_metadata {
>);
impl<$const_trait_instance: 'static + $const_trait_name $(
<I>, $const_instance: $const_instantiable)?
> $crate::dispatch::DefaultByte
for $default_byte_name <$const_trait_instance $(, $const_instance)?>
> $default_byte_name <$const_trait_instance $(, $const_instance)?>
{
fn default_byte(&self) -> $crate::dispatch::Vec<u8> {
let value: $type = $value;
$crate::dispatch::Encode::encode(&value)
}
}
unsafe impl<$const_trait_instance: 'static + $const_trait_name $(
<I>, $const_instance: $const_instantiable)?
> Send for $default_byte_name <$const_trait_instance $(, $const_instance)?> {}
unsafe impl<$const_trait_instance: 'static + $const_trait_name $(
<I>, $const_instance: $const_instantiable)?
> Sync for $default_byte_name <$const_trait_instance $(, $const_instance)?> {}
)*
&[
$crate::sp_std::vec![
$(
$crate::dispatch::ModuleConstantMetadata {
name: $crate::dispatch::DecodeDifferent::Encode(stringify!($name)),
ty: $crate::dispatch::DecodeDifferent::Encode(stringify!($type)),
value: $crate::dispatch::DecodeDifferent::Encode(
$crate::dispatch::DefaultByteGetter(
&$default_byte_name::<
$const_trait_instance $(, $const_instance)?
>(
$crate::dispatch::marker::PhantomData
)
)
),
documentation: $crate::dispatch::DecodeDifferent::Encode(
&[ $( $doc_attr ),* ]
),
$crate::metadata::PalletConstantMetadata {
name: stringify!($name),
ty: $crate::scale_info::meta_type::<$type>(),
value: $default_byte_name::<$const_trait_instance $(, $const_instance)?>(
Default::default()
).default_byte(),
docs: $crate::sp_std::vec![ $( $doc_attr ),* ],
}
),*
]
@@ -2439,106 +2469,6 @@ macro_rules! __impl_module_constants_metadata {
}
}
/// Convert the list of calls into their JSON representation, joined by ",".
#[macro_export]
#[doc(hidden)]
macro_rules! __call_to_functions {
(
$call_type:ident $origin_type:ty
{
$(
$(#[doc = $doc_attr:tt])*
fn $fn_name:ident($from:ident
$(
, $(#[$codec_attr:ident])* $param_name:ident : $param:ty
)*
);
)*
}
) => {
$crate::__functions_to_metadata!(0; $origin_type;; $(
fn $fn_name( $($(#[$codec_attr])* $param_name: $param ),* );
$( $doc_attr ),*;
)*)
};
}
/// Convert a list of functions into a list of `FunctionMetadata` items.
#[macro_export]
#[doc(hidden)]
macro_rules! __functions_to_metadata{
(
$fn_id:expr;
$origin_type:ty;
$( $function_metadata:expr ),*;
fn $fn_name:ident(
$(
$(#[$codec_attr:ident])* $param_name:ident : $param:ty
),*
);
$( $fn_doc:expr ),*;
$( $rest:tt )*
) => {
$crate::__functions_to_metadata!(
$fn_id + 1; $origin_type;
$( $function_metadata, )* $crate::__function_to_metadata!(
fn $fn_name($( $(#[$codec_attr])* $param_name : $param ),*); $( $fn_doc ),*; $fn_id;
);
$($rest)*
)
};
(
$fn_id:expr;
$origin_type:ty;
$( $function_metadata:expr ),*;
) => {
&[ $( $function_metadata ),* ]
}
}
/// Convert a function into its metadata representation.
#[macro_export]
#[doc(hidden)]
macro_rules! __function_to_metadata {
(
fn $fn_name:ident(
$( $(#[$codec_attr:ident])* $param_name:ident : $param:ty),*
);
$( $fn_doc:expr ),*;
$fn_id:expr;
) => {
$crate::dispatch::FunctionMetadata {
name: $crate::dispatch::DecodeDifferent::Encode(stringify!($fn_name)),
arguments: $crate::dispatch::DecodeDifferent::Encode(&[
$(
$crate::dispatch::FunctionArgumentMetadata {
name: $crate::dispatch::DecodeDifferent::Encode(stringify!($param_name)),
ty: $crate::dispatch::DecodeDifferent::Encode(
$crate::__function_to_metadata!(@stringify_expand_attr
$(#[$codec_attr])* $param_name: $param
)
),
}
),*
]),
documentation: $crate::dispatch::DecodeDifferent::Encode(&[ $( $fn_doc ),* ]),
}
};
(@stringify_expand_attr #[compact] $param_name:ident : $param:ty) => {
concat!("Compact<", stringify!($param), ">")
};
(@stringify_expand_attr $param_name:ident : $param:ty) => { stringify!($param) };
(@stringify_expand_attr $(#[codec_attr:ident])* $param_name:ident : $param:ty) => {
compile_error!(concat!(
"Invalid attribute for parameter `", stringify!($param_name),
"`, the following attributes are supported: `#[compact]`"
));
}
}
#[macro_export]
#[doc(hidden)]
macro_rules! __check_reserved_fn_name {
@@ -2597,6 +2527,7 @@ macro_rules! __check_reserved_fn_name {
mod tests {
use super::*;
use crate::{
metadata::*,
traits::{
Get, GetCallName, IntegrityTest, OnFinalize, OnIdle, OnInitialize, OnRuntimeUpgrade,
PalletInfo,
@@ -2623,7 +2554,7 @@ mod tests {
type DbWeight: Get<RuntimeDbWeight>;
}
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)]
#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, scale_info::TypeInfo)]
pub enum RawOrigin<AccountId> {
Root,
Signed(AccountId),
@@ -2679,68 +2610,7 @@ mod tests {
}
}
const EXPECTED_METADATA: &'static [FunctionMetadata] = &[
FunctionMetadata {
name: DecodeDifferent::Encode("aux_0"),
arguments: DecodeDifferent::Encode(&[]),
documentation: DecodeDifferent::Encode(&[" Hi, this is a comment."]),
},
FunctionMetadata {
name: DecodeDifferent::Encode("aux_1"),
arguments: DecodeDifferent::Encode(&[FunctionArgumentMetadata {
name: DecodeDifferent::Encode("_data"),
ty: DecodeDifferent::Encode("Compact<u32>"),
}]),
documentation: DecodeDifferent::Encode(&[]),
},
FunctionMetadata {
name: DecodeDifferent::Encode("aux_2"),
arguments: DecodeDifferent::Encode(&[
FunctionArgumentMetadata {
name: DecodeDifferent::Encode("_data"),
ty: DecodeDifferent::Encode("i32"),
},
FunctionArgumentMetadata {
name: DecodeDifferent::Encode("_data2"),
ty: DecodeDifferent::Encode("String"),
},
]),
documentation: DecodeDifferent::Encode(&[]),
},
FunctionMetadata {
name: DecodeDifferent::Encode("aux_3"),
arguments: DecodeDifferent::Encode(&[]),
documentation: DecodeDifferent::Encode(&[]),
},
FunctionMetadata {
name: DecodeDifferent::Encode("aux_4"),
arguments: DecodeDifferent::Encode(&[FunctionArgumentMetadata {
name: DecodeDifferent::Encode("_data"),
ty: DecodeDifferent::Encode("i32"),
}]),
documentation: DecodeDifferent::Encode(&[]),
},
FunctionMetadata {
name: DecodeDifferent::Encode("aux_5"),
arguments: DecodeDifferent::Encode(&[
FunctionArgumentMetadata {
name: DecodeDifferent::Encode("_data"),
ty: DecodeDifferent::Encode("i32"),
},
FunctionArgumentMetadata {
name: DecodeDifferent::Encode("_data2"),
ty: DecodeDifferent::Encode("Compact<u32>"),
},
]),
documentation: DecodeDifferent::Encode(&[]),
},
FunctionMetadata {
name: DecodeDifferent::Encode("operational"),
arguments: DecodeDifferent::Encode(&[]),
documentation: DecodeDifferent::Encode(&[]),
},
];
#[derive(scale_info::TypeInfo)]
pub struct TraitImpl {}
impl Config for TraitImpl {}
@@ -2823,17 +2693,19 @@ mod tests {
#[test]
fn module_json_metadata() {
let metadata = Module::<TraitImpl>::call_functions();
assert_eq!(EXPECTED_METADATA, metadata);
let expected_metadata =
PalletCallMetadata { ty: scale_info::meta_type::<Call<TraitImpl>>() };
assert_eq!(expected_metadata, metadata);
}
#[test]
fn compact_attr() {
let call: Call<TraitImpl> = Call::aux_1(1);
let call: Call<TraitImpl> = Call::aux_1 { _data: 1 };
let encoded = call.encode();
assert_eq!(2, encoded.len());
assert_eq!(vec![1, 4], encoded);
let call: Call<TraitImpl> = Call::aux_5(1, 2);
let call: Call<TraitImpl> = Call::aux_5 { _data: 1, _data2: 2 };
let encoded = call.encode();
assert_eq!(6, encoded.len());
assert_eq!(vec![5, 1, 0, 0, 0, 8], encoded);
@@ -2841,13 +2713,13 @@ mod tests {
#[test]
fn encode_is_correct_and_decode_works() {
let call: Call<TraitImpl> = Call::aux_0();
let call: Call<TraitImpl> = Call::aux_0 {};
let encoded = call.encode();
assert_eq!(vec![0], encoded);
let decoded = Call::<TraitImpl>::decode(&mut &encoded[..]).unwrap();
assert_eq!(decoded, call);
let call: Call<TraitImpl> = Call::aux_2(32, "hello".into());
let call: Call<TraitImpl> = Call::aux_2 { _data: 32, _data2: "hello".into() };
let encoded = call.encode();
assert_eq!(vec![2, 32, 0, 0, 0, 20, 104, 101, 108, 108, 111], encoded);
let decoded = Call::<TraitImpl>::decode(&mut &encoded[..]).unwrap();
@@ -2899,19 +2771,19 @@ mod tests {
fn weight_should_attach_to_call_enum() {
// operational.
assert_eq!(
Call::<TraitImpl>::operational().get_dispatch_info(),
Call::<TraitImpl>::operational {}.get_dispatch_info(),
DispatchInfo { weight: 5, class: DispatchClass::Operational, pays_fee: Pays::Yes },
);
// custom basic
assert_eq!(
Call::<TraitImpl>::aux_3().get_dispatch_info(),
Call::<TraitImpl>::aux_3 {}.get_dispatch_info(),
DispatchInfo { weight: 3, class: DispatchClass::Normal, pays_fee: Pays::Yes },
);
}
#[test]
fn call_name() {
let name = Call::<TraitImpl>::aux_3().get_call_name();
let name = Call::<TraitImpl>::aux_3 {}.get_call_name();
assert_eq!("aux_3", name);
}
@@ -2929,4 +2801,9 @@ mod tests {
fn integrity_test_should_work() {
<Module<TraitImpl> as IntegrityTest>::integrity_test();
}
#[test]
fn test_new_call_variant() {
Call::<TraitImpl>::new_call_variant_aux_0();
}
}
+3 -20
View File
@@ -17,8 +17,6 @@
//! Macro for declaring a module error.
#[doc(hidden)]
pub use frame_metadata::{DecodeDifferent, ErrorMetadata, ModuleErrorMetadata};
#[doc(hidden)]
pub use sp_runtime::traits::{BadOrigin, LookupError};
@@ -87,10 +85,13 @@ macro_rules! decl_error {
}
) => {
$(#[$attr])*
#[derive($crate::scale_info::TypeInfo)]
#[scale_info(skip_type_params($generic $(, $inst_generic)?), capture_docs = "always")]
pub enum $error<$generic: $trait $(, $inst_generic: $instance)?>
$( where $( $where_ty: $where_bound ),* )?
{
#[doc(hidden)]
#[codec(skip)]
__Ignore(
$crate::sp_std::marker::PhantomData<($generic, $( $inst_generic)?)>,
$crate::Never,
@@ -159,24 +160,6 @@ macro_rules! decl_error {
}
}
}
impl<$generic: $trait $(, $inst_generic: $instance)?> $crate::error::ModuleErrorMetadata
for $error<$generic $(, $inst_generic)?>
$( where $( $where_ty: $where_bound ),* )?
{
fn metadata() -> &'static [$crate::error::ErrorMetadata] {
&[
$(
$crate::error::ErrorMetadata {
name: $crate::error::DecodeDifferent::Encode(stringify!($name)),
documentation: $crate::error::DecodeDifferent::Encode(&[
$( $doc_attr ),*
]),
}
),*
]
}
}
};
(@GENERATE_AS_U8
$self:ident
+4 -264
View File
@@ -21,8 +21,6 @@
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
pub use frame_metadata::{DecodeDifferent, EventMetadata, FnEncode, OuterEventMetadata};
/// Implement the `Event` for a module.
///
/// # Simple Event Example:
@@ -129,8 +127,10 @@ macro_rules! decl_event {
Clone, PartialEq, Eq,
$crate::codec::Encode,
$crate::codec::Decode,
$crate::scale_info::TypeInfo,
$crate::RuntimeDebug,
)]
#[scale_info(capture_docs = "always")]
/// Events for this module.
///
$(#[$attr])*
@@ -142,13 +142,6 @@ macro_rules! decl_event {
impl From<Event> for () {
fn from(_: Event) -> () { () }
}
impl Event {
#[allow(dead_code)]
#[doc(hidden)]
pub fn metadata() -> &'static [ $crate::event::EventMetadata ] {
$crate::__events_to_metadata!(; $( $events )* )
}
}
}
}
@@ -272,8 +265,10 @@ macro_rules! __decl_generic_event {
Clone, PartialEq, Eq,
$crate::codec::Encode,
$crate::codec::Decode,
$crate::scale_info::TypeInfo,
$crate::RuntimeDebug,
)]
#[scale_info(capture_docs = "always")]
/// Events for this module.
///
$(#[$attr])*
@@ -290,263 +285,8 @@ macro_rules! __decl_generic_event {
impl<$( $generic_param ),* $(, $instance)? > From<RawEvent<$( $generic_param ),* $(, $instance)?>> for () {
fn from(_: RawEvent<$( $generic_param ),* $(, $instance)?>) -> () { () }
}
impl<$( $generic_param ),* $(, $instance)?> RawEvent<$( $generic_param ),* $(, $instance)?> {
#[allow(dead_code)]
#[doc(hidden)]
pub fn metadata() -> &'static [$crate::event::EventMetadata] {
$crate::__events_to_metadata!(; $( $events )* )
}
}
};
(@cannot_parse $ty:ty) => {
compile_error!(concat!("The type `", stringify!($ty), "` can't be parsed as an unnamed one, please name it `Name = ", stringify!($ty), "`"));
}
}
#[macro_export]
#[doc(hidden)]
macro_rules! __events_to_metadata {
(
$( $metadata:expr ),*;
$( #[doc = $doc_attr:tt] )*
$event:ident $( ( $( $param:path ),* $(,)? ) )*,
$( $rest:tt )*
) => {
$crate::__events_to_metadata!(
$( $metadata, )*
$crate::event::EventMetadata {
name: $crate::event::DecodeDifferent::Encode(stringify!($event)),
arguments: $crate::event::DecodeDifferent::Encode(&[
$( $( stringify!($param) ),* )*
]),
documentation: $crate::event::DecodeDifferent::Encode(&[
$( $doc_attr ),*
]),
};
$( $rest )*
)
};
(
$( $metadata:expr ),*;
) => {
&[ $( $metadata ),* ]
}
}
#[cfg(test)]
#[allow(dead_code)]
mod tests {
use super::*;
use codec::{Decode, Encode};
use serde::Serialize;
mod system {
pub trait Config: 'static {
type Origin;
type BlockNumber;
type PalletInfo: crate::traits::PalletInfo;
type DbWeight: crate::traits::Get<crate::weights::RuntimeDbWeight>;
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin, system=self {}
}
decl_event!(
pub enum Event {
SystemEvent,
}
);
}
mod system_renamed {
pub trait Config: 'static {
type Origin;
type BlockNumber;
type PalletInfo: crate::traits::PalletInfo;
type DbWeight: crate::traits::Get<crate::weights::RuntimeDbWeight>;
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin, system=self {}
}
decl_event!(
pub enum Event {
SystemEvent,
}
);
}
mod event_module {
use super::system;
pub trait Config: system::Config {
type Balance;
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin, system=system {}
}
decl_event!(
/// Event without renaming the generic parameter `Balance` and `Origin`.
pub enum Event<T> where <T as Config>::Balance, <T as system::Config>::Origin
{
/// Hi, I am a comment.
TestEvent(Balance, Origin),
/// Dog
EventWithoutParams,
}
);
}
mod event_module2 {
use super::system;
pub trait Config: system::Config {
type Balance;
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin, system=system {}
}
decl_event!(
/// Event with renamed generic parameter
pub enum Event<T>
where
BalanceRenamed = <T as Config>::Balance,
OriginRenamed = <T as system::Config>::Origin,
{
TestEvent(BalanceRenamed),
TestOrigin(OriginRenamed),
}
);
}
mod event_module3 {
decl_event!(
pub enum Event {
HiEvent,
}
);
}
mod event_module4 {
use super::system;
pub trait Config: system::Config {
type Balance;
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin, system=system {}
}
decl_event!(
/// Event finish formatting on an unnamed one with trailing comma
pub enum Event<T> where
<T as Config>::Balance,
<T as system::Config>::Origin,
{
TestEvent(Balance, Origin),
}
);
}
mod event_module5 {
use super::system;
pub trait Config: system::Config {
type Balance;
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin, system=system {}
}
decl_event!(
/// Event finish formatting on an named one with trailing comma
pub enum Event<T>
where
BalanceRenamed = <T as Config>::Balance,
OriginRenamed = <T as system::Config>::Origin,
{
TestEvent(BalanceRenamed, OriginRenamed),
TrailingCommaInArgs(u32, u32),
}
);
}
#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, Serialize)]
pub struct TestRuntime;
#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, Serialize)]
pub struct TestRuntime2;
impl event_module::Config for TestRuntime {
type Balance = u32;
}
impl event_module2::Config for TestRuntime {
type Balance = u32;
}
impl system::Config for TestRuntime {
type Origin = u32;
type BlockNumber = u32;
type PalletInfo = crate::tests::PanicPalletInfo;
type DbWeight = ();
}
#[test]
fn event_metadata() {
assert_eq!(
system_renamed::Event::metadata(),
&[EventMetadata {
name: DecodeDifferent::Encode("SystemEvent"),
arguments: DecodeDifferent::Encode(&[]),
documentation: DecodeDifferent::Encode(&[]),
},]
);
assert_eq!(
event_module::Event::<TestRuntime>::metadata(),
&[
EventMetadata {
name: DecodeDifferent::Encode("TestEvent"),
arguments: DecodeDifferent::Encode(&["Balance", "Origin"]),
documentation: DecodeDifferent::Encode(&[" Hi, I am a comment."])
},
EventMetadata {
name: DecodeDifferent::Encode("EventWithoutParams"),
arguments: DecodeDifferent::Encode(&[]),
documentation: DecodeDifferent::Encode(&[" Dog"]),
},
]
);
assert_eq!(
event_module2::Event::<TestRuntime>::metadata(),
&[
EventMetadata {
name: DecodeDifferent::Encode("TestEvent"),
arguments: DecodeDifferent::Encode(&["BalanceRenamed"]),
documentation: DecodeDifferent::Encode(&[])
},
EventMetadata {
name: DecodeDifferent::Encode("TestOrigin"),
arguments: DecodeDifferent::Encode(&["OriginRenamed"]),
documentation: DecodeDifferent::Encode(&[]),
},
]
);
assert_eq!(
event_module3::Event::metadata(),
&[EventMetadata {
name: DecodeDifferent::Encode("HiEvent"),
arguments: DecodeDifferent::Encode(&[]),
documentation: DecodeDifferent::Encode(&[])
}],
);
}
}
+9 -8
View File
@@ -17,6 +17,7 @@
//! Hash utilities.
use crate::metadata;
use codec::{Codec, MaxEncodedLen};
use sp_io::hashing::{blake2_128, blake2_256, twox_128, twox_256, twox_64};
use sp_std::prelude::Vec;
@@ -58,7 +59,7 @@ impl<T: Codec> Hashable for T {
/// Hasher to use to hash keys to insert to storage.
pub trait StorageHasher: 'static {
const METADATA: frame_metadata::StorageHasher;
const METADATA: metadata::StorageHasher;
type Output: AsRef<[u8]>;
fn hash(x: &[u8]) -> Self::Output;
@@ -79,7 +80,7 @@ pub trait ReversibleStorageHasher: StorageHasher {
/// Store the key directly.
pub struct Identity;
impl StorageHasher for Identity {
const METADATA: frame_metadata::StorageHasher = frame_metadata::StorageHasher::Identity;
const METADATA: metadata::StorageHasher = metadata::StorageHasher::Identity;
type Output = Vec<u8>;
fn hash(x: &[u8]) -> Vec<u8> {
x.to_vec()
@@ -97,7 +98,7 @@ impl ReversibleStorageHasher for Identity {
/// Hash storage keys with `concat(twox64(key), key)`
pub struct Twox64Concat;
impl StorageHasher for Twox64Concat {
const METADATA: frame_metadata::StorageHasher = frame_metadata::StorageHasher::Twox64Concat;
const METADATA: metadata::StorageHasher = metadata::StorageHasher::Twox64Concat;
type Output = Vec<u8>;
fn hash(x: &[u8]) -> Vec<u8> {
twox_64(x).iter().chain(x.into_iter()).cloned().collect::<Vec<_>>()
@@ -119,7 +120,7 @@ impl ReversibleStorageHasher for Twox64Concat {
/// Hash storage keys with `concat(blake2_128(key), key)`
pub struct Blake2_128Concat;
impl StorageHasher for Blake2_128Concat {
const METADATA: frame_metadata::StorageHasher = frame_metadata::StorageHasher::Blake2_128Concat;
const METADATA: metadata::StorageHasher = metadata::StorageHasher::Blake2_128Concat;
type Output = Vec<u8>;
fn hash(x: &[u8]) -> Vec<u8> {
blake2_128(x).iter().chain(x.into_iter()).cloned().collect::<Vec<_>>()
@@ -141,7 +142,7 @@ impl ReversibleStorageHasher for Blake2_128Concat {
/// Hash storage keys with blake2 128
pub struct Blake2_128;
impl StorageHasher for Blake2_128 {
const METADATA: frame_metadata::StorageHasher = frame_metadata::StorageHasher::Blake2_128;
const METADATA: metadata::StorageHasher = metadata::StorageHasher::Blake2_128;
type Output = [u8; 16];
fn hash(x: &[u8]) -> [u8; 16] {
blake2_128(x)
@@ -154,7 +155,7 @@ impl StorageHasher for Blake2_128 {
/// Hash storage keys with blake2 256
pub struct Blake2_256;
impl StorageHasher for Blake2_256 {
const METADATA: frame_metadata::StorageHasher = frame_metadata::StorageHasher::Blake2_256;
const METADATA: metadata::StorageHasher = metadata::StorageHasher::Blake2_256;
type Output = [u8; 32];
fn hash(x: &[u8]) -> [u8; 32] {
blake2_256(x)
@@ -167,7 +168,7 @@ impl StorageHasher for Blake2_256 {
/// Hash storage keys with twox 128
pub struct Twox128;
impl StorageHasher for Twox128 {
const METADATA: frame_metadata::StorageHasher = frame_metadata::StorageHasher::Twox128;
const METADATA: metadata::StorageHasher = metadata::StorageHasher::Twox128;
type Output = [u8; 16];
fn hash(x: &[u8]) -> [u8; 16] {
twox_128(x)
@@ -180,7 +181,7 @@ impl StorageHasher for Twox128 {
/// Hash storage keys with twox 256
pub struct Twox256;
impl StorageHasher for Twox256 {
const METADATA: frame_metadata::StorageHasher = frame_metadata::StorageHasher::Twox256;
const METADATA: metadata::StorageHasher = metadata::StorageHasher::Twox256;
type Output = [u8; 32];
fn hash(x: &[u8]) -> [u8; 32] {
twox_256(x)
+104 -150
View File
@@ -36,6 +36,8 @@ pub use log;
pub use once_cell;
#[doc(hidden)]
pub use paste;
#[doc(hidden)]
pub use scale_info;
#[cfg(feature = "std")]
pub use serde;
pub use sp_core::Void;
@@ -90,17 +92,18 @@ pub use self::{
pub use sp_runtime::{self, print, traits::Printable, ConsensusEngineId};
use codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_runtime::TypeId;
/// A unified log target for support operations.
pub const LOG_TARGET: &'static str = "runtime::frame-support";
/// A type that cannot be instantiated.
#[derive(Debug, PartialEq, Eq, Clone)]
#[derive(Debug, PartialEq, Eq, Clone, TypeInfo)]
pub enum Never {}
/// A pallet identifier. These are per pallet and should be stored in a registry somewhere.
#[derive(Clone, Copy, Eq, PartialEq, Encode, Decode)]
#[derive(Clone, Copy, Eq, PartialEq, Encode, Decode, TypeInfo)]
pub struct PalletId(pub [u8; 8]);
impl TypeId for PalletId {
@@ -811,13 +814,13 @@ pub use serde::{Deserialize, Serialize};
#[cfg(test)]
pub mod tests {
use super::*;
use codec::{Codec, EncodeLike};
use frame_metadata::{
DecodeDifferent, DefaultByteGetter, StorageEntryMetadata, StorageEntryModifier,
StorageEntryType, StorageHasher, StorageMetadata,
use crate::metadata::{
PalletStorageMetadata, StorageEntryMetadata, StorageEntryModifier, StorageEntryType,
StorageHasher,
};
use codec::{Codec, EncodeLike};
use sp_io::TestExternalities;
use sp_std::{marker::PhantomData, result};
use sp_std::result;
/// A PalletInfo implementation which just panics.
pub struct PanicPalletInfo;
@@ -832,7 +835,7 @@ pub mod tests {
}
pub trait Config: 'static {
type BlockNumber: Codec + EncodeLike + Default;
type BlockNumber: Codec + EncodeLike + Default + TypeInfo;
type Origin;
type PalletInfo: crate::traits::PalletInfo;
type DbWeight: crate::traits::Get<crate::weights::RuntimeDbWeight>;
@@ -1150,132 +1153,109 @@ pub mod tests {
});
}
const EXPECTED_METADATA: StorageMetadata = StorageMetadata {
prefix: DecodeDifferent::Encode("Test"),
entries: DecodeDifferent::Encode(&[
StorageEntryMetadata {
name: DecodeDifferent::Encode("Data"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map {
hasher: StorageHasher::Twox64Concat,
key: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("u64"),
unused: false,
fn expected_metadata() -> PalletStorageMetadata {
PalletStorageMetadata {
prefix: "Test",
entries: vec![
StorageEntryMetadata {
name: "Data",
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map {
hashers: vec![StorageHasher::Twox64Concat],
key: scale_info::meta_type::<u32>(),
value: scale_info::meta_type::<u64>(),
},
default: vec![0, 0, 0, 0, 0, 0, 0, 0],
docs: vec![],
},
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructData(
PhantomData::<Test>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("OptionLinkedMap"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Map {
hasher: StorageHasher::Blake2_128Concat,
key: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("u32"),
unused: false,
StorageEntryMetadata {
name: "OptionLinkedMap",
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Map {
hashers: vec![StorageHasher::Blake2_128Concat],
key: scale_info::meta_type::<u32>(),
value: scale_info::meta_type::<u32>(),
},
default: vec![0],
docs: vec![],
},
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructOptionLinkedMap(PhantomData::<Test>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GenericData"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map {
hasher: StorageHasher::Identity,
key: DecodeDifferent::Encode("T::BlockNumber"),
value: DecodeDifferent::Encode("T::BlockNumber"),
unused: false,
StorageEntryMetadata {
name: "GenericData",
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map {
hashers: vec![StorageHasher::Identity],
key: scale_info::meta_type::<u32>(),
value: scale_info::meta_type::<u32>(),
},
default: vec![0, 0, 0, 0],
docs: vec![],
},
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructGenericData(
PhantomData::<Test>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GenericData2"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Map {
hasher: StorageHasher::Blake2_128Concat,
key: DecodeDifferent::Encode("T::BlockNumber"),
value: DecodeDifferent::Encode("T::BlockNumber"),
unused: false,
StorageEntryMetadata {
name: "GenericData2",
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Map {
hashers: vec![StorageHasher::Blake2_128Concat],
key: scale_info::meta_type::<u32>(),
value: scale_info::meta_type::<u32>(),
},
default: vec![0],
docs: vec![],
},
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructGenericData2(
PhantomData::<Test>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("DataDM"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::DoubleMap {
hasher: StorageHasher::Twox64Concat,
key1: DecodeDifferent::Encode("u32"),
key2: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("u64"),
key2_hasher: StorageHasher::Blake2_128Concat,
StorageEntryMetadata {
name: "DataDM",
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map {
hashers: vec![StorageHasher::Twox64Concat, StorageHasher::Blake2_128Concat],
key: scale_info::meta_type::<(u32, u32)>(),
value: scale_info::meta_type::<u64>(),
},
default: vec![0, 0, 0, 0, 0, 0, 0, 0],
docs: vec![],
},
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructDataDM(
PhantomData::<Test>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GenericDataDM"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::DoubleMap {
hasher: StorageHasher::Blake2_128Concat,
key1: DecodeDifferent::Encode("T::BlockNumber"),
key2: DecodeDifferent::Encode("T::BlockNumber"),
value: DecodeDifferent::Encode("T::BlockNumber"),
key2_hasher: StorageHasher::Identity,
StorageEntryMetadata {
name: "GenericDataDM",
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map {
hashers: vec![StorageHasher::Blake2_128Concat, StorageHasher::Identity],
key: scale_info::meta_type::<(u32, u32)>(),
value: scale_info::meta_type::<u32>(),
},
default: vec![0, 0, 0, 0],
docs: vec![],
},
default: DecodeDifferent::Encode(DefaultByteGetter(&__GetByteStructGenericDataDM(
PhantomData::<Test>,
))),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GenericData2DM"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::DoubleMap {
hasher: StorageHasher::Blake2_128Concat,
key1: DecodeDifferent::Encode("T::BlockNumber"),
key2: DecodeDifferent::Encode("T::BlockNumber"),
value: DecodeDifferent::Encode("T::BlockNumber"),
key2_hasher: StorageHasher::Twox64Concat,
StorageEntryMetadata {
name: "GenericData2DM",
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Map {
hashers: vec![StorageHasher::Blake2_128Concat, StorageHasher::Twox64Concat],
key: scale_info::meta_type::<(u32, u32)>(),
value: scale_info::meta_type::<u32>(),
},
default: vec![0],
docs: vec![],
},
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructGenericData2DM(PhantomData::<Test>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("AppendableDM"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::DoubleMap {
hasher: StorageHasher::Blake2_128Concat,
key1: DecodeDifferent::Encode("u32"),
key2: DecodeDifferent::Encode("T::BlockNumber"),
value: DecodeDifferent::Encode("Vec<u32>"),
key2_hasher: StorageHasher::Blake2_128Concat,
StorageEntryMetadata {
name: "AppendableDM",
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map {
hashers: vec![
StorageHasher::Blake2_128Concat,
StorageHasher::Blake2_128Concat,
],
key: scale_info::meta_type::<(u32, u32)>(),
value: scale_info::meta_type::<Vec<u32>>(),
},
default: vec![0],
docs: vec![],
},
default: DecodeDifferent::Encode(DefaultByteGetter(
&__GetByteStructGenericData2DM(PhantomData::<Test>),
)),
documentation: DecodeDifferent::Encode(&[]),
},
]),
};
],
}
}
#[test]
fn store_metadata() {
let metadata = Module::<Test>::storage_metadata();
pretty_assertions::assert_eq!(EXPECTED_METADATA, metadata);
pretty_assertions::assert_eq!(expected_metadata(), metadata);
}
parameter_types! {
@@ -1470,7 +1450,7 @@ pub mod pallet_prelude {
/// It implements on pallet:
/// * [`traits::GetStorageVersion`]
/// * [`traits::OnGenesis`]: contains some logic to write pallet version into storage.
/// * `ModuleErrorMetadata`: using error declared or no metadata.
/// * `PalletErrorTypeInfo`: provides the type information for the pallet error, if defined.
///
/// It declare `type Module` type alias for `Pallet`, used by [`construct_runtime`].
///
@@ -1623,9 +1603,6 @@ pub mod pallet_prelude {
/// The macro implements `From<Error<T>>` for `&'static str`.
/// The macro implements `From<Error<T>>` for `DispatchError`.
///
/// The macro implements `ModuleErrorMetadata` on `Pallet` defining the `ErrorMetadata` of the
/// pallet.
///
/// # Event: `#[pallet::event]` optional
///
/// Allow to define pallet events, pallet events are stored in the block when they deposited
@@ -1634,7 +1611,6 @@ pub mod pallet_prelude {
/// Item is defined as:
/// ```ignore
/// #[pallet::event]
/// #[pallet::metadata($SomeType = "$Metadata", $SomeOtherType = "$Metadata", ..)] // Optional
/// #[pallet::generate_deposit($visibility fn deposit_event)] // Optional
/// pub enum Event<$some_generic> $optional_where_clause {
/// /// Some doc
@@ -1649,24 +1625,6 @@ pub mod pallet_prelude {
/// std only).
/// For ease of use, bound the trait `Member` available in frame_support::pallet_prelude.
///
/// Variant documentations and field types are put into metadata.
/// The attribute `#[pallet::metadata(..)]` allows to specify the metadata to put for some
/// types.
///
/// The metadata of a type is defined by:
/// * if matching a type in `#[pallet::metadata(..)]`, then the corresponding metadata.
/// * otherwise the type stringified.
///
/// E.g.:
/// ```ignore
/// #[pallet::event]
/// #[pallet::metadata(u32 = "SpecialU32")]
/// pub enum Event<T: Config> {
/// Proposed(u32, T::AccountId),
/// }
/// ```
/// will write in event variant metadata `"SpecialU32"` and `"T::AccountId"`.
///
/// The attribute `#[pallet::generate_deposit($visibility fn deposit_event)]` generate a helper
/// function on `Pallet` to deposit event.
///
@@ -2027,8 +1985,6 @@ pub mod pallet_prelude {
/// //
/// // The macro generates event metadata, and derive Clone, Debug, Eq, PartialEq and Codec
/// #[pallet::event]
/// // Additional argument to specify the metadata to use for given type.
/// #[pallet::metadata(BalanceOf<T> = "Balance", u32 = "Other")]
/// // Generate a funciton on Pallet to deposit an event.
/// #[pallet::generate_deposit(pub(super) fn deposit_event)]
/// pub enum Event<T: Config> {
@@ -2192,7 +2148,6 @@ pub mod pallet_prelude {
/// }
///
/// #[pallet::event]
/// #[pallet::metadata(BalanceOf<T> = "Balance", u32 = "Other")]
/// #[pallet::generate_deposit(pub(super) fn deposit_event)]
/// pub enum Event<T: Config<I>, I: 'static = ()> {
/// /// doc comment put in metadata
@@ -2342,8 +2297,7 @@ pub mod pallet_prelude {
/// 7. **migrate event**:
/// rewrite as a simple enum under with the attribute `#[pallet::event]`,
/// use `#[pallet::generate_deposit($vis fn deposit_event)]` to generate deposit_event,
/// use `#[pallet::metadata(...)]` to configure the metadata for types in order not to break
/// them. 8. **migrate error**: rewrite it with attribute `#[pallet::error]`.
/// 8. **migrate error**: rewrite it with attribute `#[pallet::error]`.
/// 9. **migrate storage**:
/// decl_storage provide an upgrade template (see 3.). All storages, genesis config, genesis
/// build and default implementation of genesis config can be taken from it directly.
@@ -31,7 +31,8 @@ use sp_std::{
///
/// Unlike a standard `BTreeMap`, there is an enforced upper limit to the number of items in the
/// map. All internal operations ensure this bound is respected.
#[derive(Encode)]
#[derive(Encode, scale_info::TypeInfo)]
#[scale_info(skip_type_params(S))]
pub struct BoundedBTreeMap<K, V, S>(BTreeMap<K, V>, PhantomData<S>);
impl<K, V, S> Decode for BoundedBTreeMap<K, V, S>
@@ -37,7 +37,8 @@ use sp_std::{convert::TryFrom, fmt, marker::PhantomData, prelude::*};
///
/// As the name suggests, the length of the queue is always bounded. All internal operations ensure
/// this bound is respected.
#[derive(Encode)]
#[derive(Encode, scale_info::TypeInfo)]
#[scale_info(skip_type_params(S))]
pub struct BoundedVec<T, S>(Vec<T>, PhantomData<S>);
/// A bounded slice.
@@ -17,6 +17,7 @@
//! Stuff to do with the runtime's storage.
pub use self::types::StorageEntryMetadata;
use crate::{
hash::{ReversibleStorageHasher, StorageHasher},
storage::types::{
@@ -19,14 +19,14 @@
//! StoragePrefixedDoubleMap traits and their methods directly.
use crate::{
metadata::{StorageEntryModifier, StorageEntryType},
storage::{
types::{OnEmptyGetter, OptionQuery, QueryKindTrait},
types::{OptionQuery, QueryKindTrait, StorageEntryMetadata},
StorageAppend, StorageDecodeLength, StoragePrefixedMap, StorageTryAppend,
},
traits::{Get, GetDefault, StorageInfo, StorageInstance},
};
use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen};
use frame_metadata::{DefaultByteGetter, StorageEntryModifier};
use sp_arithmetic::traits::SaturatedConversion;
use sp_std::prelude::*;
@@ -511,37 +511,34 @@ where
}
}
/// Part of storage metadata for a storage double map.
///
/// NOTE: Generic hashers is supported.
pub trait StorageDoubleMapMetadata {
const MODIFIER: StorageEntryModifier;
const NAME: &'static str;
const DEFAULT: DefaultByteGetter;
const HASHER1: frame_metadata::StorageHasher;
const HASHER2: frame_metadata::StorageHasher;
}
impl<Prefix, Hasher1, Hasher2, Key1, Key2, Value, QueryKind, OnEmpty, MaxValues>
StorageDoubleMapMetadata
StorageEntryMetadata
for StorageDoubleMap<Prefix, Hasher1, Key1, Hasher2, Key2, Value, QueryKind, OnEmpty, MaxValues>
where
Prefix: StorageInstance,
Hasher1: crate::hash::StorageHasher,
Hasher2: crate::hash::StorageHasher,
Key1: FullCodec,
Key2: FullCodec,
Value: FullCodec,
Key1: FullCodec + scale_info::StaticTypeInfo,
Key2: FullCodec + scale_info::StaticTypeInfo,
Value: FullCodec + scale_info::StaticTypeInfo,
QueryKind: QueryKindTrait<Value, OnEmpty>,
OnEmpty: Get<QueryKind::Query> + 'static,
MaxValues: Get<Option<u32>>,
{
const MODIFIER: StorageEntryModifier = QueryKind::METADATA;
const HASHER1: frame_metadata::StorageHasher = Hasher1::METADATA;
const HASHER2: frame_metadata::StorageHasher = Hasher2::METADATA;
const NAME: &'static str = Prefix::STORAGE_PREFIX;
const DEFAULT: DefaultByteGetter =
DefaultByteGetter(&OnEmptyGetter::<QueryKind::Query, OnEmpty>(core::marker::PhantomData));
fn ty() -> StorageEntryType {
StorageEntryType::Map {
hashers: vec![Hasher1::METADATA, Hasher2::METADATA],
key: scale_info::meta_type::<(Key1, Key2)>(),
value: scale_info::meta_type::<Value>(),
}
}
fn default() -> Vec<u8> {
OnEmpty::get().encode()
}
}
impl<Prefix, Hasher1, Hasher2, Key1, Key2, Value, QueryKind, OnEmpty, MaxValues>
@@ -603,8 +600,12 @@ where
#[cfg(test)]
mod test {
use super::*;
use crate::{hash::*, storage::types::ValueQuery};
use frame_metadata::StorageEntryModifier;
use crate::{
hash::*,
metadata::{StorageEntryModifier, StorageEntryType, StorageHasher},
storage::types::ValueQuery,
};
use assert_matches::assert_matches;
use sp_io::{hashing::twox_128, TestExternalities};
struct Prefix;
@@ -768,19 +769,27 @@ mod test {
assert_eq!(A::MODIFIER, StorageEntryModifier::Optional);
assert_eq!(AValueQueryWithAnOnEmpty::MODIFIER, StorageEntryModifier::Default);
assert_eq!(A::HASHER1, frame_metadata::StorageHasher::Blake2_128Concat);
assert_eq!(A::HASHER2, frame_metadata::StorageHasher::Twox64Concat);
assert_eq!(
AValueQueryWithAnOnEmpty::HASHER1,
frame_metadata::StorageHasher::Blake2_128Concat
let assert_map_hashers = |ty, expected_hashers| {
if let StorageEntryType::Map { hashers, .. } = ty {
assert_eq!(hashers, expected_hashers)
} else {
assert_matches!(ty, StorageEntryType::Map { .. })
}
};
assert_map_hashers(
A::ty(),
vec![StorageHasher::Blake2_128Concat, StorageHasher::Twox64Concat],
);
assert_eq!(
AValueQueryWithAnOnEmpty::HASHER2,
frame_metadata::StorageHasher::Twox64Concat
assert_map_hashers(
AValueQueryWithAnOnEmpty::ty(),
vec![StorageHasher::Blake2_128Concat, StorageHasher::Twox64Concat],
);
assert_eq!(A::NAME, "foo");
assert_eq!(AValueQueryWithAnOnEmpty::DEFAULT.0.default_byte(), 97u32.encode());
assert_eq!(A::DEFAULT.0.default_byte(), Option::<u32>::None.encode());
assert_eq!(AValueQueryWithAnOnEmpty::default(), 97u32.encode());
assert_eq!(A::default(), Option::<u32>::None.encode());
WithLen::remove_all(None);
assert_eq!(WithLen::decode_len(3, 30), None);
@@ -20,6 +20,7 @@
use crate::hash::{ReversibleStorageHasher, StorageHasher};
use codec::{Encode, EncodeLike, FullCodec, MaxEncodedLen};
use paste::paste;
use scale_info::StaticTypeInfo;
use sp_std::prelude::*;
/// A type used exclusively by storage maps as their key type.
@@ -35,14 +36,14 @@ pub struct Key<Hasher, KeyType>(core::marker::PhantomData<(Hasher, KeyType)>);
/// A trait that contains the current key as an associated type.
pub trait KeyGenerator {
type Key: EncodeLike<Self::Key>;
type Key: EncodeLike<Self::Key> + StaticTypeInfo;
type KArg: Encode;
type HashFn: FnOnce(&[u8]) -> Vec<u8>;
type HArg;
const HASHER_METADATA: &'static [frame_metadata::StorageHasher];
const HASHER_METADATA: &'static [crate::metadata::StorageHasher];
/// Given a `key` tuple, calculate the final key by encoding each element individuallly and
/// Given a `key` tuple, calculate the final key by encoding each element individually and
/// hashing them using the corresponding hasher in the `KeyGenerator`.
fn final_key<KArg: EncodeLikeTuple<Self::KArg> + TupleToEncodedIter>(key: KArg) -> Vec<u8>;
/// Given a `key` tuple, migrate the keys from using the old hashers as given by `hash_fns`
@@ -67,13 +68,13 @@ pub trait KeyGeneratorInner: KeyGenerator {
fn final_hash(encoded: &[u8]) -> Vec<u8>;
}
impl<H: StorageHasher, K: FullCodec> KeyGenerator for Key<H, K> {
impl<H: StorageHasher, K: FullCodec + StaticTypeInfo> KeyGenerator for Key<H, K> {
type Key = K;
type KArg = (K,);
type HashFn = Box<dyn FnOnce(&[u8]) -> Vec<u8>>;
type HArg = (Self::HashFn,);
const HASHER_METADATA: &'static [frame_metadata::StorageHasher] = &[H::METADATA];
const HASHER_METADATA: &'static [crate::metadata::StorageHasher] = &[H::METADATA];
fn final_key<KArg: EncodeLikeTuple<Self::KArg> + TupleToEncodedIter>(key: KArg) -> Vec<u8> {
H::hash(&key.to_encoded_iter().next().expect("should have at least one element!"))
@@ -89,13 +90,15 @@ impl<H: StorageHasher, K: FullCodec> KeyGenerator for Key<H, K> {
}
}
impl<H: StorageHasher, K: FullCodec + MaxEncodedLen> KeyGeneratorMaxEncodedLen for Key<H, K> {
impl<H: StorageHasher, K: FullCodec + MaxEncodedLen + StaticTypeInfo> KeyGeneratorMaxEncodedLen
for Key<H, K>
{
fn key_max_encoded_len() -> usize {
H::max_len::<K>()
}
}
impl<H: StorageHasher, K: FullCodec> KeyGeneratorInner for Key<H, K> {
impl<H: StorageHasher, K: FullCodec + StaticTypeInfo> KeyGeneratorInner for Key<H, K> {
type Hasher = H;
fn final_hash(encoded: &[u8]) -> Vec<u8> {
@@ -111,7 +114,7 @@ impl KeyGenerator for Tuple {
for_tuples!( type HArg = ( #(Tuple::HashFn),* ); );
type HashFn = Box<dyn FnOnce(&[u8]) -> Vec<u8>>;
const HASHER_METADATA: &'static [frame_metadata::StorageHasher] =
const HASHER_METADATA: &'static [crate::metadata::StorageHasher] =
&[for_tuples!( #(Tuple::Hasher::METADATA),* )];
fn final_key<KArg: EncodeLikeTuple<Self::KArg> + TupleToEncodedIter>(key: KArg) -> Vec<u8> {
@@ -218,7 +221,9 @@ pub trait ReversibleKeyGenerator: KeyGenerator {
fn decode_final_key(key_material: &[u8]) -> Result<(Self::Key, &[u8]), codec::Error>;
}
impl<H: ReversibleStorageHasher, K: FullCodec> ReversibleKeyGenerator for Key<H, K> {
impl<H: ReversibleStorageHasher, K: FullCodec + StaticTypeInfo> ReversibleKeyGenerator
for Key<H, K>
{
type ReversibleHasher = H;
fn decode_final_key(key_material: &[u8]) -> Result<(Self::Key, &[u8]), codec::Error> {
@@ -19,14 +19,14 @@
//! methods directly.
use crate::{
metadata::{StorageEntryModifier, StorageEntryType},
storage::{
types::{OnEmptyGetter, OptionQuery, QueryKindTrait},
types::{OptionQuery, QueryKindTrait, StorageEntryMetadata},
StorageAppend, StorageDecodeLength, StoragePrefixedMap, StorageTryAppend,
},
traits::{Get, GetDefault, StorageInfo, StorageInstance},
};
use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen};
use frame_metadata::{DefaultByteGetter, StorageEntryModifier};
use sp_arithmetic::traits::SaturatedConversion;
use sp_std::prelude::*;
@@ -336,32 +336,31 @@ where
}
}
/// Part of storage metadata for a storage map.
///
/// NOTE: Generic hasher is supported.
pub trait StorageMapMetadata {
const MODIFIER: StorageEntryModifier;
const NAME: &'static str;
const DEFAULT: DefaultByteGetter;
const HASHER: frame_metadata::StorageHasher;
}
impl<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues> StorageMapMetadata
impl<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues> StorageEntryMetadata
for StorageMap<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>
where
Prefix: StorageInstance,
Hasher: crate::hash::StorageHasher,
Key: FullCodec,
Value: FullCodec,
Key: FullCodec + scale_info::StaticTypeInfo,
Value: FullCodec + scale_info::StaticTypeInfo,
QueryKind: QueryKindTrait<Value, OnEmpty>,
OnEmpty: Get<QueryKind::Query> + 'static,
MaxValues: Get<Option<u32>>,
{
const MODIFIER: StorageEntryModifier = QueryKind::METADATA;
const HASHER: frame_metadata::StorageHasher = Hasher::METADATA;
const NAME: &'static str = Prefix::STORAGE_PREFIX;
const DEFAULT: DefaultByteGetter =
DefaultByteGetter(&OnEmptyGetter::<QueryKind::Query, OnEmpty>(core::marker::PhantomData));
fn ty() -> StorageEntryType {
StorageEntryType::Map {
hashers: vec![Hasher::METADATA],
key: scale_info::meta_type::<Key>(),
value: scale_info::meta_type::<Value>(),
}
}
fn default() -> Vec<u8> {
OnEmpty::get().encode()
}
}
impl<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues> crate::traits::StorageInfoTrait
@@ -417,8 +416,12 @@ where
#[cfg(test)]
mod test {
use super::*;
use crate::{hash::*, storage::types::ValueQuery};
use frame_metadata::StorageEntryModifier;
use crate::{
hash::*,
metadata::{StorageEntryModifier, StorageEntryType, StorageHasher},
storage::types::ValueQuery,
};
use assert_matches::assert_matches;
use sp_io::{hashing::twox_128, TestExternalities};
struct Prefix;
@@ -572,14 +575,23 @@ mod test {
assert_eq!(A::MODIFIER, StorageEntryModifier::Optional);
assert_eq!(AValueQueryWithAnOnEmpty::MODIFIER, StorageEntryModifier::Default);
assert_eq!(A::HASHER, frame_metadata::StorageHasher::Blake2_128Concat);
assert_eq!(
AValueQueryWithAnOnEmpty::HASHER,
frame_metadata::StorageHasher::Blake2_128Concat
let assert_map_hashers = |ty, expected_hashers| {
if let StorageEntryType::Map { hashers, .. } = ty {
assert_eq!(hashers, expected_hashers)
} else {
assert_matches!(ty, StorageEntryType::Map { .. })
}
};
assert_map_hashers(A::ty(), vec![StorageHasher::Blake2_128Concat]);
assert_map_hashers(
AValueQueryWithAnOnEmpty::ty(),
vec![StorageHasher::Blake2_128Concat],
);
assert_eq!(A::NAME, "foo");
assert_eq!(AValueQueryWithAnOnEmpty::DEFAULT.0.default_byte(), 97u32.encode());
assert_eq!(A::DEFAULT.0.default_byte(), Option::<u32>::None.encode());
assert_eq!(AValueQueryWithAnOnEmpty::default(), 97u32.encode());
assert_eq!(A::default(), Option::<u32>::None.encode());
WithLen::remove_all(None);
assert_eq!(WithLen::decode_len(3), None);
@@ -18,8 +18,9 @@
//! Storage types to build abstraction on storage, they implements storage traits such as
//! StorageMap and others.
use crate::metadata::{StorageEntryModifier, StorageEntryType};
use codec::FullCodec;
use frame_metadata::{DefaultByte, StorageEntryModifier};
use sp_std::prelude::*;
mod double_map;
mod key;
@@ -27,14 +28,14 @@ mod map;
mod nmap;
mod value;
pub use double_map::{StorageDoubleMap, StorageDoubleMapMetadata};
pub use double_map::StorageDoubleMap;
pub use key::{
EncodeLikeTuple, HasKeyPrefix, HasReversibleKeyPrefix, Key, KeyGenerator,
KeyGeneratorMaxEncodedLen, ReversibleKeyGenerator, TupleToEncodedIter,
};
pub use map::{StorageMap, StorageMapMetadata};
pub use nmap::{StorageNMap, StorageNMapMetadata};
pub use value::{StorageValue, StorageValueMetadata};
pub use map::StorageMap;
pub use nmap::StorageNMap;
pub use value::StorageValue;
/// Trait implementing how the storage optional value is converted into the queried type.
///
@@ -102,14 +103,13 @@ where
}
}
/// A helper struct which implements DefaultByte using `Get<Value>` and encode it.
struct OnEmptyGetter<Value, OnEmpty>(core::marker::PhantomData<(Value, OnEmpty)>);
impl<Value: FullCodec, OnEmpty: crate::traits::Get<Value>> DefaultByte
for OnEmptyGetter<Value, OnEmpty>
{
fn default_byte(&self) -> sp_std::vec::Vec<u8> {
OnEmpty::get().encode()
}
/// Provide metadata for a storage entry.
///
/// Implemented by each of the storage entry kinds: value, map, doublemap and nmap.
pub trait StorageEntryMetadata {
const MODIFIER: StorageEntryModifier;
const NAME: &'static str;
fn ty() -> StorageEntryType;
fn default() -> Vec<u8>;
}
unsafe impl<Value, OnEmpty: crate::traits::Get<Value>> Send for OnEmptyGetter<Value, OnEmpty> {}
unsafe impl<Value, OnEmpty: crate::traits::Get<Value>> Sync for OnEmptyGetter<Value, OnEmpty> {}
@@ -19,17 +19,17 @@
//! StoragePrefixedDoubleMap traits and their methods directly.
use crate::{
metadata::{StorageEntryModifier, StorageEntryType},
storage::{
types::{
EncodeLikeTuple, HasKeyPrefix, HasReversibleKeyPrefix, OnEmptyGetter, OptionQuery,
QueryKindTrait, TupleToEncodedIter,
EncodeLikeTuple, HasKeyPrefix, HasReversibleKeyPrefix, OptionQuery, QueryKindTrait,
StorageEntryMetadata, TupleToEncodedIter,
},
KeyGenerator, PrefixIterator, StorageAppend, StorageDecodeLength, StoragePrefixedMap,
},
traits::{Get, GetDefault, StorageInfo, StorageInstance},
};
use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen};
use frame_metadata::{DefaultByteGetter, StorageEntryModifier};
use sp_runtime::SaturatedConversion;
use sp_std::prelude::*;
@@ -440,31 +440,30 @@ where
}
}
/// Part of storage metadata for a storage n map.
///
/// NOTE: Generic hashers is supported.
pub trait StorageNMapMetadata {
const MODIFIER: StorageEntryModifier;
const NAME: &'static str;
const DEFAULT: DefaultByteGetter;
const HASHERS: &'static [frame_metadata::StorageHasher];
}
impl<Prefix, Key, Value, QueryKind, OnEmpty, MaxValues> StorageNMapMetadata
impl<Prefix, Key, Value, QueryKind, OnEmpty, MaxValues> StorageEntryMetadata
for StorageNMap<Prefix, Key, Value, QueryKind, OnEmpty, MaxValues>
where
Prefix: StorageInstance,
Key: super::key::KeyGenerator,
Value: FullCodec,
Value: FullCodec + scale_info::StaticTypeInfo,
QueryKind: QueryKindTrait<Value, OnEmpty>,
OnEmpty: Get<QueryKind::Query> + 'static,
MaxValues: Get<Option<u32>>,
{
const MODIFIER: StorageEntryModifier = QueryKind::METADATA;
const NAME: &'static str = Prefix::STORAGE_PREFIX;
const DEFAULT: DefaultByteGetter =
DefaultByteGetter(&OnEmptyGetter::<QueryKind::Query, OnEmpty>(core::marker::PhantomData));
const HASHERS: &'static [frame_metadata::StorageHasher] = Key::HASHER_METADATA;
fn ty() -> StorageEntryType {
StorageEntryType::Map {
key: scale_info::meta_type::<Key::Key>(),
hashers: Key::HASHER_METADATA.iter().cloned().collect(),
value: scale_info::meta_type::<Value>(),
}
}
fn default() -> Vec<u8> {
OnEmpty::get().encode()
}
}
impl<Prefix, Key, Value, QueryKind, OnEmpty, MaxValues> crate::traits::StorageInfoTrait
@@ -518,9 +517,9 @@ mod test {
use super::*;
use crate::{
hash::*,
metadata::StorageEntryModifier,
storage::types::{Key, ValueQuery},
};
use frame_metadata::StorageEntryModifier;
use sp_io::{hashing::twox_128, TestExternalities};
struct Prefix;
@@ -688,8 +687,8 @@ mod test {
assert_eq!(A::MODIFIER, StorageEntryModifier::Optional);
assert_eq!(AValueQueryWithAnOnEmpty::MODIFIER, StorageEntryModifier::Default);
assert_eq!(A::NAME, "Foo");
assert_eq!(AValueQueryWithAnOnEmpty::DEFAULT.0.default_byte(), 98u32.encode());
assert_eq!(A::DEFAULT.0.default_byte(), Option::<u32>::None.encode());
assert_eq!(AValueQueryWithAnOnEmpty::default(), 98u32.encode());
assert_eq!(A::default(), Option::<u32>::None.encode());
WithLen::remove_all(None);
assert_eq!(WithLen::decode_len((3,)), None);
@@ -856,8 +855,8 @@ mod test {
assert_eq!(A::MODIFIER, StorageEntryModifier::Optional);
assert_eq!(AValueQueryWithAnOnEmpty::MODIFIER, StorageEntryModifier::Default);
assert_eq!(A::NAME, "Foo");
assert_eq!(AValueQueryWithAnOnEmpty::DEFAULT.0.default_byte(), 98u32.encode());
assert_eq!(A::DEFAULT.0.default_byte(), Option::<u32>::None.encode());
assert_eq!(AValueQueryWithAnOnEmpty::default(), 98u32.encode());
assert_eq!(A::default(), Option::<u32>::None.encode());
WithLen::remove_all(None);
assert_eq!(WithLen::decode_len((3, 30)), None);
@@ -1046,8 +1045,8 @@ mod test {
assert_eq!(A::MODIFIER, StorageEntryModifier::Optional);
assert_eq!(AValueQueryWithAnOnEmpty::MODIFIER, StorageEntryModifier::Default);
assert_eq!(A::NAME, "Foo");
assert_eq!(AValueQueryWithAnOnEmpty::DEFAULT.0.default_byte(), 98u32.encode());
assert_eq!(A::DEFAULT.0.default_byte(), Option::<u32>::None.encode());
assert_eq!(AValueQueryWithAnOnEmpty::default(), 98u32.encode());
assert_eq!(A::default(), Option::<u32>::None.encode());
WithLen::remove_all(None);
assert_eq!(WithLen::decode_len((3, 30, 300)), None);
@@ -18,15 +18,15 @@
//! Storage value type. Implements StorageValue trait and its method directly.
use crate::{
metadata::{StorageEntryModifier, StorageEntryType},
storage::{
generator::StorageValue as StorageValueT,
types::{OnEmptyGetter, OptionQuery, QueryKindTrait},
types::{OptionQuery, QueryKindTrait, StorageEntryMetadata},
StorageAppend, StorageDecodeLength, StorageTryAppend,
},
traits::{GetDefault, StorageInfo, StorageInstance},
};
use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen};
use frame_metadata::{DefaultByteGetter, StorageEntryModifier};
use sp_arithmetic::traits::SaturatedConversion;
use sp_std::prelude::*;
@@ -201,25 +201,24 @@ where
}
}
/// Part of storage metadata for storage value.
pub trait StorageValueMetadata {
const MODIFIER: StorageEntryModifier;
const NAME: &'static str;
const DEFAULT: DefaultByteGetter;
}
impl<Prefix, Value, QueryKind, OnEmpty> StorageValueMetadata
impl<Prefix, Value, QueryKind, OnEmpty> StorageEntryMetadata
for StorageValue<Prefix, Value, QueryKind, OnEmpty>
where
Prefix: StorageInstance,
Value: FullCodec,
Value: FullCodec + scale_info::StaticTypeInfo,
QueryKind: QueryKindTrait<Value, OnEmpty>,
OnEmpty: crate::traits::Get<QueryKind::Query> + 'static,
{
const MODIFIER: StorageEntryModifier = QueryKind::METADATA;
const NAME: &'static str = Prefix::STORAGE_PREFIX;
const DEFAULT: DefaultByteGetter =
DefaultByteGetter(&OnEmptyGetter::<QueryKind::Query, OnEmpty>(core::marker::PhantomData));
fn ty() -> StorageEntryType {
StorageEntryType::Plain(scale_info::meta_type::<Value>())
}
fn default() -> Vec<u8> {
OnEmpty::get().encode()
}
}
impl<Prefix, Value, QueryKind, OnEmpty> crate::traits::StorageInfoTrait
@@ -264,8 +263,7 @@ where
#[cfg(test)]
mod test {
use super::*;
use crate::storage::types::ValueQuery;
use frame_metadata::StorageEntryModifier;
use crate::{metadata::StorageEntryModifier, storage::types::ValueQuery};
use sp_io::{hashing::twox_128, TestExternalities};
struct Prefix;
@@ -347,8 +345,8 @@ mod test {
assert_eq!(A::MODIFIER, StorageEntryModifier::Optional);
assert_eq!(AValueQueryWithAnOnEmpty::MODIFIER, StorageEntryModifier::Default);
assert_eq!(A::NAME, "foo");
assert_eq!(A::DEFAULT.0.default_byte(), Option::<u32>::None.encode());
assert_eq!(AValueQueryWithAnOnEmpty::DEFAULT.0.default_byte(), 97u32.encode());
assert_eq!(A::default(), Option::<u32>::None.encode());
assert_eq!(AValueQueryWithAnOnEmpty::default(), 97u32.encode());
WithLen::kill();
assert_eq!(WithLen::decode_len(), None);
@@ -36,7 +36,8 @@ use sp_std::{convert::TryFrom, fmt, marker::PhantomData, prelude::*};
///
/// The length of the vec is not strictly bounded. Decoding a vec with more element that the bound
/// is accepted, and some method allow to bypass the restriction with warnings.
#[derive(Encode)]
#[derive(Encode, scale_info::TypeInfo)]
#[scale_info(skip_type_params(S))]
pub struct WeakBoundedVec<T, S>(Vec<T>, PhantomData<S>);
impl<T: Decode, S: Get<u32>> Decode for WeakBoundedVec<T, S> {
@@ -116,7 +116,7 @@ pub enum ExistenceRequirement {
}
/// Status of funds.
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, RuntimeDebug)]
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, RuntimeDebug, scale_info::TypeInfo)]
pub enum BalanceStatus {
/// Funds are free, as corresponding to `free` item in Balances.
Free,
@@ -165,8 +165,14 @@ pub trait AssetId: FullCodec + Copy + Eq + PartialEq + Debug {}
impl<T: FullCodec + Copy + Eq + PartialEq + Debug> AssetId for T {}
/// Simple amalgamation trait to collect together properties for a Balance under one roof.
pub trait Balance: AtLeast32BitUnsigned + FullCodec + Copy + Default + Debug {}
impl<T: AtLeast32BitUnsigned + FullCodec + Copy + Default + Debug> Balance for T {}
pub trait Balance:
AtLeast32BitUnsigned + FullCodec + Copy + Default + Debug + scale_info::TypeInfo
{
}
impl<T: AtLeast32BitUnsigned + FullCodec + Copy + Default + Debug + scale_info::TypeInfo> Balance
for T
{
}
/// Converts a balance value into an asset balance.
pub trait BalanceConversion<InBalance, AssetId, OutBalance> {
+16 -15
View File
@@ -129,6 +129,7 @@
use crate::dispatch::{DispatchError, DispatchErrorWithPostInfo, DispatchResultWithPostInfo};
use codec::{Decode, Encode};
use scale_info::TypeInfo;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use smallvec::{smallvec, SmallVec};
@@ -201,7 +202,7 @@ pub trait PaysFee<T> {
}
/// Explicit enum to denote if a transaction pays fee or not.
#[derive(Clone, Copy, Eq, PartialEq, RuntimeDebug, Encode, Decode)]
#[derive(Clone, Copy, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo)]
pub enum Pays {
/// Transactor will pay related fees.
Yes,
@@ -221,7 +222,7 @@ impl Default for Pays {
/// [DispatchClass::all] and [DispatchClass::non_mandatory] helper functions.
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, RuntimeDebug)]
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, RuntimeDebug, TypeInfo)]
pub enum DispatchClass {
/// A normal dispatch.
Normal,
@@ -311,7 +312,7 @@ pub mod priority {
}
/// A bundle of static information collected from the `#[weight = $x]` attributes.
#[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)]
#[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo)]
pub struct DispatchInfo {
/// Weight of this transaction.
pub weight: Weight,
@@ -338,7 +339,7 @@ impl GetDispatchInfo for () {
/// Weight information that is only available post dispatch.
/// NOTE: This can only be used to reduce the weight or fee, not increase it.
#[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)]
#[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo)]
pub struct PostDispatchInfo {
/// Actual weight consumed by a call or `None` which stands for the worst case static weight.
pub actual_weight: Option<Weight>,
@@ -627,7 +628,7 @@ impl<Call: Encode, Extra: Encode> GetDispatchInfo for sp_runtime::testing::TestX
}
/// The weight of database operations that the runtime can invoke.
#[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)]
#[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo)]
pub struct RuntimeDbWeight {
pub read: Weight,
pub write: Weight,
@@ -659,7 +660,7 @@ impl RuntimeDbWeight {
///
/// The `negative` value encodes whether the term is added or substracted from the
/// overall polynomial result.
#[derive(Clone, Encode, Decode)]
#[derive(Clone, Encode, Decode, TypeInfo)]
pub struct WeightToFeeCoefficient<Balance> {
/// The integral part of the coefficient.
pub coeff_integer: Balance,
@@ -737,7 +738,7 @@ where
}
/// A struct holding value for each `DispatchClass`.
#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)]
#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo)]
pub struct PerDispatchClass<T> {
/// Value for `Normal` extrinsics.
normal: T,
@@ -882,49 +883,49 @@ mod tests {
#[test]
fn weights_are_correct() {
// #[weight = 1000]
let info = Call::<TraitImpl>::f00().get_dispatch_info();
let info = Call::<TraitImpl>::f00 {}.get_dispatch_info();
assert_eq!(info.weight, 1000);
assert_eq!(info.class, DispatchClass::Normal);
assert_eq!(info.pays_fee, Pays::Yes);
// #[weight = (1000, DispatchClass::Mandatory)]
let info = Call::<TraitImpl>::f01().get_dispatch_info();
let info = Call::<TraitImpl>::f01 {}.get_dispatch_info();
assert_eq!(info.weight, 1000);
assert_eq!(info.class, DispatchClass::Mandatory);
assert_eq!(info.pays_fee, Pays::Yes);
// #[weight = (1000, Pays::No)]
let info = Call::<TraitImpl>::f02().get_dispatch_info();
let info = Call::<TraitImpl>::f02 {}.get_dispatch_info();
assert_eq!(info.weight, 1000);
assert_eq!(info.class, DispatchClass::Normal);
assert_eq!(info.pays_fee, Pays::No);
// #[weight = (1000, DispatchClass::Operational, Pays::No)]
let info = Call::<TraitImpl>::f03().get_dispatch_info();
let info = Call::<TraitImpl>::f03 {}.get_dispatch_info();
assert_eq!(info.weight, 1000);
assert_eq!(info.class, DispatchClass::Operational);
assert_eq!(info.pays_fee, Pays::No);
// #[weight = ((_a * 10 + _eb * 1) as Weight, DispatchClass::Normal, Pays::Yes)]
let info = Call::<TraitImpl>::f11(13, 20).get_dispatch_info();
let info = Call::<TraitImpl>::f11 { _a: 13, _eb: 20 }.get_dispatch_info();
assert_eq!(info.weight, 150); // 13*10 + 20
assert_eq!(info.class, DispatchClass::Normal);
assert_eq!(info.pays_fee, Pays::Yes);
// #[weight = (0, DispatchClass::Operational, Pays::Yes)]
let info = Call::<TraitImpl>::f12(10, 20).get_dispatch_info();
let info = Call::<TraitImpl>::f12 { _a: 10, _eb: 20 }.get_dispatch_info();
assert_eq!(info.weight, 0);
assert_eq!(info.class, DispatchClass::Operational);
assert_eq!(info.pays_fee, Pays::Yes);
// #[weight = T::DbWeight::get().reads(3) + T::DbWeight::get().writes(2) + 10_000]
let info = Call::<TraitImpl>::f20().get_dispatch_info();
let info = Call::<TraitImpl>::f20 {}.get_dispatch_info();
assert_eq!(info.weight, 12300); // 100*3 + 1000*2 + 10_1000
assert_eq!(info.class, DispatchClass::Normal);
assert_eq!(info.pays_fee, Pays::Yes);
// #[weight = T::DbWeight::get().reads_writes(6, 5) + 40_000]
let info = Call::<TraitImpl>::f21().get_dispatch_info();
let info = Call::<TraitImpl>::f21 {}.get_dispatch_info();
assert_eq!(info.weight, 45600); // 100*6 + 1000*5 + 40_1000
assert_eq!(info.class, DispatchClass::Normal);
assert_eq!(info.pays_fee, Pays::Yes);