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
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
# Needed for various traits. In our case, `OnFinalize`.
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
@@ -33,6 +34,7 @@ pallet-balances = { version = "4.0.0-dev", path = "../balances" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-std/std",
"sp-runtime/std",
"frame-support/std",
+17 -17
View File
@@ -330,13 +330,13 @@ benchmarks_instance_pallet! {
create_default_asset::<T, I>(true);
let origin = T::ForceOrigin::successful_origin();
let call = Call::<T, I>::force_set_metadata(
Default::default(),
name.clone(),
symbol.clone(),
let call = Call::<T, I>::force_set_metadata {
id: Default::default(),
name: name.clone(),
symbol: symbol.clone(),
decimals,
false,
);
is_frozen: false,
};
}: { call.dispatch_bypass_filter(origin)? }
verify {
let id = Default::default();
@@ -351,7 +351,7 @@ benchmarks_instance_pallet! {
Assets::<T, I>::set_metadata(origin, Default::default(), dummy.clone(), dummy, 12)?;
let origin = T::ForceOrigin::successful_origin();
let call = Call::<T, I>::force_clear_metadata(Default::default());
let call = Call::<T, I>::force_clear_metadata { id: Default::default() };
}: { call.dispatch_bypass_filter(origin)? }
verify {
assert_last_event::<T, I>(Event::MetadataCleared(Default::default()).into());
@@ -361,16 +361,16 @@ benchmarks_instance_pallet! {
let (caller, caller_lookup) = create_default_asset::<T, I>(true);
let origin = T::ForceOrigin::successful_origin();
let call = Call::<T, I>::force_asset_status(
Default::default(),
caller_lookup.clone(),
caller_lookup.clone(),
caller_lookup.clone(),
caller_lookup.clone(),
100u32.into(),
true,
false,
);
let call = Call::<T, I>::force_asset_status {
id: Default::default(),
owner: caller_lookup.clone(),
issuer: caller_lookup.clone(),
admin: caller_lookup.clone(),
freezer: caller_lookup.clone(),
min_balance: 100u32.into(),
is_sufficient: true,
is_frozen: false,
};
}: { call.dispatch_bypass_filter(origin)? }
verify {
assert_last_event::<T, I>(Event::AssetStatusChanged(Default::default()).into());
-1
View File
@@ -277,7 +277,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(T::AccountId = "AccountId", T::Balance = "Balance", T::AssetId = "AssetId")]
pub enum Event<T: Config<I>, I: 'static = ()> {
/// Some asset class was created. \[asset_id, creator, owner\]
Created(T::AssetId, T::AccountId, T::AccountId),
+6 -5
View File
@@ -19,6 +19,7 @@
use super::*;
use frame_support::pallet_prelude::*;
use scale_info::TypeInfo;
use frame_support::traits::{fungible, tokens::BalanceConversion};
use sp_runtime::{traits::Convert, FixedPointNumber, FixedPointOperand, FixedU128};
@@ -26,7 +27,7 @@ use sp_runtime::{traits::Convert, FixedPointNumber, FixedPointOperand, FixedU128
pub(super) type DepositBalanceOf<T, I = ()> =
<<T as Config<I>>::Currency as Currency<<T as SystemConfig>::AccountId>>::Balance;
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen)]
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub struct AssetDetails<Balance, AccountId, DepositBalance> {
/// Can change `owner`, `issuer`, `freezer` and `admin` accounts.
pub(super) owner: AccountId,
@@ -66,7 +67,7 @@ impl<Balance, AccountId, DepositBalance> AssetDetails<Balance, AccountId, Deposi
}
/// Data concerning an approval.
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, Default, MaxEncodedLen)]
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, Default, MaxEncodedLen, TypeInfo)]
pub struct Approval<Balance, DepositBalance> {
/// The amount of funds approved for the balance transfer from the owner to some delegated
/// target.
@@ -75,7 +76,7 @@ pub struct Approval<Balance, DepositBalance> {
pub(super) deposit: DepositBalance,
}
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, Default, MaxEncodedLen)]
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, Default, MaxEncodedLen, TypeInfo)]
pub struct AssetBalance<Balance, Extra> {
/// The balance.
pub(super) balance: Balance,
@@ -87,7 +88,7 @@ pub struct AssetBalance<Balance, Extra> {
pub(super) extra: Extra,
}
#[derive(Clone, Encode, Decode, Eq, PartialEq, Default, RuntimeDebug, MaxEncodedLen)]
#[derive(Clone, Encode, Decode, Eq, PartialEq, Default, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub struct AssetMetadata<DepositBalance, BoundedString> {
/// The balance deposited for this metadata.
///
@@ -104,7 +105,7 @@ pub struct AssetMetadata<DepositBalance, BoundedString> {
}
/// Witness data for the destroy transactions.
#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen)]
#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub struct DestroyWitness {
/// The number of accounts holding the asset.
#[codec(compact)]
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
@@ -28,6 +29,7 @@ pallet-balances = { version = "4.0.0-dev", path = "../balances" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"frame-support/std",
"frame-system/std",
"sp-runtime/std",
+5 -3
View File
@@ -49,6 +49,7 @@ use frame_support::{
weights::Weight,
RuntimeDebugNoBound,
};
use scale_info::TypeInfo;
use sp_io::hashing::blake2_256;
use sp_runtime::RuntimeDebug;
use sp_std::{
@@ -58,7 +59,8 @@ use sp_std::{
};
/// Pending atomic swap operation.
#[derive(Clone, Eq, PartialEq, RuntimeDebugNoBound, Encode, Decode)]
#[derive(Clone, Eq, PartialEq, RuntimeDebugNoBound, Encode, Decode, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct PendingSwap<T: Config> {
/// Source of the swap.
pub source: T::AccountId,
@@ -91,7 +93,8 @@ pub trait SwapAction<AccountId, T: Config> {
}
/// A swap action that only allows transferring balances.
#[derive(Clone, RuntimeDebug, Eq, PartialEq, Encode, Decode)]
#[derive(Clone, RuntimeDebug, Eq, PartialEq, Encode, Decode, TypeInfo)]
#[scale_info(skip_type_params(C))]
pub struct BalanceSwapAction<AccountId, C: ReservableCurrency<AccountId>> {
value: <C as Currency<AccountId>>::Balance,
_marker: PhantomData<C>,
@@ -213,7 +216,6 @@ pub mod pallet {
/// Event of atomic swap pallet.
#[pallet::event]
#[pallet::metadata(T::AccountId = "AccountId", PendingSwap<T> = "PendingSwap")]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Swap created. \[account, proof, swap\]
+2
View File
@@ -15,6 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
sp-application-crypto = { version = "4.0.0-dev", default-features = false, path = "../../primitives/application-crypto" }
codec = { package = "parity-scale-codec", version = "2.2.0", default-features = false, features = ["derive", "max-encoded-len"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
@@ -31,6 +32,7 @@ default = ["std"]
std = [
"sp-application-crypto/std",
"codec/std",
"scale-info/std",
"sp-std/std",
"sp-runtime/std",
"frame-support/std",
@@ -18,6 +18,7 @@ sp-application-crypto = { version = "4.0.0-dev", default-features = false, path
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [
"derive",
] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
pallet-session = { version = "4.0.0-dev", features = [
"historical",
@@ -36,6 +37,7 @@ std = [
"sp-application-crypto/std",
"sp-authority-discovery/std",
"codec/std",
"scale-info/std",
"sp-std/std",
"pallet-session/std",
"sp-runtime/std",
+2
View File
@@ -16,6 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [
"derive",
] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-authorship = { version = "4.0.0-dev", default-features = false, path = "../../primitives/authorship" }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
@@ -31,6 +32,7 @@ sp-io = { version = "4.0.0-dev", path = "../../primitives/io" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-runtime/std",
"sp-std/std",
"frame-support/std",
+8 -8
View File
@@ -115,7 +115,7 @@ where
}
}
#[derive(Encode, Decode, sp_runtime::RuntimeDebug)]
#[derive(Encode, Decode, sp_runtime::RuntimeDebug, scale_info::TypeInfo)]
#[cfg_attr(any(feature = "std", test), derive(PartialEq))]
enum UncleEntryItem<BlockNumber, Hash, Author> {
InclusionHeight(BlockNumber),
@@ -238,7 +238,7 @@ pub mod pallet {
fn create_inherent(data: &InherentData) -> Option<Self::Call> {
let uncles = data.uncles().unwrap_or_default();
let mut set_uncles = Vec::new();
let mut new_uncles = Vec::new();
if !uncles.is_empty() {
let prev_uncles = <Uncles<T>>::get();
@@ -257,10 +257,10 @@ pub mod pallet {
match Self::verify_uncle(&uncle, &existing_hashes, &mut acc) {
Ok(_) => {
let hash = uncle.hash();
set_uncles.push(uncle);
new_uncles.push(uncle);
existing_hashes.push(hash);
if set_uncles.len() == MAX_UNCLES {
if new_uncles.len() == MAX_UNCLES {
break
}
},
@@ -271,10 +271,10 @@ pub mod pallet {
}
}
if set_uncles.is_empty() {
if new_uncles.is_empty() {
None
} else {
Some(Call::set_uncles(set_uncles))
Some(Call::set_uncles { new_uncles })
}
}
@@ -283,14 +283,14 @@ pub mod pallet {
_data: &InherentData,
) -> result::Result<(), Self::Error> {
match call {
Call::set_uncles(ref uncles) if uncles.len() > MAX_UNCLES =>
Call::set_uncles { ref new_uncles } if new_uncles.len() > MAX_UNCLES =>
Err(InherentError::Uncles(Error::<T>::TooManyUncles.as_str().into())),
_ => Ok(()),
}
}
fn is_inherent(call: &Self::Call) -> bool {
matches!(call, Call::set_uncles(_))
matches!(call, Call::set_uncles { .. })
}
}
}
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }
@@ -42,6 +43,7 @@ frame-election-provider-support = { version = "4.0.0-dev", path = "../election-p
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"frame-benchmarking/std",
"frame-support/std",
"frame-system/std",
+6 -4
View File
@@ -155,8 +155,10 @@ where
) -> DispatchResult {
use frame_system::offchain::SubmitTransaction;
let call =
Call::report_equivocation_unsigned(Box::new(equivocation_proof), key_owner_proof);
let call = Call::report_equivocation_unsigned {
equivocation_proof: Box::new(equivocation_proof),
key_owner_proof,
};
match SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into()) {
Ok(()) => log::info!(
@@ -184,7 +186,7 @@ where
/// unsigned equivocation reports.
impl<T: Config> Pallet<T> {
pub fn validate_unsigned(source: TransactionSource, call: &Call<T>) -> TransactionValidity {
if let Call::report_equivocation_unsigned(equivocation_proof, key_owner_proof) = call {
if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call {
// discard equivocation report not coming from the local node
match source {
TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ },
@@ -219,7 +221,7 @@ impl<T: Config> Pallet<T> {
}
pub fn pre_dispatch(call: &Call<T>) -> Result<(), TransactionValidityError> {
if let Call::report_equivocation_unsigned(equivocation_proof, key_owner_proof) = call {
if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call {
is_known_offence::<T>(equivocation_proof, key_owner_proof)
} else {
Err(InvalidTransaction::Call.into())
+8 -8
View File
@@ -726,10 +726,10 @@ fn report_equivocation_validate_unsigned_prevents_duplicates() {
let key = (sp_consensus_babe::KEY_TYPE, &offending_authority_pair.public());
let key_owner_proof = Historical::prove(key).unwrap();
let inner = Call::report_equivocation_unsigned(
Box::new(equivocation_proof.clone()),
key_owner_proof.clone(),
);
let inner = Call::report_equivocation_unsigned {
equivocation_proof: Box::new(equivocation_proof.clone()),
key_owner_proof: key_owner_proof.clone(),
};
// only local/inblock reports are allowed
assert_eq!(
@@ -822,10 +822,10 @@ fn valid_equivocation_reports_dont_pay_fees() {
.unwrap();
// check the dispatch info for the call.
let info = Call::<Test>::report_equivocation_unsigned(
Box::new(equivocation_proof.clone()),
key_owner_proof.clone(),
)
let info = Call::<Test>::report_equivocation_unsigned {
equivocation_proof: Box::new(equivocation_proof.clone()),
key_owner_proof: key_owner_proof.clone(),
}
.get_dispatch_info();
// it should have non-zero weight and the fee has to be paid.
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.2.0", default-features = false, features = ["derive", "max-encoded-len"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true }
@@ -30,6 +31,7 @@ pallet-transaction-payment = { version = "4.0.0-dev", path = "../transaction-pay
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-std/std",
"sp-runtime/std",
"frame-benchmarking/std",
+8 -7
View File
@@ -177,6 +177,7 @@ use frame_support::{
WeakBoundedVec,
};
use frame_system as system;
use scale_info::TypeInfo;
use sp_runtime::{
traits::{
AtLeast32BitUnsigned, Bounded, CheckedAdd, CheckedSub, MaybeSerializeDeserialize,
@@ -206,7 +207,8 @@ pub mod pallet {
+ Copy
+ MaybeSerializeDeserialize
+ Debug
+ MaxEncodedLen;
+ MaxEncodedLen
+ TypeInfo;
/// Handler for the unbalanced reduction when removing a dust account.
type DustRemoval: OnUnbalanced<NegativeImbalance<Self, I>>;
@@ -435,7 +437,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(T::AccountId = "AccountId", T::Balance = "Balance")]
pub enum Event<T: Config<I>, I: 'static = ()> {
/// An account was created with some free balance. \[account, free_balance\]
Endowed(T::AccountId, T::Balance),
@@ -599,7 +600,7 @@ impl<T: Config<I>, I: 'static> GenesisConfig<T, I> {
}
/// Simplified reasons for withdrawing balance.
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, MaxEncodedLen)]
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub enum Reasons {
/// Paying system transaction fees.
Fee = 0,
@@ -633,7 +634,7 @@ impl BitOr for Reasons {
/// A single lock on a balance. There can be many of these on an account and they "overlap", so the
/// same balance is frozen by multiple locks.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, MaxEncodedLen)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub struct BalanceLock<Balance> {
/// An identifier for this lock. Only one lock may be in existence for each identifier.
pub id: LockIdentifier,
@@ -644,7 +645,7 @@ pub struct BalanceLock<Balance> {
}
/// Store named reserved balance.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, MaxEncodedLen)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub struct ReserveData<ReserveIdentifier, Balance> {
/// The identifier for the named reserve.
pub id: ReserveIdentifier,
@@ -653,7 +654,7 @@ pub struct ReserveData<ReserveIdentifier, Balance> {
}
/// All balance information for an account.
#[derive(Encode, Decode, Clone, PartialEq, Eq, Default, RuntimeDebug, MaxEncodedLen)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, Default, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub struct AccountData<Balance> {
/// Non-reserved part of the balance. There may still be restrictions on this, but it is the
/// total pool what may in principle be transferred, reserved and used for tipping.
@@ -700,7 +701,7 @@ impl<Balance: Saturating + Copy + Ord> AccountData<Balance> {
// A value placed in storage that represents the current version of the Balances storage.
// This value is used by the `on_runtime_upgrade` logic to determine whether we run
// storage migration logic. This should match directly with the semantic versions of the Rust crate.
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, MaxEncodedLen)]
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, MaxEncodedLen, TypeInfo)]
enum Releases {
V1_0_0,
V2_0_0,
+1 -1
View File
@@ -39,7 +39,7 @@ macro_rules! decl_tests {
const ID_2: LockIdentifier = *b"2 ";
pub const CALL: &<$test as frame_system::Config>::Call =
&Call::Balances(pallet_balances::Call::transfer(0, 0));
&Call::Balances(pallet_balances::Call::transfer { dest: 0, value: 0 });
/// create a transaction info struct from weight. Handy to avoid building the whole struct.
pub fn info_from_weight(w: Weight) -> DispatchInfo {
+2
View File
@@ -16,6 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"]
linregress = { version = "0.4.3", optional = true }
paste = "1.0"
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-api = { version = "4.0.0-dev", path = "../../primitives/api", default-features = false }
sp-runtime-interface = { version = "4.0.0-dev", path = "../../primitives/runtime-interface", default-features = false }
sp-runtime = { version = "4.0.0-dev", path = "../../primitives/runtime", default-features = false }
@@ -33,6 +34,7 @@ hex-literal = "0.3.1"
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-runtime-interface/std",
"sp-runtime/std",
"sp-api/std",
+30 -22
View File
@@ -331,30 +331,38 @@ macro_rules! benchmarks_iter {
verify $postcode:block
$( $rest:tt )*
) => {
$crate::benchmarks_iter! {
{ $( $instance: $instance_bound )? }
{ $( $where_clause )* }
( $( $names )* )
( $( $names_extra )* )
( $( $names_skip_meta )* )
$name {
$( $code )*
let __benchmarked_call_encoded = $crate::frame_support::codec::Encode::encode(
&<Call<T $(, $instance )?>>::$dispatch($( $arg ),*)
);
}: {
let call_decoded = <
Call<T $(, $instance )?>
as $crate::frame_support::codec::Decode
>::decode(&mut &__benchmarked_call_encoded[..])
.expect("call is encoded above, encoding must be correct");
$crate::paste::paste! {
$crate::benchmarks_iter! {
{ $( $instance: $instance_bound )? }
{ $( $where_clause )* }
( $( $names )* )
( $( $names_extra )* )
( $( $names_skip_meta )* )
$name {
$( $code )*
let __call = Call::<
T
$( , $instance )?
>:: [< new_call_variant_ $dispatch >] (
$($arg),*
);
let __benchmarked_call_encoded = $crate::frame_support::codec::Encode::encode(
&__call
);
}: {
let call_decoded = <
Call<T $(, $instance )?>
as $crate::frame_support::codec::Decode
>::decode(&mut &__benchmarked_call_encoded[..])
.expect("call is encoded above, encoding must be correct");
<
Call<T $(, $instance)? > as $crate::frame_support::traits::UnfilteredDispatchable
>::dispatch_bypass_filter(call_decoded, $origin.into())?;
<
Call<T $(, $instance)? > as $crate::frame_support::traits::UnfilteredDispatchable
>::dispatch_bypass_filter(call_decoded, $origin.into())?;
}
verify $postcode
$( $rest )*
}
verify $postcode
$( $rest )*
}
};
// iteration arm:
+2
View File
@@ -16,6 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [
"derive",
] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
@@ -33,6 +34,7 @@ pallet-balances = { version = "4.0.0-dev", path = "../balances" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-std/std",
"sp-runtime/std",
"frame-support/std",
+3 -2
View File
@@ -97,6 +97,7 @@ use frame_support::weights::Weight;
use codec::{Decode, Encode};
use frame_system::{self as system, ensure_signed};
use scale_info::TypeInfo;
pub use weights::WeightInfo;
type BalanceOf<T> = pallet_treasury::BalanceOf<T>;
@@ -136,7 +137,7 @@ pub trait Config: frame_system::Config + pallet_treasury::Config {
pub type BountyIndex = u32;
/// A bounty proposal.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct Bounty<AccountId, Balance, BlockNumber> {
/// The account proposing it.
proposer: AccountId,
@@ -153,7 +154,7 @@ pub struct Bounty<AccountId, Balance, BlockNumber> {
}
/// The status of a bounty proposal.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum BountyStatus<AccountId, BlockNumber> {
/// The bounty is proposed and waiting for approval.
Proposed,
+2
View File
@@ -15,6 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
log = { version = "0.4.14", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-core = { version = "4.0.0-dev", default-features = false, path = "../../primitives/core" }
sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" }
@@ -30,6 +31,7 @@ default = ["std"]
std = [
"codec/std",
"log/std",
"scale-info/std",
"sp-core/std",
"sp-io/std",
"sp-runtime/std",
+17 -11
View File
@@ -65,7 +65,9 @@ benchmarks_instance_pallet! {
let length = 100;
for i in 0 .. p {
// Proposals should be different so that different proposal hashes are generated
let proposal: T::Proposal = SystemCall::<T>::remark(vec![i as u8; length]).into();
let proposal: T::Proposal = SystemCall::<T>::remark {
remark: vec![i as u8; length]
}.into();
Collective::<T, I>::propose(
SystemOrigin::Signed(last_old_member.clone()).into(),
threshold,
@@ -121,7 +123,7 @@ benchmarks_instance_pallet! {
Collective::<T, I>::set_members(SystemOrigin::Root.into(), members, None, T::MaxMembers::get())?;
let proposal: T::Proposal = SystemCall::<T>::remark(vec![1; b as usize]).into();
let proposal: T::Proposal = SystemCall::<T>::remark { remark: vec![1; b as usize] }.into();
}: _(SystemOrigin::Signed(caller), Box::new(proposal.clone()), bytes_in_storage)
verify {
@@ -151,7 +153,7 @@ benchmarks_instance_pallet! {
Collective::<T, I>::set_members(SystemOrigin::Root.into(), members, None, T::MaxMembers::get())?;
let proposal: T::Proposal = SystemCall::<T>::remark(vec![1; b as usize]).into();
let proposal: T::Proposal = SystemCall::<T>::remark { remark: vec![1; b as usize] }.into();
let threshold = 1;
}: propose(SystemOrigin::Signed(caller), threshold, Box::new(proposal.clone()), bytes_in_storage)
@@ -185,7 +187,7 @@ benchmarks_instance_pallet! {
// Add previous proposals.
for i in 0 .. p - 1 {
// Proposals should be different so that different proposal hashes are generated
let proposal: T::Proposal = SystemCall::<T>::remark(vec![i as u8; b as usize]).into();
let proposal: T::Proposal = SystemCall::<T>::remark { remark: vec![i as u8; b as usize] }.into();
Collective::<T, I>::propose(
SystemOrigin::Signed(caller.clone()).into(),
threshold,
@@ -196,7 +198,7 @@ benchmarks_instance_pallet! {
assert_eq!(Collective::<T, I>::proposals().len(), (p - 1) as usize);
let proposal: T::Proposal = SystemCall::<T>::remark(vec![p as u8; b as usize]).into();
let proposal: T::Proposal = SystemCall::<T>::remark { remark: vec![p as u8; b as usize] }.into();
}: propose(SystemOrigin::Signed(caller.clone()), threshold, Box::new(proposal.clone()), bytes_in_storage)
verify {
@@ -233,7 +235,7 @@ benchmarks_instance_pallet! {
let mut last_hash = T::Hash::default();
for i in 0 .. p {
// Proposals should be different so that different proposal hashes are generated
let proposal: T::Proposal = SystemCall::<T>::remark(vec![i as u8; b as usize]).into();
let proposal: T::Proposal = SystemCall::<T>::remark { remark: vec![i as u8; b as usize] }.into();
Collective::<T, I>::propose(
SystemOrigin::Signed(proposer.clone()).into(),
threshold,
@@ -308,7 +310,9 @@ benchmarks_instance_pallet! {
let mut last_hash = T::Hash::default();
for i in 0 .. p {
// Proposals should be different so that different proposal hashes are generated
let proposal: T::Proposal = SystemCall::<T>::remark(vec![i as u8; bytes as usize]).into();
let proposal: T::Proposal = SystemCall::<T>::remark {
remark: vec![i as u8; bytes as usize]
}.into();
Collective::<T, I>::propose(
SystemOrigin::Signed(proposer.clone()).into(),
threshold,
@@ -385,7 +389,7 @@ benchmarks_instance_pallet! {
let mut last_hash = T::Hash::default();
for i in 0 .. p {
// Proposals should be different so that different proposal hashes are generated
let proposal: T::Proposal = SystemCall::<T>::remark(vec![i as u8; b as usize]).into();
let proposal: T::Proposal = SystemCall::<T>::remark { remark: vec![i as u8; b as usize] }.into();
Collective::<T, I>::propose(
SystemOrigin::Signed(caller.clone()).into(),
threshold,
@@ -471,7 +475,9 @@ benchmarks_instance_pallet! {
let mut last_hash = T::Hash::default();
for i in 0 .. p {
// Proposals should be different so that different proposal hashes are generated
let proposal: T::Proposal = SystemCall::<T>::remark(vec![i as u8; bytes as usize]).into();
let proposal: T::Proposal = SystemCall::<T>::remark {
remark: vec![i as u8; bytes as usize]
}.into();
Collective::<T, I>::propose(
SystemOrigin::Signed(caller.clone()).into(),
threshold,
@@ -543,7 +549,7 @@ benchmarks_instance_pallet! {
let mut last_hash = T::Hash::default();
for i in 0 .. p {
// Proposals should be different so that different proposal hashes are generated
let proposal: T::Proposal = SystemCall::<T>::remark(vec![i as u8; b as usize]).into();
let proposal: T::Proposal = SystemCall::<T>::remark { remark: vec![i as u8; b as usize] }.into();
Collective::<T, I>::propose(
SystemOrigin::Signed(caller.clone()).into(),
threshold,
@@ -614,7 +620,7 @@ benchmarks_instance_pallet! {
let mut last_hash = T::Hash::default();
for i in 0 .. p {
// Proposals should be different so that different proposal hashes are generated
let proposal: T::Proposal = SystemCall::<T>::remark(vec![i as u8; b as usize]).into();
let proposal: T::Proposal = SystemCall::<T>::remark { remark: vec![i as u8; b as usize] }.into();
Collective::<T, I>::propose(
SystemOrigin::Signed(caller.clone()).into(),
threshold,
+4 -3
View File
@@ -42,6 +42,7 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![recursion_limit = "128"]
use scale_info::TypeInfo;
use sp_core::u32_trait::Value as U32;
use sp_io::storage;
use sp_runtime::{traits::Hash, RuntimeDebug};
@@ -124,7 +125,8 @@ impl DefaultVote for MoreThanMajorityThenPrimeDefaultVote {
}
/// Origin for the collective module.
#[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode)]
#[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode, TypeInfo)]
#[scale_info(skip_type_params(I))]
pub enum RawOrigin<AccountId, I> {
/// It has been condoned by a given number of members of the collective from a given total.
Members(MemberCount, MemberCount),
@@ -144,7 +146,7 @@ impl<AccountId, I> GetBacking for RawOrigin<AccountId, I> {
}
/// Info for keeping track of a motion being voted on.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct Votes<AccountId, BlockNumber> {
/// The proposal's unique index.
index: ProposalIndex,
@@ -274,7 +276,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(T::AccountId = "AccountId", T::Hash = "Hash")]
pub enum Event<T: Config<I>, I: 'static = ()> {
/// A motion (given hash) has been proposed (by given account) with a threshold (given
/// `MemberCount`).
+17 -8
View File
@@ -172,7 +172,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
}
fn make_proposal(value: u64) -> Call {
Call::System(frame_system::Call::remark(value.encode()))
Call::System(frame_system::Call::remark { remark: value.encode() })
}
fn record(event: Event) -> EventRecord<Event, H256> {
@@ -229,8 +229,11 @@ fn close_works() {
#[test]
fn proposal_weight_limit_works_on_approve() {
new_test_ext().execute_with(|| {
let proposal =
Call::Collective(crate::Call::set_members(vec![1, 2, 3], None, MaxMembers::get()));
let proposal = Call::Collective(crate::Call::set_members {
new_members: vec![1, 2, 3],
prime: None,
old_count: MaxMembers::get(),
});
let proposal_len: u32 = proposal.using_encoded(|p| p.len() as u32);
let proposal_weight = proposal.get_dispatch_info().weight;
let hash = BlakeTwo256::hash_of(&proposal);
@@ -256,8 +259,11 @@ fn proposal_weight_limit_works_on_approve() {
#[test]
fn proposal_weight_limit_ignored_on_disapprove() {
new_test_ext().execute_with(|| {
let proposal =
Call::Collective(crate::Call::set_members(vec![1, 2, 3], None, MaxMembers::get()));
let proposal = Call::Collective(crate::Call::set_members {
new_members: vec![1, 2, 3],
prime: None,
old_count: MaxMembers::get(),
});
let proposal_len: u32 = proposal.using_encoded(|p| p.len() as u32);
let proposal_weight = proposal.get_dispatch_info().weight;
let hash = BlakeTwo256::hash_of(&proposal);
@@ -561,8 +567,11 @@ fn limit_active_proposals() {
#[test]
fn correct_validate_and_get_proposal() {
new_test_ext().execute_with(|| {
let proposal =
Call::Collective(crate::Call::set_members(vec![1, 2, 3], None, MaxMembers::get()));
let proposal = Call::Collective(crate::Call::set_members {
new_members: vec![1, 2, 3],
prime: None,
old_count: MaxMembers::get(),
});
let length = proposal.encode().len() as u32;
assert_ok!(Collective::propose(Origin::signed(1), 3, Box::new(proposal.clone()), length));
@@ -782,7 +791,7 @@ fn motions_reproposing_disapproved_works() {
#[test]
fn motions_approval_with_enough_votes_and_lower_voting_threshold_works() {
new_test_ext().execute_with(|| {
let proposal = Call::Democracy(mock_democracy::Call::external_propose_majority());
let proposal = Call::Democracy(mock_democracy::Call::external_propose_majority {});
let proposal_len: u32 = proposal.using_encoded(|p| p.len() as u32);
let proposal_weight = proposal.get_dispatch_info().weight;
let hash: H256 = proposal.blake2_256().into();
+2
View File
@@ -18,6 +18,7 @@ codec = { package = "parity-scale-codec", version = "2.2.0", default-features =
"derive",
"max-encoded-len",
] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
log = { version = "0.4", default-features = false }
pwasm-utils = { version = "0.18.2", default-features = false }
serde = { version = "1", optional = true, features = ["derive"] }
@@ -60,6 +61,7 @@ default = ["std"]
std = [
"serde",
"codec/std",
"scale-info/std",
"sp-core/std",
"sp-runtime/std",
"sp-io/std",
@@ -15,6 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
bitflags = "1.0"
codec = { package = "parity-scale-codec", version = "2", default-features = false, features = ["derive"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
serde = { version = "1", features = ["derive"], optional = true }
# Substrate Dependencies (This crate should not rely on frame)
@@ -26,6 +27,7 @@ sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../..
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-core/std",
"sp-runtime/std",
"sp-std/std",
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2", default-features = false, features = ["derive"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
# Substrate Dependencies
pallet-contracts-primitives = { version = "4.0.0-dev", default-features = false, path = "../../common" }
@@ -26,6 +27,7 @@ default = ["std"]
std = [
"sp-api/std",
"codec/std",
"scale-info/std",
"sp-std/std",
"sp-runtime/std",
"pallet-contracts-primitives/std",
+10 -9
View File
@@ -2060,7 +2060,9 @@ mod tests {
#[test]
fn call_runtime_works() {
let code_hash = MockLoader::insert(Call, |ctx, _| {
let call = Call::System(frame_system::Call::remark_with_event(b"Hello World".to_vec()));
let call = Call::System(frame_system::Call::remark_with_event {
remark: b"Hello World".to_vec(),
});
ctx.ext.call_runtime(call).unwrap();
exec_success()
});
@@ -2094,20 +2096,19 @@ mod tests {
use pallet_utility::Call as UtilCall;
// remark should still be allowed
let allowed_call = Call::System(SysCall::remark_with_event(b"Hello".to_vec()));
let allowed_call =
Call::System(SysCall::remark_with_event { remark: b"Hello".to_vec() });
// transfers are disallowed by the `TestFiler` (see below)
let forbidden_call = Call::Balances(BalanceCall::transfer(CHARLIE, 22));
let forbidden_call = Call::Balances(BalanceCall::transfer { dest: CHARLIE, value: 22 });
// simple cases: direct call
assert_err!(ctx.ext.call_runtime(forbidden_call.clone()), BadOrigin);
// as part of a patch: return is OK (but it interrupted the batch)
assert_ok!(ctx.ext.call_runtime(Call::Utility(UtilCall::batch(vec![
allowed_call.clone(),
forbidden_call,
allowed_call
]))),);
assert_ok!(ctx.ext.call_runtime(Call::Utility(UtilCall::batch {
calls: vec![allowed_call.clone(), forbidden_call, allowed_call]
})),);
// the transfer wasn't performed
assert_eq!(get_balance(&CHARLIE), 0);
@@ -2116,7 +2117,7 @@ mod tests {
});
TestFilter::set_filter(|call| match call {
Call::Balances(pallet_balances::Call::transfer(_, _)) => false,
Call::Balances(pallet_balances::Call::transfer { .. }) => false,
_ => true,
});
-1
View File
@@ -386,7 +386,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(T::AccountId = "AccountId", T::Hash = "Hash", BalanceOf<T> = "Balance")]
pub enum Event<T: Config> {
/// Contract deployed by address at the specified address. \[deployer, contract\]
Instantiated(T::AccountId, T::AccountId),
+8 -4
View File
@@ -24,6 +24,7 @@ use codec::{Decode, Encode};
use frame_support::{weights::Weight, DefaultNoBound};
use pallet_contracts_proc_macro::{ScheduleDebug, WeightDebug};
use pwasm_utils::{parity_wasm::elements, rules};
use scale_info::TypeInfo;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_runtime::RuntimeDebug;
@@ -72,7 +73,8 @@ pub const INSTR_BENCHMARK_BATCH_SIZE: u32 = 100;
/// changes are made to its values.
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(bound(serialize = "", deserialize = "")))]
#[derive(Clone, Encode, Decode, PartialEq, Eq, ScheduleDebug, DefaultNoBound)]
#[derive(Clone, Encode, Decode, PartialEq, Eq, ScheduleDebug, DefaultNoBound, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct Schedule<T: Config> {
/// Describes the upper limits on various metrics.
pub limits: Limits,
@@ -92,7 +94,7 @@ pub struct Schedule<T: Config> {
/// values will break existing contracts which are above the new limits when a
/// re-instrumentation is triggered.
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Clone, Encode, Decode, PartialEq, Eq, RuntimeDebug)]
#[derive(Clone, Encode, Decode, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct Limits {
/// The maximum number of topics supported by an event.
pub event_topics: u32,
@@ -174,7 +176,8 @@ impl Limits {
/// that use them as supporting instructions. Supporting means mainly pushing arguments
/// and dropping return values in order to maintain a valid module.
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Clone, Encode, Decode, PartialEq, Eq, WeightDebug)]
#[derive(Clone, Encode, Decode, PartialEq, Eq, WeightDebug, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct InstructionWeights<T: Config> {
/// Version of the instruction weights.
///
@@ -247,7 +250,8 @@ pub struct InstructionWeights<T: Config> {
/// Describes the weight for each imported function that a contract is allowed to call.
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Clone, Encode, Decode, PartialEq, Eq, WeightDebug)]
#[derive(Clone, Encode, Decode, PartialEq, Eq, WeightDebug, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct HostFnWeights<T: Config> {
/// Weight of calling `seal_caller`.
pub caller: Weight,
+3 -2
View File
@@ -29,6 +29,7 @@ use frame_support::{
traits::Get,
weights::Weight,
};
use scale_info::TypeInfo;
use sp_core::crypto::UncheckedFrom;
use sp_io::hashing::blake2_256;
use sp_runtime::{traits::Hash, RuntimeDebug};
@@ -38,7 +39,7 @@ pub type ContractInfo<T> = RawContractInfo<CodeHash<T>>;
/// Information for managing an account and its sub trie abstraction.
/// This is the required info to cache for an account.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct RawContractInfo<CodeHash> {
/// Unique ID for the subtree encoded as a bytes vector.
pub trie_id: TrieId,
@@ -61,7 +62,7 @@ fn child_trie_info(trie_id: &[u8]) -> ChildInfo {
ChildInfo::new_default(trie_id)
}
#[derive(Encode, Decode)]
#[derive(Encode, Decode, TypeInfo)]
pub struct DeletedContract {
pub(crate) trie_id: TrieId,
}
+6 -1
View File
@@ -1781,7 +1781,12 @@ fn gas_estimation_call_runtime() {
// Call something trivial with a huge gas limit so that we can observe the effects
// of pre-charging. This should create a difference between consumed and required.
let call = Call::Contracts(crate::Call::call(addr_callee, 0, GAS_LIMIT / 3, vec![]));
let call = Call::Contracts(crate::Call::call {
dest: addr_callee,
value: 0,
gas_limit: GAS_LIMIT / 3,
data: vec![],
});
let result =
Contracts::bare_call(ALICE, addr_caller.clone(), 0, GAS_LIMIT, call.encode(), false);
assert_ok!(&result.result);
+3 -2
View File
@@ -50,7 +50,8 @@ pub use tests::MockExt;
/// `instruction_weights_version` and `code` when a contract with an outdated instrumention is
/// called. Therefore one must be careful when holding any in-memory representation of this
/// type while calling into a contract as those fields can get out of date.
#[derive(Clone, Encode, Decode)]
#[derive(Clone, Encode, Decode, scale_info::TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct PrefabWasmModule<T: Config> {
/// Version of the instruction weights with which the code was instrumented.
#[codec(compact)]
@@ -1967,7 +1968,7 @@ mod tests {
#[cfg(feature = "unstable-interface")]
fn call_runtime_works() {
use std::convert::TryInto;
let call = Call::System(frame_system::Call::remark(b"Hello World".to_vec()));
let call = Call::System(frame_system::Call::remark { remark: b"Hello World".to_vec() });
let mut ext = MockExt::default();
let result = execute(CODE_CALL_RUNTIME, call.encode(), &mut ext).unwrap();
assert_eq!(*ext.runtime_calls.borrow(), vec![call]);
+2
View File
@@ -17,6 +17,7 @@ serde = { version = "1.0.126", optional = true, features = ["derive"] }
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [
"derive",
] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
@@ -34,6 +35,7 @@ default = ["std"]
std = [
"serde",
"codec/std",
"scale-info/std",
"sp-std/std",
"sp-io/std",
"frame-benchmarking/std",
+14 -10
View File
@@ -73,7 +73,7 @@ fn add_referendum<T: Config>(n: u32) -> Result<ReferendumIndex, &'static str> {
None,
63,
frame_system::RawOrigin::Root.into(),
Call::enact_proposal(proposal_hash, referendum_index).into(),
Call::enact_proposal { proposal_hash, index: referendum_index }.into(),
)
.map_err(|_| "failed to schedule named")?;
Ok(referendum_index)
@@ -194,7 +194,7 @@ benchmarks! {
emergency_cancel {
let origin = T::CancellationOrigin::successful_origin();
let referendum_index = add_referendum::<T>(0)?;
let call = Call::<T>::emergency_cancel(referendum_index);
let call = Call::<T>::emergency_cancel { ref_index: referendum_index };
assert_ok!(Democracy::<T>::referendum_status(referendum_index));
}: { call.dispatch_bypass_filter(origin)? }
verify {
@@ -224,7 +224,7 @@ benchmarks! {
let referendum_index = add_referendum::<T>(0)?;
assert_ok!(Democracy::<T>::referendum_status(referendum_index));
let call = Call::<T>::blacklist(hash, Some(referendum_index));
let call = Call::<T>::blacklist { proposal_hash: hash, maybe_ref_index: Some(referendum_index) };
let origin = T::BlacklistOrigin::successful_origin();
}: { call.dispatch_bypass_filter(origin)? }
verify {
@@ -247,7 +247,7 @@ benchmarks! {
(T::BlockNumber::zero(), vec![T::AccountId::default(); v as usize])
);
let call = Call::<T>::external_propose(proposal_hash);
let call = Call::<T>::external_propose { proposal_hash };
}: { call.dispatch_bypass_filter(origin)? }
verify {
// External proposal created
@@ -257,7 +257,7 @@ benchmarks! {
external_propose_majority {
let origin = T::ExternalMajorityOrigin::successful_origin();
let proposal_hash = T::Hashing::hash_of(&0);
let call = Call::<T>::external_propose_majority(proposal_hash);
let call = Call::<T>::external_propose_majority { proposal_hash };
}: { call.dispatch_bypass_filter(origin)? }
verify {
// External proposal created
@@ -267,7 +267,7 @@ benchmarks! {
external_propose_default {
let origin = T::ExternalDefaultOrigin::successful_origin();
let proposal_hash = T::Hashing::hash_of(&0);
let call = Call::<T>::external_propose_default(proposal_hash);
let call = Call::<T>::external_propose_default { proposal_hash };
}: { call.dispatch_bypass_filter(origin)? }
verify {
// External proposal created
@@ -283,7 +283,11 @@ benchmarks! {
let origin_fast_track = T::FastTrackOrigin::successful_origin();
let voting_period = T::FastTrackVotingPeriod::get();
let delay = 0u32;
let call = Call::<T>::fast_track(proposal_hash, voting_period.into(), delay.into());
let call = Call::<T>::fast_track {
proposal_hash,
voting_period: voting_period.into(),
delay: delay.into()
};
}: { call.dispatch_bypass_filter(origin_fast_track)? }
verify {
@@ -306,7 +310,7 @@ benchmarks! {
vetoers.sort();
Blacklist::<T>::insert(proposal_hash, (T::BlockNumber::zero(), vetoers));
let call = Call::<T>::veto_external(proposal_hash);
let call = Call::<T>::veto_external { proposal_hash };
let origin = T::VetoOrigin::successful_origin();
ensure!(NextExternal::<T>::get().is_some(), "no external proposal");
}: { call.dispatch_bypass_filter(origin)? }
@@ -356,7 +360,7 @@ benchmarks! {
let origin = T::ExternalMajorityOrigin::successful_origin();
let proposal_hash = T::Hashing::hash_of(&r);
let call = Call::<T>::external_propose_majority(proposal_hash);
let call = Call::<T>::external_propose_majority { proposal_hash };
call.dispatch_bypass_filter(origin)?;
// External proposal created
ensure!(<NextExternal<T>>::exists(), "External proposal didn't work");
@@ -739,7 +743,7 @@ benchmarks! {
let b in 0 .. MAX_BYTES;
let proposer = funded_account::<T>("proposer", 0);
let raw_call = Call::note_preimage(vec![1; b as usize]);
let raw_call = Call::note_preimage { encoded_proposal: vec![1; b as usize] };
let generic_call: T::Proposal = raw_call.into();
let encoded_proposal = generic_call.encode();
let proposal_hash = T::Hashing::hash(&encoded_proposal[..]);
+2 -1
View File
@@ -19,6 +19,7 @@
use crate::types::Delegations;
use codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{Bounded, CheckedDiv, CheckedMul, Zero},
RuntimeDebug,
@@ -26,7 +27,7 @@ use sp_runtime::{
use sp_std::{convert::TryFrom, result::Result};
/// A value denoting the strength of conviction of a vote.
#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, RuntimeDebug)]
#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, RuntimeDebug, TypeInfo)]
pub enum Conviction {
/// 0.1x votes, unlocked.
None,
+4 -10
View File
@@ -162,6 +162,7 @@ use frame_support::{
},
weights::Weight,
};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{Bounded, Dispatchable, Hash, Saturating, Zero},
ArithmeticError, DispatchError, DispatchResult, RuntimeDebug,
@@ -205,7 +206,7 @@ type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;
#[derive(Clone, Encode, Decode, RuntimeDebug)]
#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
pub enum PreimageStatus<AccountId, Balance, BlockNumber> {
/// The preimage is imminently needed at the argument.
Missing(BlockNumber),
@@ -232,7 +233,7 @@ impl<AccountId, Balance, BlockNumber> PreimageStatus<AccountId, Balance, BlockNu
// A value placed in storage that represents the current version of the Democracy storage.
// This value is used by the `on_runtime_upgrade` logic to determine whether we run
// storage migration logic.
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug)]
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]
enum Releases {
V1,
}
@@ -505,13 +506,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(
T::AccountId = "AccountId",
Vec<T::AccountId> = "Vec<AccountId>",
BalanceOf<T> = "Balance",
T::BlockNumber = "BlockNumber",
T::Hash = "Hash",
)]
pub enum Event<T: Config> {
/// A motion has been proposed by a public account. \[proposal_index, deposit\]
Proposed(PropIndex, BalanceOf<T>),
@@ -1714,7 +1708,7 @@ impl<T: Config> Pallet<T> {
None,
63,
frame_system::RawOrigin::Root.into(),
Call::enact_proposal(status.proposal_hash, index).into(),
Call::enact_proposal { proposal_hash: status.proposal_hash, index }.into(),
)
.is_err()
{
+3 -2
View File
@@ -72,7 +72,7 @@ frame_support::construct_runtime!(
pub struct BaseFilter;
impl Contains<Call> for BaseFilter {
fn contains(call: &Call) -> bool {
!matches!(call, &Call::Balances(pallet_balances::Call::set_balance(..)))
!matches!(call, &Call::Balances(pallet_balances::Call::set_balance { .. }))
}
}
@@ -226,7 +226,8 @@ fn params_should_work() {
}
fn set_balance_proposal(value: u64) -> Vec<u8> {
Call::Balances(pallet_balances::Call::set_balance(42, value, 0)).encode()
Call::Balances(pallet_balances::Call::set_balance { who: 42, new_free: value, new_reserved: 0 })
.encode()
}
#[test]
+5 -4
View File
@@ -19,13 +19,14 @@
use crate::{AccountVote, Conviction, Vote, VoteThreshold};
use codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{Bounded, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, Saturating, Zero},
RuntimeDebug,
};
/// Info regarding an ongoing referendum.
#[derive(Encode, Decode, Default, Clone, PartialEq, Eq, RuntimeDebug)]
#[derive(Encode, Decode, Default, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct Tally<Balance> {
/// The number of aye votes, expressed in terms of post-conviction lock-vote.
pub ayes: Balance,
@@ -36,7 +37,7 @@ pub struct Tally<Balance> {
}
/// Amount of votes and capital placed in delegation for an account.
#[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq, RuntimeDebug)]
#[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct Delegations<Balance> {
/// The number of votes (this is post-conviction).
pub votes: Balance,
@@ -159,7 +160,7 @@ impl<
}
/// Info regarding an ongoing referendum.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct ReferendumStatus<BlockNumber, Hash, Balance> {
/// When voting on this referendum will end.
pub end: BlockNumber,
@@ -174,7 +175,7 @@ pub struct ReferendumStatus<BlockNumber, Hash, Balance> {
}
/// Info regarding a referendum, present or past.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum ReferendumInfo<BlockNumber, Hash, Balance> {
/// Referendum is happening, the arg is the block number at which it will end.
Ongoing(ReferendumStatus<BlockNumber, Hash, Balance>),
+19 -3
View File
@@ -19,6 +19,7 @@
use crate::{Conviction, Delegations, ReferendumIndex};
use codec::{Decode, Encode, EncodeLike, Input, Output};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{Saturating, Zero},
RuntimeDebug,
@@ -51,8 +52,21 @@ impl Decode for Vote {
}
}
impl TypeInfo for Vote {
type Identity = Self;
fn type_info() -> scale_info::Type {
scale_info::Type::builder()
.path(scale_info::Path::new("Vote", module_path!()))
.composite(
scale_info::build::Fields::unnamed()
.field(|f| f.ty::<u8>().docs(&["Raw vote byte, encodes aye + conviction"])),
)
}
}
/// A vote for a referendum of a particular account.
#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, RuntimeDebug)]
#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub enum AccountVote<Balance> {
/// A standard vote, one-way (approve or reject) with a given amount of conviction.
Standard { vote: Vote, balance: Balance },
@@ -92,7 +106,9 @@ impl<Balance: Saturating> AccountVote<Balance> {
}
/// A "prior" lock, i.e. a lock for some now-forgotten reason.
#[derive(Encode, Decode, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, RuntimeDebug)]
#[derive(
Encode, Decode, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, RuntimeDebug, TypeInfo,
)]
pub struct PriorLock<BlockNumber, Balance>(BlockNumber, Balance);
impl<BlockNumber: Ord + Copy + Zero, Balance: Ord + Copy + Zero> PriorLock<BlockNumber, Balance> {
@@ -115,7 +131,7 @@ impl<BlockNumber: Ord + Copy + Zero, Balance: Ord + Copy + Zero> PriorLock<Block
}
/// An indicator for what an account is doing; it can either be delegating or voting.
#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug)]
#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub enum Voting<Balance, AccountId, BlockNumber> {
/// The account is voting directly. `delegations` is the total amount of post-conviction voting
/// weight that it controls from those that have delegated to it.
@@ -19,13 +19,14 @@
use crate::Tally;
use codec::{Decode, Encode};
use scale_info::TypeInfo;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_runtime::traits::{IntegerSquareRoot, Zero};
use sp_std::ops::{Add, Div, Mul, Rem};
/// A means of determining if a vote is past pass threshold.
#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, sp_runtime::RuntimeDebug)]
#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, sp_runtime::RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum VoteThreshold {
/// A supermajority of approvals is needed to pass this vote.
@@ -17,6 +17,7 @@ static_assertions = "1.1.0"
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [
"derive",
] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
log = { version = "0.4.14", default-features = false }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
@@ -55,6 +56,7 @@ frame-benchmarking = { version = "4.0.0-dev", path = "../benchmarking" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"log/std",
"frame-support/std",
@@ -353,7 +353,10 @@ frame_benchmarking::benchmarks! {
// encode the most significant storage item that needs to be decoded in the dispatch.
let encoded_snapshot = <MultiPhase<T>>::snapshot().ok_or("missing snapshot")?.encode();
let encoded_call = <Call<T>>::submit_unsigned(Box::new(raw_solution.clone()), witness).encode();
let encoded_call = Call::<T>::submit_unsigned {
raw_solution: Box::new(raw_solution.clone()),
witness
}.encode();
}: {
assert_ok!(
<MultiPhase<T>>::submit_unsigned(
@@ -217,6 +217,7 @@ use frame_support::{
weights::{DispatchClass, Weight},
};
use frame_system::{ensure_none, offchain::SendTransactionTypes};
use scale_info::TypeInfo;
use sp_arithmetic::{
traits::{CheckedAdd, Saturating, Zero},
UpperOf,
@@ -311,7 +312,7 @@ impl<T: Config> ElectionProvider<T::AccountId, T::BlockNumber> for NoFallback<T>
}
/// Current phase of the pallet.
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, Debug)]
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, Debug, TypeInfo)]
pub enum Phase<Bn> {
/// Nothing, the election is not happening.
Off,
@@ -373,7 +374,7 @@ impl<Bn: PartialEq + Eq> Phase<Bn> {
}
/// The type of `Computation` that provided this election data.
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, Debug)]
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, Debug, TypeInfo)]
pub enum ElectionCompute {
/// Election was computed on-chain.
OnChain,
@@ -399,7 +400,7 @@ impl Default for ElectionCompute {
///
/// Such a solution should never become effective in anyway before being checked by the
/// `Pallet::feasibility_check`.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, PartialOrd, Ord)]
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, PartialOrd, Ord, TypeInfo)]
pub struct RawSolution<S> {
/// the solution itself.
pub solution: S,
@@ -417,7 +418,7 @@ impl<C: Default> Default for RawSolution<C> {
}
/// A checked solution, ready to be enacted.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, Default)]
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, Default, TypeInfo)]
pub struct ReadySolution<A> {
/// The final supports of the solution.
///
@@ -436,7 +437,7 @@ pub struct ReadySolution<A> {
/// [`ElectionDataProvider`] and are kept around until the round is finished.
///
/// These are stored together because they are often accessed together.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, Default)]
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, Default, TypeInfo)]
pub struct RoundSnapshot<A> {
/// All of the voters.
pub voters: Vec<(A, VoteWeight, Vec<A>)>,
@@ -449,7 +450,7 @@ pub struct RoundSnapshot<A> {
/// This is stored automatically on-chain, and it contains the **size of the entire snapshot**.
/// This is also used in dispatchables as weight witness data and should **only contain the size of
/// the presented solution**, not the entire snapshot.
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, Debug, Default)]
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, Debug, Default, TypeInfo)]
pub struct SolutionOrSnapshotSize {
/// The length of voters.
#[codec(compact)]
@@ -643,7 +644,8 @@ pub mod pallet {
+ Clone
+ sp_std::fmt::Debug
+ Ord
+ NposSolution;
+ NposSolution
+ TypeInfo;
/// Configuration for the fallback
type Fallback: ElectionProvider<
@@ -949,7 +951,8 @@ pub mod pallet {
// create the submission
let deposit = Self::deposit_for(&raw_solution, size);
let reward = {
let call = Call::submit(raw_solution.clone(), num_signed_submissions);
let call =
Call::submit { raw_solution: raw_solution.clone(), num_signed_submissions };
let call_fee = T::EstimateCallFee::estimate_call_fee(&call, None.into());
T::SignedRewardBase::get().saturating_add(call_fee)
};
@@ -985,10 +988,6 @@ pub mod pallet {
}
#[pallet::event]
#[pallet::metadata(
<T as frame_system::Config>::AccountId = "AccountId",
BalanceOf<T> = "Balance"
)]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// A solution was stored with the given compute.
@@ -1042,14 +1041,14 @@ pub mod pallet {
impl<T: Config> ValidateUnsigned for Pallet<T> {
type Call = Call<T>;
fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity {
if let Call::submit_unsigned(solution, _) = call {
if let Call::submit_unsigned { raw_solution, .. } = call {
// Discard solution not coming from the local OCW.
match source {
TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ },
_ => return InvalidTransaction::Call.into(),
}
let _ = Self::unsigned_pre_dispatch_checks(solution)
let _ = Self::unsigned_pre_dispatch_checks(raw_solution)
.map_err(|err| {
log!(debug, "unsigned transaction validation failed due to {:?}", err);
err
@@ -1060,11 +1059,11 @@ pub mod pallet {
// The higher the score[0], the better a solution is.
.priority(
T::MinerTxPriority::get()
.saturating_add(solution.score[0].saturated_into()),
.saturating_add(raw_solution.score[0].saturated_into()),
)
// Used to deduplicate unsigned solutions: each validator should produce one
// solution per round at most, and solutions are not propagate.
.and_provides(solution.round)
.and_provides(raw_solution.round)
// Transaction should stay in the pool for the duration of the unsigned phase.
.longevity(T::UnsignedPhase::get().saturated_into::<u64>())
// We don't propagate this. This can never be validated at a remote node.
@@ -1076,8 +1075,8 @@ pub mod pallet {
}
fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
if let Call::submit_unsigned(solution, _) = call {
Self::unsigned_pre_dispatch_checks(solution)
if let Call::submit_unsigned { raw_solution, .. } = call {
Self::unsigned_pre_dispatch_checks(raw_solution)
.map_err(dispatch_error_to_invalid)
.map_err(Into::into)
} else {
@@ -42,7 +42,7 @@ use sp_std::{
/// A raw, unchecked signed submission.
///
/// This is just a wrapper around [`RawSolution`] and some additional info.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, Default)]
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, Default, scale_info::TypeInfo)]
pub struct SignedSubmission<AccountId, Balance: HasCompact, Solution> {
/// Who submitted this solution.
pub who: AccountId,
@@ -160,9 +160,9 @@ impl<T: Config> Pallet<T> {
let call = restore_solution::<T>()
.and_then(|call| {
// ensure the cached call is still current before submitting
if let Call::submit_unsigned(solution, _) = &call {
if let Call::submit_unsigned { raw_solution, .. } = &call {
// prevent errors arising from state changes in a forkful chain
Self::basic_checks(solution, "restored")?;
Self::basic_checks(raw_solution, "restored")?;
Ok(call)
} else {
Err(MinerError::SolutionCallInvalid)
@@ -213,7 +213,8 @@ impl<T: Config> Pallet<T> {
let (raw_solution, witness) = Self::mine_and_check()?;
let score = raw_solution.score.clone();
let call: Call<T> = Call::submit_unsigned(Box::new(raw_solution), witness).into();
let call: Call<T> =
Call::submit_unsigned { raw_solution: Box::new(raw_solution), witness }.into();
log!(
debug,
@@ -763,7 +764,10 @@ mod tests {
ExtBuilder::default().desired_targets(0).build_and_execute(|| {
let solution =
RawSolution::<TestNposSolution> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(Box::new(solution.clone()), witness());
let call = Call::submit_unsigned {
raw_solution: Box::new(solution.clone()),
witness: witness(),
};
// initial
assert_eq!(MultiPhase::current_phase(), Phase::Off);
@@ -833,7 +837,10 @@ mod tests {
let solution =
RawSolution::<TestNposSolution> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(Box::new(solution.clone()), witness());
let call = Call::submit_unsigned {
raw_solution: Box::new(solution.clone()),
witness: witness(),
};
// initial
assert!(<MultiPhase as ValidateUnsigned>::validate_unsigned(
@@ -870,7 +877,8 @@ mod tests {
assert!(MultiPhase::current_phase().is_unsigned());
let raw = RawSolution::<TestNposSolution> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(Box::new(raw.clone()), witness());
let call =
Call::submit_unsigned { raw_solution: Box::new(raw.clone()), witness: witness() };
assert_eq!(raw.solution.unique_targets().len(), 0);
// won't work anymore.
@@ -896,7 +904,10 @@ mod tests {
let solution =
RawSolution::<TestNposSolution> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(Box::new(solution.clone()), witness());
let call = Call::submit_unsigned {
raw_solution: Box::new(solution.clone()),
witness: witness(),
};
assert_eq!(
<MultiPhase as ValidateUnsigned>::validate_unsigned(
@@ -923,7 +934,10 @@ mod tests {
// This is in itself an invalid BS solution.
let solution =
RawSolution::<TestNposSolution> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(Box::new(solution.clone()), witness());
let call = Call::submit_unsigned {
raw_solution: Box::new(solution.clone()),
witness: witness(),
};
let outer_call: OuterCall = call.into();
let _ = outer_call.dispatch(Origin::none());
})
@@ -944,7 +958,10 @@ mod tests {
let mut correct_witness = witness();
correct_witness.voters += 1;
correct_witness.targets -= 1;
let call = Call::submit_unsigned(Box::new(solution.clone()), correct_witness);
let call = Call::submit_unsigned {
raw_solution: Box::new(solution.clone()),
witness: correct_witness,
};
let outer_call: OuterCall = call.into();
let _ = outer_call.dispatch(Origin::none());
})
@@ -1350,7 +1367,7 @@ mod tests {
let encoded = pool.read().transactions[0].clone();
let extrinsic: Extrinsic = codec::Decode::decode(&mut &*encoded).unwrap();
let call = extrinsic.call;
assert!(matches!(call, OuterCall::MultiPhase(Call::submit_unsigned(..))));
assert!(matches!(call, OuterCall::MultiPhase(Call::submit_unsigned { .. })));
})
}
@@ -1367,7 +1384,7 @@ mod tests {
let encoded = pool.read().transactions[0].clone();
let extrinsic = Extrinsic::decode(&mut &*encoded).unwrap();
let call = match extrinsic.call {
OuterCall::MultiPhase(call @ Call::submit_unsigned(..)) => call,
OuterCall::MultiPhase(call @ Call::submit_unsigned { .. }) => call,
_ => panic!("bad call: unexpected submission"),
};
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-arithmetic = { version = "4.0.0-dev", default-features = false, path = "../../primitives/arithmetic" }
sp-npos-elections = { version = "4.0.0-dev", default-features = false, path = "../../primitives/npos-elections" }
@@ -16,6 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [
"derive",
] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
sp-npos-elections = { version = "4.0.0-dev", default-features = false, path = "../../primitives/npos-elections" }
sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" }
@@ -35,6 +36,7 @@ substrate-test-utils = { version = "4.0.0-dev", path = "../../test-utils" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"frame-support/std",
"sp-runtime/std",
"sp-npos-elections/std",
@@ -108,6 +108,7 @@ use frame_support::{
},
weights::Weight,
};
use scale_info::TypeInfo;
use sp_npos_elections::{ElectionResult, ExtendedBalance};
use sp_runtime::{
traits::{Saturating, StaticLookup, Zero},
@@ -135,7 +136,7 @@ type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<
>>::NegativeImbalance;
/// An indication that the renouncing account currently has which of the below roles.
#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug)]
#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)]
pub enum Renouncing {
/// A member is renouncing.
Member,
@@ -146,7 +147,7 @@ pub enum Renouncing {
}
/// An active voter.
#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq)]
#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, TypeInfo)]
pub struct Voter<AccountId, Balance> {
/// The members being backed.
pub votes: Vec<AccountId>,
@@ -159,7 +160,7 @@ pub struct Voter<AccountId, Balance> {
}
/// A holder of a seat as either a member or a runner-up.
#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq)]
#[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq, TypeInfo)]
pub struct SeatHolder<AccountId, Balance> {
/// The holder.
pub who: AccountId,
@@ -531,11 +532,6 @@ pub mod pallet {
}
#[pallet::event]
#[pallet::metadata(
<T as frame_system::Config>::AccountId = "AccountId",
BalanceOf<T> = "Balance",
Vec<(<T as frame_system::Config>::AccountId, BalanceOf<T>)> = "Vec<(AccountId, Balance)>",
)]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// A new term with \[new_members\]. This indicates that enough candidates existed to run
+2
View File
@@ -16,6 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [
"derive",
] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-core = { version = "4.0.0-dev", default-features = false, path = "../../primitives/core" }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" }
@@ -30,6 +31,7 @@ pallet-balances = { version = "4.0.0-dev", path = "../balances" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-core/std",
"sp-std/std",
"sp-io/std",
+3 -2
View File
@@ -111,7 +111,9 @@ mod tests;
// entries before they increase the capacity.
/// The activity status of a voter.
#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, Default, RuntimeDebug)]
#[derive(
PartialEq, Eq, Copy, Clone, Encode, Decode, Default, RuntimeDebug, scale_info::TypeInfo,
)]
pub struct VoterInfo<Balance> {
/// Last VoteIndex in which this voter assigned (or initialized) approvals.
last_active: VoteIndex,
@@ -462,7 +464,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(T::AccountId = "AccountId", Vec<T::AccountId> = "Vec<AccountId>")]
pub enum Event<T: Config> {
/// Reaped \[voter, reaper\].
VoterReaped(T::AccountId, T::AccountId),
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }
sp-core = { version = "4.0.0-dev", default-features = false, path = "../../primitives/core" }
@@ -28,6 +29,7 @@ log = { version = "0.4.14", default-features = false }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"frame-support/std",
"frame-system/std",
"lite-json/std",
@@ -294,8 +294,10 @@ pub mod pallet {
/// are being whitelisted and marked as valid.
fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
// Firstly let's check that we call the right function.
if let Call::submit_price_unsigned_with_signed_payload(ref payload, ref signature) =
call
if let Call::submit_price_unsigned_with_signed_payload {
price_payload: ref payload,
ref signature,
} = call
{
let signature_valid =
SignedPayload::<T>::verify::<T::AuthorityId>(payload, signature.clone());
@@ -303,7 +305,7 @@ pub mod pallet {
return InvalidTransaction::BadProof.into()
}
Self::validate_transaction_parameters(&payload.block_number, &payload.price)
} else if let Call::submit_price_unsigned(block_number, new_price) = call {
} else if let Call::submit_price_unsigned { block_number, price: new_price } = call {
Self::validate_transaction_parameters(block_number, new_price)
} else {
InvalidTransaction::Call.into()
@@ -330,7 +332,7 @@ pub mod pallet {
/// Payload used by this example crate to hold price
/// data required to submit a transaction.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, scale_info::TypeInfo)]
pub struct PricePayload<Public, BlockNumber> {
block_number: BlockNumber,
price: u32,
@@ -443,7 +445,7 @@ impl<T: Config> Pallet<T> {
// Received price is wrapped into a call to `submit_price` public function of this
// pallet. This means that the transaction, when executed, will simply call that
// function passing `price` as an argument.
Call::submit_price(price)
Call::submit_price { price }
});
for (acc, res) in &results {
@@ -472,7 +474,7 @@ impl<T: Config> Pallet<T> {
// Received price is wrapped into a call to `submit_price_unsigned` public function of this
// pallet. This means that the transaction, when executed, will simply call that function
// passing `price` as an argument.
let call = Call::submit_price_unsigned(block_number, price);
let call = Call::submit_price_unsigned { block_number, price };
// Now let's create a transaction out of this call and submit it to the pool.
// Here we showcase two ways to send an unsigned transaction / unsigned payload (raw)
@@ -507,8 +509,9 @@ impl<T: Config> Pallet<T> {
let (_, result) = Signer::<T, T::AuthorityId>::any_account()
.send_unsigned_transaction(
|account| PricePayload { price, block_number, public: account.public.clone() },
|payload, signature| {
Call::submit_price_unsigned_with_signed_payload(payload, signature)
|payload, signature| Call::submit_price_unsigned_with_signed_payload {
price_payload: payload,
signature,
},
)
.ok_or("No local accounts accounts available.")?;
@@ -536,8 +539,9 @@ impl<T: Config> Pallet<T> {
let transaction_results = Signer::<T, T::AuthorityId>::all_accounts()
.send_unsigned_transaction(
|account| PricePayload { price, block_number, public: account.public.clone() },
|payload, signature| {
Call::submit_price_unsigned_with_signed_payload(payload, signature)
|payload, signature| Call::submit_price_unsigned_with_signed_payload {
price_payload: payload,
signature,
},
);
for (_account_id, result) in transaction_results.into_iter() {
@@ -227,7 +227,7 @@ fn should_submit_signed_transaction_on_chain() {
assert!(pool_state.read().transactions.is_empty());
let tx = Extrinsic::decode(&mut &*tx).unwrap();
assert_eq!(tx.signature.unwrap().0, 0);
assert_eq!(tx.call, Call::Example(crate::Call::submit_price(15523)));
assert_eq!(tx.call, Call::Example(crate::Call::submit_price { price: 15523 }));
});
}
@@ -273,10 +273,10 @@ fn should_submit_unsigned_transaction_on_chain_for_any_account() {
let tx = pool_state.write().transactions.pop().unwrap();
let tx = Extrinsic::decode(&mut &*tx).unwrap();
assert_eq!(tx.signature, None);
if let Call::Example(crate::Call::submit_price_unsigned_with_signed_payload(
body,
if let Call::Example(crate::Call::submit_price_unsigned_with_signed_payload {
price_payload: body,
signature,
)) = tx.call
}) = tx.call
{
assert_eq!(body, price_payload);
@@ -333,10 +333,10 @@ fn should_submit_unsigned_transaction_on_chain_for_all_accounts() {
let tx = pool_state.write().transactions.pop().unwrap();
let tx = Extrinsic::decode(&mut &*tx).unwrap();
assert_eq!(tx.signature, None);
if let Call::Example(crate::Call::submit_price_unsigned_with_signed_payload(
body,
if let Call::Example(crate::Call::submit_price_unsigned_with_signed_payload {
price_payload: body,
signature,
)) = tx.call
}) = tx.call
{
assert_eq!(body, price_payload);
@@ -373,7 +373,10 @@ fn should_submit_raw_unsigned_transaction_on_chain() {
assert!(pool_state.read().transactions.is_empty());
let tx = Extrinsic::decode(&mut &*tx).unwrap();
assert_eq!(tx.signature, None);
assert_eq!(tx.call, Call::Example(crate::Call::submit_price_unsigned(1, 15523)));
assert_eq!(
tx.call,
Call::Example(crate::Call::submit_price_unsigned { block_number: 1, price: 15523 })
);
});
}
@@ -13,6 +13,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }
sp-core = { version = "4.0.0-dev", default-features = false, path = "../../primitives/core" }
@@ -25,6 +26,7 @@ sp-tasks = { version = "4.0.0-dev", default-features = false, path = "../../prim
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"frame-support/std",
"frame-system/std",
"sp-core/std",
+1 -1
View File
@@ -95,7 +95,7 @@ pub mod pallet {
}
/// Request to enlist participant.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, scale_info::TypeInfo)]
pub struct EnlistedParticipant {
pub account: Vec<u8>,
pub signature: Vec<u8>,
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }
pallet-balances = { version = "4.0.0-dev", default-features = false, path = "../balances" }
@@ -35,6 +36,7 @@ std = [
"frame-system/std",
"log/std",
"pallet-balances/std",
"scale-info/std",
"sp-io/std",
"sp-runtime/std",
"sp-std/std"
+9 -7
View File
@@ -277,6 +277,7 @@ use frame_support::{
};
use frame_system::ensure_signed;
use log::info;
use scale_info::TypeInfo;
use sp_runtime::{
traits::{Bounded, DispatchInfoOf, SaturatedConversion, Saturating, SignedExtension},
transaction_validity::{
@@ -688,12 +689,13 @@ impl<T: Config> Pallet<T> {
// types defined in the runtime. Lookup `pub type SignedExtra = (...)` in `node/runtime` and
// `node-template` for an example of this.
// A simple signed extension that checks for the `set_dummy` call. In that case, it increases the
// priority and prints some log.
//
// Additionally, it drops any transaction with an encoded length higher than 200 bytes. No
// particular reason why, just to demonstrate the power of signed extensions.
#[derive(Encode, Decode, Clone, Eq, PartialEq)]
/// A simple signed extension that checks for the `set_dummy` call. In that case, it increases the
/// priority and prints some log.
///
/// Additionally, it drops any transaction with an encoded length higher than 200 bytes. No
/// particular reason why, just to demonstrate the power of signed extensions.
#[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct WatchDummy<T: Config + Send + Sync>(PhantomData<T>);
impl<T: Config + Send + Sync> sp_std::fmt::Debug for WatchDummy<T> {
@@ -730,7 +732,7 @@ where
// check for `set_dummy`
match call.is_sub_type() {
Some(Call::set_dummy(..)) => {
Some(Call::set_dummy { .. }) => {
sp_runtime::print("set_dummy was received.");
let mut valid_tx = ValidTransaction::default();
+3 -3
View File
@@ -163,7 +163,7 @@ fn set_dummy_works() {
#[test]
fn signed_ext_watch_dummy_works() {
new_test_ext().execute_with(|| {
let call = <pallet_example::Call<Test>>::set_dummy(10).into();
let call = pallet_example::Call::set_dummy { new_value: 10 }.into();
let info = DispatchInfo::default();
assert_eq!(
@@ -183,14 +183,14 @@ fn signed_ext_watch_dummy_works() {
#[test]
fn weights_work() {
// must have a defined weight.
let default_call = <pallet_example::Call<Test>>::accumulate_dummy(10);
let default_call = pallet_example::Call::<Test>::accumulate_dummy { increase_by: 10 };
let info1 = default_call.get_dispatch_info();
// aka. `let info = <Call<Test> as GetDispatchInfo>::get_dispatch_info(&default_call);`
assert!(info1.weight > 0);
// `set_dummy` is simpler than `accumulate_dummy`, and the weight
// should be less.
let custom_call = <pallet_example::Call<Test>>::set_dummy(20);
let custom_call = pallet_example::Call::<Test>::set_dummy { new_value: 20 };
let info2 = custom_call.get_dispatch_info();
assert!(info1.weight > info2.weight);
}
+2
View File
@@ -16,6 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [
"derive",
] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
@@ -38,6 +39,7 @@ default = ["std"]
with-tracing = ["sp-tracing/with-tracing"]
std = [
"codec/std",
"scale-info/std",
"frame-support/std",
"frame-system/std",
"sp-core/std",
+45 -21
View File
@@ -645,7 +645,7 @@ mod tests {
None
}
fn is_inherent(call: &Self::Call) -> bool {
*call == Call::<T>::inherent_call()
*call == Call::<T>::inherent_call {}
}
}
@@ -658,7 +658,7 @@ mod tests {
call: &Self::Call,
) -> TransactionValidity {
match call {
Call::allowed_unsigned(..) => Ok(Default::default()),
Call::allowed_unsigned { .. } => Ok(Default::default()),
_ => UnknownTransaction::NoUnsignedValidator.into(),
}
}
@@ -666,8 +666,8 @@ mod tests {
// Inherent call is accepted for being dispatched
fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
match call {
Call::allowed_unsigned(..) => Ok(()),
Call::inherent_call(..) => Ok(()),
Call::allowed_unsigned { .. } => Ok(()),
Call::inherent_call { .. } => Ok(()),
_ => Err(UnknownTransaction::NoUnsignedValidator.into()),
}
}
@@ -809,13 +809,17 @@ mod tests {
Some((who, extra(nonce, fee)))
}
fn call_transfer(dest: u64, value: u64) -> Call {
Call::Balances(BalancesCall::transfer { dest, value })
}
#[test]
fn balance_transfer_dispatch_works() {
let mut t = frame_system::GenesisConfig::default().build_storage::<Runtime>().unwrap();
pallet_balances::GenesisConfig::<Runtime> { balances: vec![(1, 211)] }
.assimilate_storage(&mut t)
.unwrap();
let xt = TestXt::new(Call::Balances(BalancesCall::transfer(2, 69)), sign_extra(1, 0, 0));
let xt = TestXt::new(call_transfer(2, 69), sign_extra(1, 0, 0));
let weight = xt.get_dispatch_info().weight +
<Runtime as frame_system::Config>::BlockWeights::get()
.get(DispatchClass::Normal)
@@ -912,7 +916,7 @@ mod tests {
fn bad_extrinsic_not_inserted() {
let mut t = new_test_ext(1);
// bad nonce check!
let xt = TestXt::new(Call::Balances(BalancesCall::transfer(33, 69)), sign_extra(1, 30, 0));
let xt = TestXt::new(call_transfer(33, 69), sign_extra(1, 30, 0));
t.execute_with(|| {
Executive::initialize_block(&Header::new(
1,
@@ -933,7 +937,10 @@ mod tests {
fn block_weight_limit_enforced() {
let mut t = new_test_ext(10000);
// given: TestXt uses the encoded len as fixed Len:
let xt = TestXt::new(Call::Balances(BalancesCall::transfer(33, 0)), sign_extra(1, 0, 0));
let xt = TestXt::new(
Call::Balances(BalancesCall::transfer { dest: 33, value: 0 }),
sign_extra(1, 0, 0),
);
let encoded = xt.encode();
let encoded_len = encoded.len() as Weight;
// on_initialize weight + base block execution weight
@@ -954,7 +961,7 @@ mod tests {
for nonce in 0..=num_to_exhaust_block {
let xt = TestXt::new(
Call::Balances(BalancesCall::transfer(33, 0)),
Call::Balances(BalancesCall::transfer { dest: 33, value: 0 }),
sign_extra(1, nonce.into(), 0),
);
let res = Executive::apply_extrinsic(xt);
@@ -978,9 +985,18 @@ mod tests {
#[test]
fn block_weight_and_size_is_stored_per_tx() {
let xt = TestXt::new(Call::Balances(BalancesCall::transfer(33, 0)), sign_extra(1, 0, 0));
let x1 = TestXt::new(Call::Balances(BalancesCall::transfer(33, 0)), sign_extra(1, 1, 0));
let x2 = TestXt::new(Call::Balances(BalancesCall::transfer(33, 0)), sign_extra(1, 2, 0));
let xt = TestXt::new(
Call::Balances(BalancesCall::transfer { dest: 33, value: 0 }),
sign_extra(1, 0, 0),
);
let x1 = TestXt::new(
Call::Balances(BalancesCall::transfer { dest: 33, value: 0 }),
sign_extra(1, 1, 0),
);
let x2 = TestXt::new(
Call::Balances(BalancesCall::transfer { dest: 33, value: 0 }),
sign_extra(1, 2, 0),
);
let len = xt.clone().encode().len() as u32;
let mut t = new_test_ext(1);
t.execute_with(|| {
@@ -1034,8 +1050,8 @@ mod tests {
#[test]
fn validate_unsigned() {
let valid = TestXt::new(Call::Custom(custom::Call::allowed_unsigned()), None);
let invalid = TestXt::new(Call::Custom(custom::Call::unallowed_unsigned()), None);
let valid = TestXt::new(Call::Custom(custom::Call::allowed_unsigned {}), None);
let invalid = TestXt::new(Call::Custom(custom::Call::unallowed_unsigned {}), None);
let mut t = new_test_ext(1);
let mut default_with_prio_3 = ValidTransaction::default();
@@ -1074,8 +1090,10 @@ mod tests {
<pallet_balances::Pallet<Runtime> as LockableCurrency<Balance>>::set_lock(
id, &1, 110, lock,
);
let xt =
TestXt::new(Call::System(SystemCall::remark(vec![1u8])), sign_extra(1, 0, 0));
let xt = TestXt::new(
Call::System(SystemCall::remark { remark: vec![1u8] }),
sign_extra(1, 0, 0),
);
let weight = xt.get_dispatch_info().weight +
<Runtime as frame_system::Config>::BlockWeights::get()
.get(DispatchClass::Normal)
@@ -1222,7 +1240,10 @@ mod tests {
/// used through the `ExecuteBlock` trait.
#[test]
fn custom_runtime_upgrade_is_called_when_using_execute_block_trait() {
let xt = TestXt::new(Call::Balances(BalancesCall::transfer(33, 0)), sign_extra(1, 0, 0));
let xt = TestXt::new(
Call::Balances(BalancesCall::transfer { dest: 33, value: 0 }),
sign_extra(1, 0, 0),
);
let header = new_test_ext(1).execute_with(|| {
// Make sure `on_runtime_upgrade` is called.
@@ -1326,7 +1347,7 @@ mod tests {
#[test]
fn calculating_storage_root_twice_works() {
let call = Call::Custom(custom::Call::calculate_storage_root());
let call = Call::Custom(custom::Call::calculate_storage_root {});
let xt = TestXt::new(call, sign_extra(1, 0, 0));
let header = new_test_ext(1).execute_with(|| {
@@ -1352,8 +1373,11 @@ mod tests {
#[test]
#[should_panic(expected = "Invalid inherent position for extrinsic at index 1")]
fn invalid_inherent_position_fail() {
let xt1 = TestXt::new(Call::Balances(BalancesCall::transfer(33, 0)), sign_extra(1, 0, 0));
let xt2 = TestXt::new(Call::Custom(custom::Call::inherent_call()), None);
let xt1 = TestXt::new(
Call::Balances(BalancesCall::transfer { dest: 33, value: 0 }),
sign_extra(1, 0, 0),
);
let xt2 = TestXt::new(Call::Custom(custom::Call::inherent_call {}), None);
let header = new_test_ext(1).execute_with(|| {
// Let's build some fake block.
@@ -1378,8 +1402,8 @@ mod tests {
#[test]
fn valid_inherents_position_works() {
let xt1 = TestXt::new(Call::Custom(custom::Call::inherent_call()), None);
let xt2 = TestXt::new(Call::Balances(BalancesCall::transfer(33, 0)), sign_extra(1, 0, 0));
let xt1 = TestXt::new(Call::Custom(custom::Call::inherent_call {}), None);
let xt2 = TestXt::new(call_transfer(33, 0), sign_extra(1, 0, 0));
let header = new_test_ext(1).execute_with(|| {
// Let's build some fake block.
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
sp-arithmetic = { version = "4.0.0-dev", default-features = false, path = "../../primitives/arithmetic" }
@@ -30,6 +31,7 @@ pallet-balances = { version = "4.0.0-dev", path = "../balances" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-std/std",
"sp-runtime/std",
"sp-arithmetic/std",
+3 -3
View File
@@ -81,7 +81,7 @@ benchmarks! {
}
set_target {
let call = Call::<T>::set_target(Default::default());
let call = Call::<T>::set_target { target: Default::default() };
let origin = T::AdminOrigin::successful_origin();
}: { call.dispatch_bypass_filter(origin)? }
@@ -111,7 +111,7 @@ benchmarks! {
Gilt::<T>::place_bid(RawOrigin::Signed(caller.clone()).into(), T::MinFreeze::get(), 1)?;
}
Call::<T>::set_target(Perquintill::from_percent(100))
Call::<T>::set_target { target: Perquintill::from_percent(100) }
.dispatch_bypass_filter(T::AdminOrigin::successful_origin())?;
}: { Gilt::<T>::pursue_target(b) }
@@ -127,7 +127,7 @@ benchmarks! {
Gilt::<T>::place_bid(RawOrigin::Signed(caller.clone()).into(), T::MinFreeze::get(), i + 1)?;
}
Call::<T>::set_target(Perquintill::from_percent(100))
Call::<T>::set_target { target: Perquintill::from_percent(100) }
.dispatch_bypass_filter(T::AdminOrigin::successful_origin())?;
}: { Gilt::<T>::pursue_target(q) }
+6 -5
View File
@@ -82,6 +82,7 @@ pub mod pallet {
traits::{Currency, OnUnbalanced, ReservableCurrency},
};
use frame_system::pallet_prelude::*;
use scale_info::TypeInfo;
use sp_arithmetic::{PerThing, Perquintill};
use sp_runtime::traits::{Saturating, Zero};
use sp_std::prelude::*;
@@ -111,7 +112,8 @@ pub mod pallet {
+ MaybeSerializeDeserialize
+ sp_std::fmt::Debug
+ Default
+ From<u64>;
+ From<u64>
+ TypeInfo;
/// Origin required for setting the target proportion to be under gilt.
type AdminOrigin: EnsureOrigin<Self::Origin>;
@@ -181,7 +183,7 @@ pub mod pallet {
pub struct Pallet<T>(_);
/// A single bid on a gilt, an item of a *queue* in `Queues`.
#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug)]
#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct GiltBid<Balance, AccountId> {
/// The amount bid.
pub amount: Balance,
@@ -190,7 +192,7 @@ pub mod pallet {
}
/// Information representing an active gilt.
#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug)]
#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct ActiveGilt<Balance, AccountId, BlockNumber> {
/// The proportion of the effective total issuance (i.e. accounting for any eventual gilt
/// expansion or contraction that may eventually be claimed).
@@ -214,7 +216,7 @@ pub mod pallet {
/// `issuance - frozen + proportion * issuance`
///
/// where `issuance = total_issuance - IgnoredIssuance`
#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug)]
#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct ActiveGiltsTotal<Balance> {
/// The total amount of funds held in reserve for all active gilts.
pub frozen: Balance,
@@ -269,7 +271,6 @@ pub mod pallet {
}
#[pallet::event]
#[pallet::metadata(T::AccountId = "AccountId")]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// A bid was successfully placed.
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-application-crypto = { version = "4.0.0-dev", default-features = false, path = "../../primitives/application-crypto" }
sp-core = { version = "4.0.0-dev", default-features = false, path = "../../primitives/core" }
sp-finality-grandpa = { version = "4.0.0-dev", default-features = false, path = "../../primitives/finality-grandpa" }
@@ -44,6 +45,7 @@ frame-election-provider-support = { version = "4.0.0-dev", path = "../election-p
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"frame-benchmarking/std",
"sp-application-crypto/std",
"sp-core/std",
+6 -4
View File
@@ -164,8 +164,10 @@ where
) -> DispatchResult {
use frame_system::offchain::SubmitTransaction;
let call =
Call::report_equivocation_unsigned(Box::new(equivocation_proof), key_owner_proof);
let call = Call::report_equivocation_unsigned {
equivocation_proof: Box::new(equivocation_proof),
key_owner_proof,
};
match SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into()) {
Ok(()) => log::info!(
@@ -203,7 +205,7 @@ pub struct GrandpaTimeSlot {
/// unsigned equivocation reports.
impl<T: Config> Pallet<T> {
pub fn validate_unsigned(source: TransactionSource, call: &Call<T>) -> TransactionValidity {
if let Call::report_equivocation_unsigned(equivocation_proof, key_owner_proof) = call {
if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call {
// discard equivocation report not coming from the local node
match source {
TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ },
@@ -242,7 +244,7 @@ impl<T: Config> Pallet<T> {
}
pub fn pre_dispatch(call: &Call<T>) -> Result<(), TransactionValidityError> {
if let Call::report_equivocation_unsigned(equivocation_proof, key_owner_proof) = call {
if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call {
is_known_offence::<T>(equivocation_proof, key_owner_proof)
} else {
Err(InvalidTransaction::Call.into())
+4 -2
View File
@@ -67,6 +67,8 @@ pub use equivocation::{
pub use pallet::*;
use scale_info::TypeInfo;
/// The current storage version.
const STORAGE_VERSION: StorageVersion = StorageVersion::new(4);
@@ -354,7 +356,7 @@ pub trait WeightInfo {
}
/// A stored pending change.
#[derive(Encode, Decode)]
#[derive(Encode, Decode, TypeInfo)]
pub struct StoredPendingChange<N> {
/// The block number this was scheduled at.
pub scheduled_at: N,
@@ -370,7 +372,7 @@ pub struct StoredPendingChange<N> {
/// Current state of the GRANDPA authority set. State transitions must happen in
/// the same order of states defined below, e.g. `Paused` implies a prior
/// `PendingPause`.
#[derive(Decode, Encode)]
#[derive(Decode, Encode, TypeInfo)]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub enum StoredState<N> {
/// The current authority set is live, and GRANDPA is enabled.
+8 -8
View File
@@ -681,10 +681,10 @@ fn report_equivocation_validate_unsigned_prevents_duplicates() {
let key_owner_proof =
Historical::prove((sp_finality_grandpa::KEY_TYPE, &equivocation_key)).unwrap();
let call = Call::report_equivocation_unsigned(
Box::new(equivocation_proof.clone()),
key_owner_proof.clone(),
);
let call = Call::report_equivocation_unsigned {
equivocation_proof: Box::new(equivocation_proof.clone()),
key_owner_proof: key_owner_proof.clone(),
};
// only local/inblock reports are allowed
assert_eq!(
@@ -843,10 +843,10 @@ fn valid_equivocation_reports_dont_pay_fees() {
Historical::prove((sp_finality_grandpa::KEY_TYPE, &equivocation_key)).unwrap();
// check the dispatch info for the call.
let info = Call::<Test>::report_equivocation_unsigned(
Box::new(equivocation_proof.clone()),
key_owner_proof.clone(),
)
let info = Call::<Test>::report_equivocation_unsigned {
equivocation_proof: Box::new(equivocation_proof.clone()),
key_owner_proof: key_owner_proof.clone(),
}
.get_dispatch_info();
// it should have non-zero weight and the fee has to be paid.
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.2.0", default-features = false, features = ["derive", "max-encoded-len"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
enumflags2 = { version = "0.6.2" }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" }
@@ -30,6 +31,7 @@ pallet-balances = { version = "4.0.0-dev", path = "../balances" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-std/std",
"sp-io/std",
"sp-runtime/std",
-4
View File
@@ -240,10 +240,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(
T::AccountId = "AccountId",
BalanceOf<T> = "Balance"
)]
pub enum Event<T: Config> {
/// A name was set or reset (which will remove all judgements). \[who\]
IdentitySet(T::AccountId),
+165 -5
View File
@@ -22,6 +22,10 @@ use frame_support::{
traits::{ConstU32, Get},
BoundedVec, CloneNoBound, PartialEqNoBound, RuntimeDebugNoBound,
};
use scale_info::{
build::{Fields, Variants},
meta_type, Path, Type, TypeInfo, TypeParameter,
};
use sp_runtime::{traits::Zero, RuntimeDebug};
use sp_std::{fmt::Debug, iter::once, ops::Add, prelude::*};
@@ -89,6 +93,81 @@ impl Encode for Data {
}
impl codec::EncodeLike for Data {}
/// Add a Raw variant with the given index and a fixed sized byte array
macro_rules! data_raw_variants {
($variants:ident, $(($index:literal, $size:literal)),* ) => {
$variants
$(
.variant(concat!("Raw", stringify!($size)), |v| v
.index($index)
.fields(Fields::unnamed().field(|f| f.ty::<[u8; $size]>()))
)
)*
}
}
impl TypeInfo for Data {
type Identity = Self;
fn type_info() -> Type {
let variants = Variants::new().variant("None", |v| v.index(0));
// create a variant for all sizes of Raw data from 0-32
let variants = data_raw_variants!(
variants,
(1, 0),
(2, 1),
(3, 2),
(4, 3),
(5, 4),
(6, 5),
(7, 6),
(8, 7),
(9, 8),
(10, 9),
(11, 10),
(12, 11),
(13, 12),
(14, 13),
(15, 14),
(16, 15),
(17, 16),
(18, 17),
(19, 18),
(20, 19),
(21, 20),
(22, 21),
(23, 22),
(24, 23),
(25, 24),
(26, 25),
(27, 26),
(28, 27),
(29, 28),
(30, 29),
(31, 30),
(32, 31),
(33, 32)
);
let variants = variants
.variant("BlakeTwo256", |v| {
v.index(34).fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))
})
.variant("Sha256", |v| {
v.index(35).fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))
})
.variant("Keccak256", |v| {
v.index(36).fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))
})
.variant("ShaThree256", |v| {
v.index(37).fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))
});
Type::builder().path(Path::new("Data", module_path!())).variant(variants)
}
}
impl Default for Data {
fn default() -> Self {
Self::None
@@ -102,7 +181,7 @@ pub type RegistrarIndex = u32;
///
/// NOTE: Registrars may pay little attention to some fields. Registrars may want to make clear
/// which fields their attestation is relevant for by off-chain means.
#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen)]
#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub enum Judgement<Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq>
{
/// The default value; no opinion is held.
@@ -152,7 +231,7 @@ impl<Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + Part
/// The fields that we use to identify the owner of an account with. Each corresponds to a field
/// in the `IdentityInfo` struct.
#[repr(u64)]
#[derive(Clone, Copy, PartialEq, Eq, BitFlags, RuntimeDebug)]
#[derive(Clone, Copy, PartialEq, Eq, BitFlags, RuntimeDebug, TypeInfo)]
pub enum IdentityField {
Display = 0b0000000000000000000000000000000000000000000000000000000000000001,
Legal = 0b0000000000000000000000000000000000000000000000000000000000000010,
@@ -186,16 +265,27 @@ impl Decode for IdentityFields {
Ok(Self(<BitFlags<IdentityField>>::from_bits(field as u64).map_err(|_| "invalid value")?))
}
}
impl TypeInfo for IdentityFields {
type Identity = Self;
fn type_info() -> Type {
Type::builder()
.path(Path::new("BitFlags", module_path!()))
.type_params(vec![TypeParameter::new("T", Some(meta_type::<IdentityField>()))])
.composite(Fields::unnamed().field(|f| f.ty::<u64>().type_name("IdentityField")))
}
}
/// Information concerning the identity of the controller of an account.
///
/// NOTE: This should be stored at the end of the storage item to facilitate the addition of extra
/// fields in a backwards compatible way through a specialized `Decode` impl.
#[derive(
CloneNoBound, Encode, Decode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound,
CloneNoBound, Encode, Decode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo,
)]
#[codec(mel_bound(FieldLimit: Get<u32>))]
#[cfg_attr(test, derive(frame_support::DefaultNoBound))]
#[scale_info(skip_type_params(FieldLimit))]
pub struct IdentityInfo<FieldLimit: Get<u32>> {
/// Additional fields of the identity that are not catered for with the struct's explicit
/// fields.
@@ -246,12 +336,15 @@ pub struct IdentityInfo<FieldLimit: Get<u32>> {
///
/// NOTE: This is stored separately primarily to facilitate the addition of extra fields in a
/// backwards compatible way through a specialized `Decode` impl.
#[derive(CloneNoBound, Encode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound)]
#[derive(
CloneNoBound, Encode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo,
)]
#[codec(mel_bound(
Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq + Zero + Add,
MaxJudgements: Get<u32>,
MaxAdditionalFields: Get<u32>,
))]
#[scale_info(skip_type_params(MaxJudgements, MaxAdditionalFields))]
pub struct Registration<
Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq,
MaxJudgements: Get<u32>,
@@ -296,7 +389,7 @@ impl<
}
/// Information concerning a registrar.
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen)]
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub struct RegistrarInfo<
Balance: Encode + Decode + Clone + Debug + Eq + PartialEq,
AccountId: Encode + Decode + Clone + Debug + Eq + PartialEq,
@@ -311,3 +404,70 @@ pub struct RegistrarInfo<
/// these fields.
pub fields: IdentityFields,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn manual_data_type_info() {
let mut registry = scale_info::Registry::new();
let type_id = registry.register_type(&scale_info::meta_type::<Data>());
let registry: scale_info::PortableRegistry = registry.into();
let type_info = registry.resolve(type_id.id()).unwrap();
let check_type_info = |data: &Data| {
let variant_name = match data {
Data::None => "None".to_string(),
Data::BlakeTwo256(_) => "BlakeTwo256".to_string(),
Data::Sha256(_) => "Sha256".to_string(),
Data::Keccak256(_) => "Keccak256".to_string(),
Data::ShaThree256(_) => "ShaThree256".to_string(),
Data::Raw(bytes) => format!("Raw{}", bytes.len()),
};
if let scale_info::TypeDef::Variant(variant) = type_info.type_def() {
let variant = variant
.variants()
.iter()
.find(|v| v.name() == &variant_name)
.expect(&format!("Expected to find variant {}", variant_name));
let field_arr_len = variant
.fields()
.first()
.and_then(|f| registry.resolve(f.ty().id()))
.map(|ty| {
if let scale_info::TypeDef::Array(arr) = ty.type_def() {
arr.len()
} else {
panic!("Should be an array type")
}
})
.unwrap_or(0);
let encoded = data.encode();
assert_eq!(encoded[0], variant.index());
assert_eq!(encoded.len() as u32 - 1, field_arr_len);
} else {
panic!("Should be a variant type")
};
};
let mut data = vec![
Data::None,
Data::BlakeTwo256(Default::default()),
Data::Sha256(Default::default()),
Data::Keccak256(Default::default()),
Data::ShaThree256(Default::default()),
];
// A Raw instance for all possible sizes of the Raw data
for n in 0..32 {
data.push(Data::Raw(vec![0u8; n as usize].try_into().unwrap()))
}
for d in data.iter() {
check_type_info(d);
}
}
}
+2
View File
@@ -16,6 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"]
sp-application-crypto = { version = "4.0.0-dev", default-features = false, path = "../../primitives/application-crypto" }
pallet-authorship = { version = "4.0.0-dev", default-features = false, path = "../authorship" }
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-core = { version = "4.0.0-dev", default-features = false, path = "../../primitives/core" }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" }
@@ -36,6 +37,7 @@ std = [
"sp-application-crypto/std",
"pallet-authorship/std",
"codec/std",
"scale-info/std",
"sp-core/std",
"sp-std/std",
"sp-io/std",
@@ -80,7 +80,7 @@ benchmarks! {
let k in 1 .. MAX_KEYS;
let e in 1 .. MAX_EXTERNAL_ADDRESSES;
let (input_heartbeat, signature) = create_heartbeat::<T>(k, e)?;
let call = Call::heartbeat(input_heartbeat, signature);
let call = Call::heartbeat { heartbeat: input_heartbeat, signature };
}: {
ImOnline::<T>::validate_unsigned(TransactionSource::InBlock, &call)
.map_err(<&str>::from)?;
@@ -90,7 +90,7 @@ benchmarks! {
let k in 1 .. MAX_KEYS;
let e in 1 .. MAX_EXTERNAL_ADDRESSES;
let (input_heartbeat, signature) = create_heartbeat::<T>(k, e)?;
let call = Call::heartbeat(input_heartbeat, signature);
let call = Call::heartbeat { heartbeat: input_heartbeat, signature };
}: {
ImOnline::<T>::validate_unsigned(TransactionSource::InBlock, &call)
.map_err(<&str>::from)?;
+8 -8
View File
@@ -80,6 +80,7 @@ use frame_support::traits::{
};
use frame_system::offchain::{SendTransactionTypes, SubmitTransaction};
pub use pallet::*;
use scale_info::TypeInfo;
use sp_application_crypto::RuntimeAppPublic;
use sp_core::offchain::OpaqueNetworkState;
use sp_runtime::{
@@ -140,7 +141,7 @@ const INCLUDE_THRESHOLD: u32 = 3;
/// This stores the block number at which heartbeat was requested and when the worker
/// has actually managed to produce it.
/// Note we store such status for every `authority_index` separately.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
struct HeartbeatStatus<BlockNumber> {
/// An index of the session that we are supposed to send heartbeat for.
pub session_index: SessionIndex,
@@ -202,7 +203,7 @@ impl<BlockNumber: sp_std::fmt::Debug> sp_std::fmt::Debug for OffchainErr<BlockNu
pub type AuthIndex = u32;
/// Heartbeat which is sent/received.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct Heartbeat<BlockNumber>
where
BlockNumber: PartialEq + Eq + Decode + Encode,
@@ -297,7 +298,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(T::AuthorityId = "AuthorityId", Vec<IdentificationTuple<T>> = "Vec<IdentificationTuple>")]
pub enum Event<T: Config> {
/// A new heartbeat was received from `AuthorityId` \[authority_id\]
HeartbeatReceived(T::AuthorityId),
@@ -459,7 +459,7 @@ pub mod pallet {
type Call = Call<T>;
fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
if let Call::heartbeat(heartbeat, signature) = call {
if let Call::heartbeat { heartbeat, signature } = call {
if <Pallet<T>>::is_online(heartbeat.authority_index) {
// we already received a heartbeat for this authority
return InvalidTransaction::Stale.into()
@@ -631,7 +631,7 @@ impl<T: Config> Pallet<T> {
let prepare_heartbeat = || -> OffchainResult<T, Call<T>> {
let network_state =
sp_io::offchain::network_state().map_err(|_| OffchainErr::NetworkState)?;
let heartbeat_data = Heartbeat {
let heartbeat = Heartbeat {
block_number,
network_state,
session_index,
@@ -639,9 +639,9 @@ impl<T: Config> Pallet<T> {
validators_len,
};
let signature = key.sign(&heartbeat_data.encode()).ok_or(OffchainErr::FailedSigning)?;
let signature = key.sign(&heartbeat.encode()).ok_or(OffchainErr::FailedSigning)?;
Ok(Call::heartbeat(heartbeat_data, signature))
Ok(Call::heartbeat { heartbeat, signature })
};
if Self::is_online(authority_index) {
@@ -820,7 +820,7 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
}
/// An offence that is filed if a validator didn't send a heartbeat message.
#[derive(RuntimeDebug)]
#[derive(RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Clone, PartialEq, Eq))]
pub struct UnresponsivenessOffence<Offender> {
/// The current session index in which we report the unresponsive validators.
+11 -10
View File
@@ -130,14 +130,15 @@ fn heartbeat(
};
let signature = id.sign(&heartbeat.encode()).unwrap();
ImOnline::pre_dispatch(&crate::Call::heartbeat(heartbeat.clone(), signature.clone())).map_err(
|e| match e {
TransactionValidityError::Invalid(InvalidTransaction::Custom(
INVALID_VALIDATORS_LEN,
)) => "invalid validators len",
e @ _ => <&'static str>::from(e),
},
)?;
ImOnline::pre_dispatch(&crate::Call::heartbeat {
heartbeat: heartbeat.clone(),
signature: signature.clone(),
})
.map_err(|e| match e {
TransactionValidityError::Invalid(InvalidTransaction::Custom(INVALID_VALIDATORS_LEN)) =>
"invalid validators len",
e @ _ => <&'static str>::from(e),
})?;
ImOnline::heartbeat(Origin::none(), heartbeat, signature)
}
@@ -237,7 +238,7 @@ fn should_generate_heartbeats() {
// check stuff about the transaction.
let ex: Extrinsic = Decode::decode(&mut &*transaction).unwrap();
let heartbeat = match ex.call {
crate::mock::Call::ImOnline(crate::Call::heartbeat(h, ..)) => h,
crate::mock::Call::ImOnline(crate::Call::heartbeat { heartbeat, .. }) => heartbeat,
e => panic!("Unexpected call: {:?}", e),
};
@@ -352,7 +353,7 @@ fn should_not_send_a_report_if_already_online() {
// check stuff about the transaction.
let ex: Extrinsic = Decode::decode(&mut &*transaction).unwrap();
let heartbeat = match ex.call {
crate::mock::Call::ImOnline(crate::Call::heartbeat(h, ..)) => h,
crate::mock::Call::ImOnline(crate::Call::heartbeat { heartbeat, .. }) => heartbeat,
e => panic!("Unexpected call: {:?}", e),
};
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-keyring = { version = "4.0.0-dev", optional = true, path = "../../primitives/keyring" }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" }
@@ -32,6 +33,7 @@ default = ["std"]
std = [
"sp-keyring",
"codec/std",
"scale-info/std",
"sp-core/std",
"sp-std/std",
"sp-io/std",
-1
View File
@@ -260,7 +260,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(T::AccountId = "AccountId", T::AccountIndex = "AccountIndex")]
pub enum Event<T: Config> {
/// A account index was assigned. \[index, who\]
IndexAssigned(T::AccountId, T::AccountIndex),
+2
View File
@@ -16,6 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [
"derive",
] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
@@ -33,6 +34,7 @@ sp-io = { version = "4.0.0-dev", path = "../../primitives/io" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-std/std",
"frame-support/std",
"sp-runtime/std",
+10 -10
View File
@@ -35,11 +35,11 @@ fn setup_lottery<T: Config>(repeat: bool) -> Result<(), &'static str> {
let delay = 5u32.into();
// Calls will be maximum length...
let mut calls = vec![
frame_system::Call::<T>::set_code(vec![]).into();
frame_system::Call::<T>::set_code { code: vec![] }.into();
T::MaxCalls::get().saturating_sub(1) as usize
];
// Last call will be the match for worst case scenario.
calls.push(frame_system::Call::<T>::remark(vec![]).into());
calls.push(frame_system::Call::<T>::remark { remark: vec![] }.into());
let origin = T::ManagerOrigin::successful_origin();
Lottery::<T>::set_calls(origin.clone(), calls)?;
Lottery::<T>::start_lottery(origin, price, length, delay, repeat)?;
@@ -53,7 +53,7 @@ benchmarks! {
setup_lottery::<T>(false)?;
// force user to have a long vec of calls participating
let set_code_index: CallIndex = Lottery::<T>::call_to_index(
&frame_system::Call::<T>::set_code(vec![]).into()
&frame_system::Call::<T>::set_code{ code: vec![] }.into()
)?;
let already_called: (u32, Vec<CallIndex>) = (
LotteryIndex::<T>::get(),
@@ -64,7 +64,7 @@ benchmarks! {
);
Participants::<T>::insert(&caller, already_called);
let call = frame_system::Call::<T>::remark(vec![]);
let call = frame_system::Call::<T>::remark { remark: vec![] };
}: _(RawOrigin::Signed(caller), Box::new(call.into()))
verify {
assert_eq!(TicketsCount::<T>::get(), 1);
@@ -72,9 +72,9 @@ benchmarks! {
set_calls {
let n in 0 .. T::MaxCalls::get() as u32;
let calls = vec![frame_system::Call::<T>::remark(vec![]).into(); n as usize];
let calls = vec![frame_system::Call::<T>::remark { remark: vec![] }.into(); n as usize];
let call = Call::<T>::set_calls(calls);
let call = Call::<T>::set_calls { calls };
let origin = T::ManagerOrigin::successful_origin();
assert!(CallIndices::<T>::get().is_empty());
}: { call.dispatch_bypass_filter(origin)? }
@@ -89,7 +89,7 @@ benchmarks! {
let end = 10u32.into();
let payout = 5u32.into();
let call = Call::<T>::start_lottery(price, end, payout, true);
let call = Call::<T>::start_lottery { price, length: end, delay: payout, repeat: true };
let origin = T::ManagerOrigin::successful_origin();
}: { call.dispatch_bypass_filter(origin)? }
verify {
@@ -99,7 +99,7 @@ benchmarks! {
stop_repeat {
setup_lottery::<T>(true)?;
assert_eq!(crate::Lottery::<T>::get().unwrap().repeat, true);
let call = Call::<T>::stop_repeat();
let call = Call::<T>::stop_repeat {};
let origin = T::ManagerOrigin::successful_origin();
}: { call.dispatch_bypass_filter(origin)? }
verify {
@@ -115,7 +115,7 @@ benchmarks! {
let lottery_account = Lottery::<T>::account_id();
T::Currency::make_free_balance_be(&lottery_account, T::Currency::minimum_balance() * 10u32.into());
// Buy a ticket
let call = frame_system::Call::<T>::remark(vec![]);
let call = frame_system::Call::<T>::remark { remark: vec![] };
Lottery::<T>::buy_ticket(RawOrigin::Signed(winner.clone()).into(), Box::new(call.into()))?;
// Kill user account for worst case
T::Currency::make_free_balance_be(&winner, 0u32.into());
@@ -146,7 +146,7 @@ benchmarks! {
let lottery_account = Lottery::<T>::account_id();
T::Currency::make_free_balance_be(&lottery_account, T::Currency::minimum_balance() * 10u32.into());
// Buy a ticket
let call = frame_system::Call::<T>::remark(vec![]);
let call = frame_system::Call::<T>::remark { remark: vec![] };
Lottery::<T>::buy_ticket(RawOrigin::Signed(winner.clone()).into(), Box::new(call.into()))?;
// Kill user account for worst case
T::Currency::make_free_balance_be(&winner, 0u32.into());
+1 -2
View File
@@ -76,7 +76,7 @@ type BalanceOf<T> =
// We use this to uniquely match someone's incoming call with the calls configured for the lottery.
type CallIndex = (u8, u8);
#[derive(Encode, Decode, Default, Eq, PartialEq, RuntimeDebug)]
#[derive(Encode, Decode, Default, Eq, PartialEq, RuntimeDebug, scale_info::TypeInfo)]
pub struct LotteryConfig<BlockNumber, Balance> {
/// Price per entry.
price: Balance,
@@ -170,7 +170,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(T::AccountId = "AccountId", BalanceOf<T> = "Balance")]
pub enum Event<T: Config> {
/// A lottery has been started!
LotteryStarted,
+24 -21
View File
@@ -43,8 +43,8 @@ fn basic_end_to_end_works() {
let length = 20;
let delay = 5;
let calls = vec![
Call::Balances(BalancesCall::force_transfer(0, 0, 0)),
Call::Balances(BalancesCall::transfer(0, 0)),
Call::Balances(BalancesCall::force_transfer { source: 0, dest: 0, value: 0 }),
Call::Balances(BalancesCall::transfer { dest: 0, value: 0 }),
];
// Set calls for the lottery
@@ -55,7 +55,7 @@ fn basic_end_to_end_works() {
assert!(crate::Lottery::<Test>::get().is_some());
assert_eq!(Balances::free_balance(&1), 100);
let call = Box::new(Call::Balances(BalancesCall::transfer(2, 20)));
let call = Box::new(Call::Balances(BalancesCall::transfer { dest: 2, value: 20 }));
assert_ok!(Lottery::buy_ticket(Origin::signed(1), call.clone()));
// 20 from the transfer, 10 from buying a ticket
assert_eq!(Balances::free_balance(&1), 100 - 20 - 10);
@@ -96,17 +96,17 @@ fn set_calls_works() {
assert!(!CallIndices::<Test>::exists());
let calls = vec![
Call::Balances(BalancesCall::force_transfer(0, 0, 0)),
Call::Balances(BalancesCall::transfer(0, 0)),
Call::Balances(BalancesCall::force_transfer { source: 0, dest: 0, value: 0 }),
Call::Balances(BalancesCall::transfer { dest: 0, value: 0 }),
];
assert_ok!(Lottery::set_calls(Origin::root(), calls));
assert!(CallIndices::<Test>::exists());
let too_many_calls = vec![
Call::Balances(BalancesCall::force_transfer(0, 0, 0)),
Call::Balances(BalancesCall::transfer(0, 0)),
Call::System(SystemCall::remark(vec![])),
Call::Balances(BalancesCall::force_transfer { source: 0, dest: 0, value: 0 }),
Call::Balances(BalancesCall::transfer { dest: 0, value: 0 }),
Call::System(SystemCall::remark { remark: vec![] }),
];
assert_noop!(
@@ -150,7 +150,7 @@ fn buy_ticket_works_as_simple_passthrough() {
// as a simple passthrough to the real call.
new_test_ext().execute_with(|| {
// No lottery set up
let call = Box::new(Call::Balances(BalancesCall::transfer(2, 20)));
let call = Box::new(Call::Balances(BalancesCall::transfer { dest: 2, value: 20 }));
// This is just a basic transfer then
assert_ok!(Lottery::buy_ticket(Origin::signed(1), call.clone()));
assert_eq!(Balances::free_balance(&1), 100 - 20);
@@ -158,8 +158,8 @@ fn buy_ticket_works_as_simple_passthrough() {
// Lottery is set up, but too expensive to enter, so `do_buy_ticket` fails.
let calls = vec![
Call::Balances(BalancesCall::force_transfer(0, 0, 0)),
Call::Balances(BalancesCall::transfer(0, 0)),
Call::Balances(BalancesCall::force_transfer { source: 0, dest: 0, value: 0 }),
Call::Balances(BalancesCall::transfer { dest: 0, value: 0 }),
];
assert_ok!(Lottery::set_calls(Origin::root(), calls));
@@ -170,21 +170,24 @@ fn buy_ticket_works_as_simple_passthrough() {
assert_eq!(TicketsCount::<Test>::get(), 0);
// If call would fail, the whole thing still fails the same
let fail_call = Box::new(Call::Balances(BalancesCall::transfer(2, 1000)));
let fail_call = Box::new(Call::Balances(BalancesCall::transfer { dest: 2, value: 1000 }));
assert_noop!(
Lottery::buy_ticket(Origin::signed(1), fail_call),
BalancesError::<Test, _>::InsufficientBalance,
);
let bad_origin_call = Box::new(Call::Balances(BalancesCall::force_transfer(0, 0, 0)));
assert_noop!(Lottery::buy_ticket(Origin::signed(1), bad_origin_call), BadOrigin);
let bad_origin_call =
Box::new(Call::Balances(BalancesCall::force_transfer { source: 0, dest: 0, value: 0 }));
assert_noop!(Lottery::buy_ticket(Origin::signed(1), bad_origin_call), BadOrigin,);
// User can call other txs, but doesn't get a ticket
let remark_call = Box::new(Call::System(SystemCall::remark(b"hello, world!".to_vec())));
let remark_call =
Box::new(Call::System(SystemCall::remark { remark: b"hello, world!".to_vec() }));
assert_ok!(Lottery::buy_ticket(Origin::signed(2), remark_call));
assert_eq!(TicketsCount::<Test>::get(), 0);
let successful_call = Box::new(Call::Balances(BalancesCall::transfer(2, 1)));
let successful_call =
Box::new(Call::Balances(BalancesCall::transfer { dest: 2, value: 1 }));
assert_ok!(Lottery::buy_ticket(Origin::signed(2), successful_call));
assert_eq!(TicketsCount::<Test>::get(), 1);
});
@@ -195,13 +198,13 @@ fn buy_ticket_works() {
new_test_ext().execute_with(|| {
// Set calls for the lottery.
let calls = vec![
Call::System(SystemCall::remark(vec![])),
Call::Balances(BalancesCall::transfer(0, 0)),
Call::System(SystemCall::remark { remark: vec![] }),
Call::Balances(BalancesCall::transfer { dest: 0, value: 0 }),
];
assert_ok!(Lottery::set_calls(Origin::root(), calls));
// Can't buy ticket before start
let call = Box::new(Call::Balances(BalancesCall::transfer(2, 1)));
let call = Box::new(Call::Balances(BalancesCall::transfer { dest: 2, value: 1 }));
assert_ok!(Lottery::buy_ticket(Origin::signed(1), call.clone()));
assert_eq!(TicketsCount::<Test>::get(), 0);
@@ -214,12 +217,12 @@ fn buy_ticket_works() {
assert_eq!(TicketsCount::<Test>::get(), 1);
// Can't buy another of the same ticket (even if call is slightly changed)
let call = Box::new(Call::Balances(BalancesCall::transfer(3, 30)));
let call = Box::new(Call::Balances(BalancesCall::transfer { dest: 3, value: 30 }));
assert_ok!(Lottery::buy_ticket(Origin::signed(1), call));
assert_eq!(TicketsCount::<Test>::get(), 1);
// Buy ticket for remark
let call = Box::new(Call::System(SystemCall::remark(b"hello, world!".to_vec())));
let call = Box::new(Call::System(SystemCall::remark { remark: b"hello, world!".to_vec() }));
assert_ok!(Lottery::buy_ticket(Origin::signed(1), call.clone()));
assert_eq!(TicketsCount::<Test>::get(), 2);
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
log = { version = "0.4.0", default-features = false }
sp-core = { version = "4.0.0-dev", default-features = false, path = "../../primitives/core" }
@@ -29,6 +30,7 @@ frame-system = { version = "4.0.0-dev", default-features = false, path = "../sys
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"log/std",
"sp-core/std",
"sp-io/std",
-3
View File
@@ -131,9 +131,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(
PhantomData<(T::AccountId, <T as Config<I>>::Event)> = "sp_std::marker::PhantomData<(AccountId, Event)>",
)]
pub enum Event<T: Config<I>, I: 'static = ()> {
/// The given member was added; see the transaction for who.
MemberAdded,
@@ -13,6 +13,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
mmr-lib = { package = "ckb-merkle-mountain-range", default-features = false, version = "0.3.1" }
sp-core = { version = "4.0.0-dev", default-features = false, path = "../../primitives/core" }
@@ -34,6 +35,7 @@ hex-literal = "0.3"
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"mmr-lib/std",
"sp-core/std",
"sp-io/std",
@@ -124,7 +124,8 @@ pub mod pallet {
+ Copy
+ Default
+ codec::Codec
+ codec::EncodeLike;
+ codec::EncodeLike
+ scale_info::TypeInfo;
/// Data stored in the leaf nodes.
///
-28
View File
@@ -1,28 +0,0 @@
[package]
name = "frame-metadata"
version = "14.0.0-dev"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "Apache-2.0"
homepage = "https://substrate.dev"
repository = "https://github.com/paritytech/substrate/"
description = "Decodable variant of the RuntimeMetadata."
readme = "README.md"
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
serde = { version = "1.0.126", optional = true, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-core = { version = "4.0.0-dev", default-features = false, path = "../../primitives/core" }
[features]
default = ["std"]
std = [
"codec/std",
"sp-std/std",
"sp-core/std",
"serde",
]
-7
View File
@@ -1,7 +0,0 @@
Decodable variant of the RuntimeMetadata.
This really doesn't belong here, but is necessary for the moment. In the future
it should be removed entirely to an external module for shimming on to the
codec-encoded metadata.
License: Apache-2.0
-466
View File
@@ -1,466 +0,0 @@
// This file is part of Substrate.
// Copyright (C) 2018-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Decodable variant of the RuntimeMetadata.
//!
//! This really doesn't belong here, but is necessary for the moment. In the future
//! it should be removed entirely to an external module for shimming on to the
//! codec-encoded metadata.
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
use codec::{Decode, Error, Input};
use codec::{Encode, Output};
#[cfg(feature = "std")]
use serde::Serialize;
use sp_core::RuntimeDebug;
use sp_std::vec::Vec;
#[cfg(feature = "std")]
type StringBuf = String;
/// Current prefix of metadata
pub const META_RESERVED: u32 = 0x6174656d; // 'meta' warn endianness
/// On `no_std` we do not support `Decode` and thus `StringBuf` is just `&'static str`.
/// So, if someone tries to decode this stuff on `no_std`, they will get a compilation error.
#[cfg(not(feature = "std"))]
type StringBuf = &'static str;
/// A type that decodes to a different type than it encodes.
/// The user needs to make sure that both types use the same encoding.
///
/// For example a `&'static [ &'static str ]` can be decoded to a `Vec<String>`.
#[derive(Clone)]
pub enum DecodeDifferent<B, O>
where
B: 'static,
O: 'static,
{
Encode(B),
Decoded(O),
}
impl<B, O> Encode for DecodeDifferent<B, O>
where
B: Encode + 'static,
O: Encode + 'static,
{
fn encode_to<W: Output + ?Sized>(&self, dest: &mut W) {
match self {
DecodeDifferent::Encode(b) => b.encode_to(dest),
DecodeDifferent::Decoded(o) => o.encode_to(dest),
}
}
}
impl<B, O> codec::EncodeLike for DecodeDifferent<B, O>
where
B: Encode + 'static,
O: Encode + 'static,
{
}
#[cfg(feature = "std")]
impl<B, O> Decode for DecodeDifferent<B, O>
where
B: 'static,
O: Decode + 'static,
{
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
<O>::decode(input).map(|val| DecodeDifferent::Decoded(val))
}
}
impl<B, O> PartialEq for DecodeDifferent<B, O>
where
B: Encode + Eq + PartialEq + 'static,
O: Encode + Eq + PartialEq + 'static,
{
fn eq(&self, other: &Self) -> bool {
self.encode() == other.encode()
}
}
impl<B, O> Eq for DecodeDifferent<B, O>
where
B: Encode + Eq + PartialEq + 'static,
O: Encode + Eq + PartialEq + 'static,
{
}
impl<B, O> sp_std::fmt::Debug for DecodeDifferent<B, O>
where
B: sp_std::fmt::Debug + Eq + 'static,
O: sp_std::fmt::Debug + Eq + 'static,
{
fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
match self {
DecodeDifferent::Encode(b) => b.fmt(f),
DecodeDifferent::Decoded(o) => o.fmt(f),
}
}
}
#[cfg(feature = "std")]
impl<B, O> serde::Serialize for DecodeDifferent<B, O>
where
B: serde::Serialize + 'static,
O: serde::Serialize + 'static,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
DecodeDifferent::Encode(b) => b.serialize(serializer),
DecodeDifferent::Decoded(o) => o.serialize(serializer),
}
}
}
pub type DecodeDifferentArray<B, O = B> = DecodeDifferent<&'static [B], Vec<O>>;
type DecodeDifferentStr = DecodeDifferent<&'static str, StringBuf>;
/// All the metadata about a function.
#[derive(Clone, PartialEq, Eq, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub struct FunctionMetadata {
pub name: DecodeDifferentStr,
pub arguments: DecodeDifferentArray<FunctionArgumentMetadata>,
pub documentation: DecodeDifferentArray<&'static str, StringBuf>,
}
/// All the metadata about a function argument.
#[derive(Clone, PartialEq, Eq, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub struct FunctionArgumentMetadata {
pub name: DecodeDifferentStr,
pub ty: DecodeDifferentStr,
}
/// Newtype wrapper for support encoding functions (actual the result of the function).
#[derive(Clone, Eq)]
pub struct FnEncode<E>(pub fn() -> E)
where
E: Encode + 'static;
impl<E: Encode> Encode for FnEncode<E> {
fn encode_to<W: Output + ?Sized>(&self, dest: &mut W) {
self.0().encode_to(dest);
}
}
impl<E: Encode> codec::EncodeLike for FnEncode<E> {}
impl<E: Encode + PartialEq> PartialEq for FnEncode<E> {
fn eq(&self, other: &Self) -> bool {
self.0().eq(&other.0())
}
}
impl<E: Encode + sp_std::fmt::Debug> sp_std::fmt::Debug for FnEncode<E> {
fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
self.0().fmt(f)
}
}
#[cfg(feature = "std")]
impl<E: Encode + serde::Serialize> serde::Serialize for FnEncode<E> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0().serialize(serializer)
}
}
/// All the metadata about an outer event.
#[derive(Clone, PartialEq, Eq, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub struct OuterEventMetadata {
pub name: DecodeDifferentStr,
pub events: DecodeDifferentArray<
(&'static str, FnEncode<&'static [EventMetadata]>),
(StringBuf, Vec<EventMetadata>),
>,
}
/// All the metadata about an event.
#[derive(Clone, PartialEq, Eq, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub struct EventMetadata {
pub name: DecodeDifferentStr,
pub arguments: DecodeDifferentArray<&'static str, StringBuf>,
pub documentation: DecodeDifferentArray<&'static str, StringBuf>,
}
/// All the metadata about one storage entry.
#[derive(Clone, PartialEq, Eq, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub struct StorageEntryMetadata {
pub name: DecodeDifferentStr,
pub modifier: StorageEntryModifier,
pub ty: StorageEntryType,
pub default: ByteGetter,
pub documentation: DecodeDifferentArray<&'static str, StringBuf>,
}
/// All the metadata about one module constant.
#[derive(Clone, PartialEq, Eq, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub struct ModuleConstantMetadata {
pub name: DecodeDifferentStr,
pub ty: DecodeDifferentStr,
pub value: ByteGetter,
pub documentation: DecodeDifferentArray<&'static str, StringBuf>,
}
/// All the metadata about a module error.
#[derive(Clone, PartialEq, Eq, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub struct ErrorMetadata {
pub name: DecodeDifferentStr,
pub documentation: DecodeDifferentArray<&'static str, StringBuf>,
}
/// All the metadata about errors in a module.
pub trait ModuleErrorMetadata {
fn metadata() -> &'static [ErrorMetadata];
}
impl ModuleErrorMetadata for &'static str {
fn metadata() -> &'static [ErrorMetadata] {
&[]
}
}
/// A technical trait to store lazy initiated vec value as static dyn pointer.
pub trait DefaultByte: Send + Sync {
fn default_byte(&self) -> Vec<u8>;
}
/// Wrapper over dyn pointer for accessing a cached once byte value.
#[derive(Clone)]
pub struct DefaultByteGetter(pub &'static dyn DefaultByte);
/// Decode different for static lazy initiated byte value.
pub type ByteGetter = DecodeDifferent<DefaultByteGetter, Vec<u8>>;
impl Encode for DefaultByteGetter {
fn encode_to<W: Output + ?Sized>(&self, dest: &mut W) {
self.0.default_byte().encode_to(dest)
}
}
impl codec::EncodeLike for DefaultByteGetter {}
impl PartialEq<DefaultByteGetter> for DefaultByteGetter {
fn eq(&self, other: &DefaultByteGetter) -> bool {
let left = self.0.default_byte();
let right = other.0.default_byte();
left.eq(&right)
}
}
impl Eq for DefaultByteGetter {}
#[cfg(feature = "std")]
impl serde::Serialize for DefaultByteGetter {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.default_byte().serialize(serializer)
}
}
impl sp_std::fmt::Debug for DefaultByteGetter {
fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
self.0.default_byte().fmt(f)
}
}
/// Hasher used by storage maps
#[derive(Clone, PartialEq, Eq, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub enum StorageHasher {
Blake2_128,
Blake2_256,
Blake2_128Concat,
Twox128,
Twox256,
Twox64Concat,
Identity,
}
/// A storage entry type.
#[derive(Clone, PartialEq, Eq, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub enum StorageEntryType {
Plain(DecodeDifferentStr),
Map {
hasher: StorageHasher,
key: DecodeDifferentStr,
value: DecodeDifferentStr,
// is_linked flag previously, unused now to keep backwards compat
unused: bool,
},
DoubleMap {
hasher: StorageHasher,
key1: DecodeDifferentStr,
key2: DecodeDifferentStr,
value: DecodeDifferentStr,
key2_hasher: StorageHasher,
},
NMap {
keys: DecodeDifferentArray<&'static str, StringBuf>,
hashers: DecodeDifferentArray<StorageHasher>,
value: DecodeDifferentStr,
},
}
/// A storage entry modifier.
#[derive(Clone, PartialEq, Eq, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub enum StorageEntryModifier {
Optional,
Default,
}
/// All metadata of the storage.
#[derive(Clone, PartialEq, Eq, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub struct StorageMetadata {
/// The common prefix used by all storage entries.
pub prefix: DecodeDifferent<&'static str, StringBuf>,
pub entries: DecodeDifferent<&'static [StorageEntryMetadata], Vec<StorageEntryMetadata>>,
}
/// Metadata prefixed by a u32 for reserved usage
#[derive(Eq, Encode, PartialEq, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub struct RuntimeMetadataPrefixed(pub u32, pub RuntimeMetadata);
/// Metadata of the extrinsic used by the runtime.
#[derive(Eq, Encode, PartialEq, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub struct ExtrinsicMetadata {
/// Extrinsic version.
pub version: u8,
/// The signed extensions in the order they appear in the extrinsic.
pub signed_extensions: Vec<DecodeDifferentStr>,
}
/// The metadata of a runtime.
/// The version ID encoded/decoded through
/// the enum nature of `RuntimeMetadata`.
#[derive(Eq, Encode, PartialEq, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub enum RuntimeMetadata {
/// Unused; enum filler.
V0(RuntimeMetadataDeprecated),
/// Version 1 for runtime metadata. No longer used.
V1(RuntimeMetadataDeprecated),
/// Version 2 for runtime metadata. No longer used.
V2(RuntimeMetadataDeprecated),
/// Version 3 for runtime metadata. No longer used.
V3(RuntimeMetadataDeprecated),
/// Version 4 for runtime metadata. No longer used.
V4(RuntimeMetadataDeprecated),
/// Version 5 for runtime metadata. No longer used.
V5(RuntimeMetadataDeprecated),
/// Version 6 for runtime metadata. No longer used.
V6(RuntimeMetadataDeprecated),
/// Version 7 for runtime metadata. No longer used.
V7(RuntimeMetadataDeprecated),
/// Version 8 for runtime metadata. No longer used.
V8(RuntimeMetadataDeprecated),
/// Version 9 for runtime metadata. No longer used.
V9(RuntimeMetadataDeprecated),
/// Version 10 for runtime metadata. No longer used.
V10(RuntimeMetadataDeprecated),
/// Version 11 for runtime metadata. No longer used.
V11(RuntimeMetadataDeprecated),
/// Version 12 for runtime metadata. No longer used.
V12(RuntimeMetadataDeprecated),
/// Version 13 for runtime metadata.
V13(RuntimeMetadataV13),
}
/// Enum that should fail.
#[derive(Eq, PartialEq, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize))]
pub enum RuntimeMetadataDeprecated {}
impl Encode for RuntimeMetadataDeprecated {
fn encode_to<W: Output + ?Sized>(&self, _dest: &mut W) {}
}
impl codec::EncodeLike for RuntimeMetadataDeprecated {}
#[cfg(feature = "std")]
impl Decode for RuntimeMetadataDeprecated {
fn decode<I: Input>(_input: &mut I) -> Result<Self, Error> {
Err("Decoding is not supported".into())
}
}
/// The metadata of a runtime.
#[derive(Eq, Encode, PartialEq, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub struct RuntimeMetadataV13 {
/// Metadata of all the modules.
pub modules: DecodeDifferentArray<ModuleMetadata>,
/// Metadata of the extrinsic.
pub extrinsic: ExtrinsicMetadata,
}
/// The latest version of the metadata.
pub type RuntimeMetadataLastVersion = RuntimeMetadataV13;
/// All metadata about an runtime module.
#[derive(Clone, PartialEq, Eq, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode, Serialize))]
pub struct ModuleMetadata {
pub name: DecodeDifferentStr,
pub storage: Option<DecodeDifferent<FnEncode<StorageMetadata>, StorageMetadata>>,
pub calls: ODFnA<FunctionMetadata>,
pub event: ODFnA<EventMetadata>,
pub constants: DFnA<ModuleConstantMetadata>,
pub errors: DFnA<ErrorMetadata>,
/// Define the index of the module, this index will be used for the encoding of module event,
/// call and origin variants.
pub index: u8,
}
type ODFnA<T> = Option<DFnA<T>>;
type DFnA<T> = DecodeDifferent<FnEncode<&'static [T]>, Vec<T>>;
impl Into<sp_core::OpaqueMetadata> for RuntimeMetadataPrefixed {
fn into(self) -> sp_core::OpaqueMetadata {
sp_core::OpaqueMetadata::new(self.encode())
}
}
impl Into<RuntimeMetadataPrefixed> for RuntimeMetadataLastVersion {
fn into(self) -> RuntimeMetadataPrefixed {
RuntimeMetadataPrefixed(META_RESERVED, RuntimeMetadata::V13(self))
}
}
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
@@ -30,6 +31,7 @@ pallet-balances = { version = "4.0.0-dev", path = "../balances" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-runtime/std",
"frame-support/std",
"frame-system/std",
+5 -2
View File
@@ -40,7 +40,8 @@ fn setup_multi<T: Config>(s: u32, z: u32) -> Result<(Vec<T::AccountId>, Vec<u8>)
}
signatories.sort();
// Must first convert to outer call type.
let call: <T as Config>::Call = frame_system::Call::<T>::remark(vec![0; z as usize]).into();
let call: <T as Config>::Call =
frame_system::Call::<T>::remark { remark: vec![0; z as usize] }.into();
let call_data = call.encode();
return Ok((signatories, call_data))
}
@@ -51,7 +52,9 @@ benchmarks! {
let z in 0 .. 10_000;
let max_signatories = T::MaxSignatories::get().into();
let (mut signatories, _) = setup_multi::<T>(max_signatories, z)?;
let call: <T as Config>::Call = frame_system::Call::<T>::remark(vec![0; z as usize]).into();
let call: <T as Config>::Call = frame_system::Call::<T>::remark {
remark: vec![0; z as usize]
}.into();
let call_hash = call.using_encoded(blake2_256);
let multi_account_id = Multisig::<T>::multi_account_id(&signatories, 1);
let caller = signatories.pop().ok_or("signatories should have len 2 or more")?;
+3 -7
View File
@@ -61,6 +61,7 @@ use frame_support::{
RuntimeDebug,
};
use frame_system::{self as system, RawOrigin};
use scale_info::TypeInfo;
use sp_io::hashing::blake2_256;
use sp_runtime::{
traits::{Dispatchable, Zero},
@@ -79,7 +80,7 @@ pub type OpaqueCall = Vec<u8>;
/// A global extrinsic index, formed as the extrinsic index within a block, together with that
/// block's height. This allows a transaction in which a multisig operation of a particular
/// composite was created to be uniquely identified.
#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, Default, RuntimeDebug)]
#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, Default, RuntimeDebug, TypeInfo)]
pub struct Timepoint<BlockNumber> {
/// The height of the chain at the point in time.
height: BlockNumber,
@@ -88,7 +89,7 @@ pub struct Timepoint<BlockNumber> {
}
/// An open multisig operation.
#[derive(Clone, Eq, PartialEq, Encode, Decode, Default, RuntimeDebug)]
#[derive(Clone, Eq, PartialEq, Encode, Decode, Default, RuntimeDebug, TypeInfo)]
pub struct Multisig<BlockNumber, Balance, AccountId> {
/// The extrinsic when the multisig operation was opened.
when: Timepoint<BlockNumber>,
@@ -203,11 +204,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(
T::AccountId = "AccountId",
T::BlockNumber = "BlockNumber",
Timepoint<T::BlockNumber> = "Timepoint<BlockNumber>"
)]
pub enum Event<T: Config> {
/// A new multisig operation has begun. \[approving, multisig, call_hash\]
NewMultisig(T::AccountId, T::AccountId, CallHash),
+28 -24
View File
@@ -99,7 +99,7 @@ impl Contains<Call> for TestBaseCallFilter {
match *c {
Call::Balances(_) => true,
// Needed for benchmarking
Call::System(frame_system::Call::remark(_)) => true,
Call::System(frame_system::Call::remark { .. }) => true,
_ => false,
}
}
@@ -132,6 +132,10 @@ fn now() -> Timepoint<u64> {
Multisig::timepoint()
}
fn call_transfer(dest: u64, value: u64) -> Call {
Call::Balances(BalancesCall::transfer { dest, value })
}
#[test]
fn multisig_deposit_is_taken_and_returned() {
new_test_ext().execute_with(|| {
@@ -140,7 +144,7 @@ fn multisig_deposit_is_taken_and_returned() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Call::Balances(BalancesCall::transfer(6, 15));
let call = call_transfer(6, 15);
let call_weight = call.get_dispatch_info().weight;
let data = call.encode();
assert_ok!(Multisig::as_multi(
@@ -177,7 +181,7 @@ fn multisig_deposit_is_taken_and_returned_with_call_storage() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Call::Balances(BalancesCall::transfer(6, 15));
let call = call_transfer(6, 15);
let call_weight = call.get_dispatch_info().weight;
let data = call.encode();
let hash = blake2_256(&data);
@@ -206,7 +210,7 @@ fn multisig_deposit_is_taken_and_returned_with_alt_call_storage() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Call::Balances(BalancesCall::transfer(6, 15));
let call = call_transfer(6, 15);
let call_weight = call.get_dispatch_info().weight;
let data = call.encode();
let hash = blake2_256(&data);
@@ -254,7 +258,7 @@ fn multisig_deposit_is_taken_and_returned_with_alt_call_storage() {
#[test]
fn cancel_multisig_returns_deposit() {
new_test_ext().execute_with(|| {
let call = Call::Balances(BalancesCall::transfer(6, 15)).encode();
let call = call_transfer(6, 15).encode();
let hash = blake2_256(&call);
assert_ok!(Multisig::approve_as_multi(
Origin::signed(1),
@@ -294,7 +298,7 @@ fn timepoint_checking_works() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Call::Balances(BalancesCall::transfer(6, 15)).encode();
let call = call_transfer(6, 15).encode();
let hash = blake2_256(&call);
assert_noop!(
@@ -339,7 +343,7 @@ fn multisig_2_of_3_works_with_call_storing() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Call::Balances(BalancesCall::transfer(6, 15));
let call = call_transfer(6, 15);
let call_weight = call.get_dispatch_info().weight;
let data = call.encode();
let hash = blake2_256(&data);
@@ -366,7 +370,7 @@ fn multisig_2_of_3_works() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Call::Balances(BalancesCall::transfer(6, 15));
let call = call_transfer(6, 15);
let call_weight = call.get_dispatch_info().weight;
let data = call.encode();
let hash = blake2_256(&data);
@@ -394,7 +398,7 @@ fn multisig_3_of_3_works() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Call::Balances(BalancesCall::transfer(6, 15));
let call = call_transfer(6, 15);
let call_weight = call.get_dispatch_info().weight;
let data = call.encode();
let hash = blake2_256(&data);
@@ -432,7 +436,7 @@ fn multisig_3_of_3_works() {
#[test]
fn cancel_multisig_works() {
new_test_ext().execute_with(|| {
let call = Call::Balances(BalancesCall::transfer(6, 15)).encode();
let call = call_transfer(6, 15).encode();
let hash = blake2_256(&call);
assert_ok!(Multisig::approve_as_multi(
Origin::signed(1),
@@ -467,7 +471,7 @@ fn cancel_multisig_works() {
#[test]
fn cancel_multisig_with_call_storage_works() {
new_test_ext().execute_with(|| {
let call = Call::Balances(BalancesCall::transfer(6, 15)).encode();
let call = call_transfer(6, 15).encode();
let hash = blake2_256(&call);
assert_ok!(Multisig::as_multi(Origin::signed(1), 3, vec![2, 3], None, call, true, 0));
assert_eq!(Balances::free_balance(1), 4);
@@ -497,7 +501,7 @@ fn cancel_multisig_with_call_storage_works() {
#[test]
fn cancel_multisig_with_alt_call_storage_works() {
new_test_ext().execute_with(|| {
let call = Call::Balances(BalancesCall::transfer(6, 15)).encode();
let call = call_transfer(6, 15).encode();
let hash = blake2_256(&call);
assert_ok!(Multisig::approve_as_multi(
Origin::signed(1),
@@ -532,7 +536,7 @@ fn multisig_2_of_3_as_multi_works() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Call::Balances(BalancesCall::transfer(6, 15));
let call = call_transfer(6, 15);
let call_weight = call.get_dispatch_info().weight;
let data = call.encode();
assert_ok!(Multisig::as_multi(
@@ -567,10 +571,10 @@ fn multisig_2_of_3_as_multi_with_many_calls_works() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call1 = Call::Balances(BalancesCall::transfer(6, 10));
let call1 = call_transfer(6, 10);
let call1_weight = call1.get_dispatch_info().weight;
let data1 = call1.encode();
let call2 = Call::Balances(BalancesCall::transfer(7, 5));
let call2 = call_transfer(7, 5);
let call2_weight = call2.get_dispatch_info().weight;
let data2 = call2.encode();
@@ -624,7 +628,7 @@ fn multisig_2_of_3_cannot_reissue_same_call() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Call::Balances(BalancesCall::transfer(6, 10));
let call = call_transfer(6, 10);
let call_weight = call.get_dispatch_info().weight;
let data = call.encode();
let hash = blake2_256(&data);
@@ -677,7 +681,7 @@ fn multisig_2_of_3_cannot_reissue_same_call() {
#[test]
fn minimum_threshold_check_works() {
new_test_ext().execute_with(|| {
let call = Call::Balances(BalancesCall::transfer(6, 15)).encode();
let call = call_transfer(6, 15).encode();
assert_noop!(
Multisig::as_multi(Origin::signed(1), 0, vec![2], None, call.clone(), false, 0),
Error::<Test>::MinimumThreshold,
@@ -692,7 +696,7 @@ fn minimum_threshold_check_works() {
#[test]
fn too_many_signatories_fails() {
new_test_ext().execute_with(|| {
let call = Call::Balances(BalancesCall::transfer(6, 15)).encode();
let call = call_transfer(6, 15).encode();
assert_noop!(
Multisig::as_multi(Origin::signed(1), 2, vec![2, 3, 4], None, call.clone(), false, 0),
Error::<Test>::TooManySignatories,
@@ -703,7 +707,7 @@ fn too_many_signatories_fails() {
#[test]
fn duplicate_approvals_are_ignored() {
new_test_ext().execute_with(|| {
let call = Call::Balances(BalancesCall::transfer(6, 15)).encode();
let call = call_transfer(6, 15).encode();
let hash = blake2_256(&call);
assert_ok!(Multisig::approve_as_multi(
Origin::signed(1),
@@ -754,7 +758,7 @@ fn multisig_1_of_3_works() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Call::Balances(BalancesCall::transfer(6, 15)).encode();
let call = call_transfer(6, 15).encode();
let hash = blake2_256(&call);
assert_noop!(
Multisig::approve_as_multi(Origin::signed(1), 1, vec![2, 3], None, hash.clone(), 0),
@@ -764,7 +768,7 @@ fn multisig_1_of_3_works() {
Multisig::as_multi(Origin::signed(1), 1, vec![2, 3], None, call.clone(), false, 0),
Error::<Test>::MinimumThreshold,
);
let boxed_call = Box::new(Call::Balances(BalancesCall::transfer(6, 15)));
let boxed_call = Box::new(call_transfer(6, 15));
assert_ok!(Multisig::as_multi_threshold_1(Origin::signed(1), vec![2, 3], boxed_call));
assert_eq!(Balances::free_balance(6), 15);
@@ -774,7 +778,7 @@ fn multisig_1_of_3_works() {
#[test]
fn multisig_filters() {
new_test_ext().execute_with(|| {
let call = Box::new(Call::System(frame_system::Call::set_code(vec![])));
let call = Box::new(Call::System(frame_system::Call::set_code { code: vec![] }));
assert_noop!(
Multisig::as_multi_threshold_1(Origin::signed(1), vec![2], call.clone()),
DispatchError::BadOrigin,
@@ -790,7 +794,7 @@ fn weight_check_works() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Call::Balances(BalancesCall::transfer(6, 15));
let call = call_transfer(6, 15);
let data = call.encode();
assert_ok!(Multisig::as_multi(
Origin::signed(1),
@@ -821,7 +825,7 @@ fn multisig_handles_no_preimage_after_all_approve() {
assert_ok!(Balances::transfer(Origin::signed(2), multi, 5));
assert_ok!(Balances::transfer(Origin::signed(3), multi, 5));
let call = Call::Balances(BalancesCall::transfer(6, 15));
let call = call_transfer(6, 15);
let call_weight = call.get_dispatch_info().weight;
let data = call.encode();
let hash = blake2_256(&data);
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
@@ -28,6 +29,7 @@ pallet-balances = { version = "4.0.0-dev", path = "../balances" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-std/std",
"sp-io/std",
"sp-runtime/std",
-1
View File
@@ -91,7 +91,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(T::AccountId = "AccountId", BalanceOf<T> = "Balance")]
pub enum Event<T: Config> {
/// A name was set. \[who\]
NameSet(T::AccountId),
@@ -13,6 +13,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }
sp-core = { version = "4.0.0-dev", default-features = false, path = "../../primitives/core" }
@@ -25,6 +26,7 @@ log = { version = "0.4.14", default-features = false }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"frame-support/std",
"frame-system/std",
"sp-core/std",
@@ -126,7 +126,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(T::AccountId = "AccountId")]
pub enum Event<T: Config> {
/// The given well known node was added.
NodeAdded(PeerId, T::AccountId),
+2
View File
@@ -15,6 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
pallet-balances = { version = "4.0.0-dev", default-features = false, path = "../balances" }
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" }
serde = { version = "1.0.126", optional = true }
sp-runtime = { version = "4.0.0-dev", default-features = false, path = "../../primitives/runtime" }
@@ -32,6 +33,7 @@ default = ["std"]
std = [
"pallet-balances/std",
"codec/std",
"scale-info/std",
"sp-std/std",
"serde",
"sp-runtime/std",
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../../benchmarking" }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../../system" }
@@ -57,4 +58,5 @@ std = [
"frame-election-provider-support/std",
"sp-std/std",
"codec/std",
"scale-info/std",
]
+2
View File
@@ -14,6 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "2.2.0", default-features = false, features = ["max-encoded-len"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }
sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" }
@@ -31,6 +32,7 @@ pallet-utility = { version = "4.0.0-dev", path = "../utility" }
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"sp-runtime/std",
"frame-support/std",
"frame-system/std",
+5 -5
View File
@@ -83,7 +83,7 @@ benchmarks! {
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());
// ... and "real" is the traditional caller. This is not a typo.
let real: T::AccountId = whitelisted_caller();
let call: <T as Config>::Call = frame_system::Call::<T>::remark(vec![]).into();
let call: <T as Config>::Call = frame_system::Call::<T>::remark { remark: vec![] }.into();
}: _(RawOrigin::Signed(caller), real, Some(T::ProxyType::default()), Box::new(call))
verify {
assert_last_event::<T>(Event::ProxyExecuted(Ok(())).into())
@@ -98,7 +98,7 @@ benchmarks! {
T::Currency::make_free_balance_be(&delegate, BalanceOf::<T>::max_value());
// ... and "real" is the traditional caller. This is not a typo.
let real: T::AccountId = whitelisted_caller();
let call: <T as Config>::Call = frame_system::Call::<T>::remark(vec![]).into();
let call: <T as Config>::Call = frame_system::Call::<T>::remark { remark: vec![] }.into();
Proxy::<T>::announce(
RawOrigin::Signed(delegate.clone()).into(),
real.clone(),
@@ -118,7 +118,7 @@ benchmarks! {
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());
// ... and "real" is the traditional caller. This is not a typo.
let real: T::AccountId = whitelisted_caller();
let call: <T as Config>::Call = frame_system::Call::<T>::remark(vec![]).into();
let call: <T as Config>::Call = frame_system::Call::<T>::remark { remark: vec![] }.into();
Proxy::<T>::announce(
RawOrigin::Signed(caller.clone()).into(),
real.clone(),
@@ -139,7 +139,7 @@ benchmarks! {
T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value());
// ... and "real" is the traditional caller. This is not a typo.
let real: T::AccountId = whitelisted_caller();
let call: <T as Config>::Call = frame_system::Call::<T>::remark(vec![]).into();
let call: <T as Config>::Call = frame_system::Call::<T>::remark { remark: vec![] }.into();
Proxy::<T>::announce(
RawOrigin::Signed(caller.clone()).into(),
real.clone(),
@@ -161,7 +161,7 @@ benchmarks! {
// ... and "real" is the traditional caller. This is not a typo.
let real: T::AccountId = whitelisted_caller();
add_announcements::<T>(a, Some(caller.clone()), None)?;
let call: <T as Config>::Call = frame_system::Call::<T>::remark(vec![]).into();
let call: <T as Config>::Call = frame_system::Call::<T>::remark { remark: vec![] }.into();
let call_hash = T::CallHasher::hash_of(&call);
}: _(RawOrigin::Signed(caller.clone()), real.clone(), call_hash)
verify {

Some files were not shown because too many files have changed in this diff Show More