From 0701fb047d512eb978e8d750f73e8ec6205f1dcf Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Tue, 6 Apr 2021 12:53:34 +0200 Subject: [PATCH 01/56] outline --- Cargo.lock | 33 +++--- Cargo.toml | 2 +- .../{template => simple-staking}/Cargo.toml | 11 +- .../{template => simple-staking}/README.md | 0 .../src/benchmarking.rs | 4 +- .../{template => simple-staking}/src/lib.rs | 107 +++++++++++------- .../{template => simple-staking}/src/mock.rs | 6 +- pallets/simple-staking/src/tests.rs | 15 +++ pallets/template/src/tests.rs | 23 ---- runtime/statemine/Cargo.toml | 10 +- runtime/statemint/Cargo.toml | 10 +- 11 files changed, 124 insertions(+), 97 deletions(-) rename pallets/{template => simple-staking}/Cargo.toml (86%) rename pallets/{template => simple-staking}/README.md (100%) rename pallets/{template => simple-staking}/src/benchmarking.rs (75%) rename pallets/{template => simple-staking}/src/lib.rs (51%) rename pallets/{template => simple-staking}/src/mock.rs (91%) create mode 100644 pallets/simple-staking/src/tests.rs delete mode 100644 pallets/template/src/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 7ae3689..f919c45 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4581,6 +4581,21 @@ dependencies = [ "sp-trie", ] +[[package]] +name = "pallet-simple-staking" +version = "3.0.0" +dependencies = [ + "frame-benchmarking", + "frame-support", + "frame-system", + "pallet-balances", + "parity-scale-codec", + "serde", + "sp-core", + "sp-io", + "sp-runtime", +] + [[package]] name = "pallet-society" version = "3.0.0" @@ -4643,20 +4658,6 @@ dependencies = [ "sp-std", ] -[[package]] -name = "pallet-template" -version = "3.0.0" -dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "parity-scale-codec", - "serde", - "sp-core", - "sp-io", - "sp-runtime", -] - [[package]] name = "pallet-timestamp" version = "3.0.0" @@ -9003,8 +9004,8 @@ dependencies = [ "pallet-multisig", "pallet-proxy", "pallet-randomness-collective-flip", + "pallet-simple-staking", "pallet-sudo", - "pallet-template", "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", @@ -9108,8 +9109,8 @@ dependencies = [ "pallet-multisig", "pallet-proxy", "pallet-randomness-collective-flip", + "pallet-simple-staking", "pallet-sudo", - "pallet-template", "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", diff --git a/Cargo.toml b/Cargo.toml index bc9917a..4759f8a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ panic = 'unwind' [workspace] members = [ 'node', - 'pallets/template', + 'pallets/simple-staking', 'runtime/statemint', 'runtime/statemine', ] diff --git a/pallets/template/Cargo.toml b/pallets/simple-staking/Cargo.toml similarity index 86% rename from pallets/template/Cargo.toml rename to pallets/simple-staking/Cargo.toml index e5bc598..5f5432f 100644 --- a/pallets/template/Cargo.toml +++ b/pallets/simple-staking/Cargo.toml @@ -4,7 +4,7 @@ description = 'FRAME pallet template for defining custom runtime logic.' edition = '2018' homepage = 'https://substrate.dev' license = 'Unlicense' -name = 'pallet-template' +name = 'pallet-simple-staking' readme = 'README.md' repository = 'https://github.com/paritytech/substrate/' version = '3.0.0' @@ -20,6 +20,8 @@ std = [ 'frame-support/std', 'frame-system/std', 'frame-benchmarking/std', + 'pallet-balances/std', + 'sp-runtime/std', ] [dependencies.codec] @@ -28,6 +30,13 @@ features = ['derive'] package = 'parity-scale-codec' version = '2.0.0' +[dependencies.pallet-balances] +default-features = false +optional = true +git = 'https://github.com/paritytech/substrate.git' +branch = 'rococo-v1' +version = '3.0.0' + [dependencies.frame-benchmarking] default-features = false optional = true diff --git a/pallets/template/README.md b/pallets/simple-staking/README.md similarity index 100% rename from pallets/template/README.md rename to pallets/simple-staking/README.md diff --git a/pallets/template/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs similarity index 75% rename from pallets/template/src/benchmarking.rs rename to pallets/simple-staking/src/benchmarking.rs index 4e1acc8..fb826ba 100644 --- a/pallets/template/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -3,7 +3,7 @@ use super::*; #[allow(unused)] -use crate::Module as Template; +use crate::Module as simple_staking; use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; use frame_system::RawOrigin; @@ -17,4 +17,4 @@ benchmarks! { } } -impl_benchmark_test_suite!(Template, crate::mock::new_test_ext(), crate::mock::Test,); +impl_benchmark_test_suite!(simple_staking, crate::mock::new_test_ext(), crate::mock::Test,); diff --git a/pallets/template/src/lib.rs b/pallets/simple-staking/src/lib.rs similarity index 51% rename from pallets/template/src/lib.rs rename to pallets/simple-staking/src/lib.rs index 68220ac..9afb80a 100644 --- a/pallets/template/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -16,14 +16,29 @@ mod benchmarking; #[frame_support::pallet] pub mod pallet { - use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*}; + use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, traits::{Currency, Vec}}; use frame_system::pallet_prelude::*; - + use frame_system::Config as SystemConfig; + use frame_support::sp_runtime::{ + RuntimeDebug, + traits::{ + AtLeast32BitUnsigned, + } + }; /// Configure the pallet by specifying the parameters and types on which it depends. #[pallet::config] pub trait Config: frame_system::Config { /// Because this pallet emits events, it depends on the runtime's definition of an event. type Event: From> + IsType<::Event>; + type Balance: Member + Parameter + AtLeast32BitUnsigned + Default + Copy; + + } + + + #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] + pub struct AuthorInfo { + who: AccountId, + deposit: Balance } #[pallet::pallet] @@ -32,14 +47,24 @@ pub mod pallet { // The pallet's runtime storage items. // https://substrate.dev/docs/en/knowledgebase/runtime/storage + #[pallet::storage] - #[pallet::getter(fn something)] - // Learn more about declaring storage items: - // https://substrate.dev/docs/en/knowledgebase/runtime/storage#declaring-storage-items - pub type Something = StorageValue<_, u32>; + #[pallet::getter(fn invulnerables)] + pub type Invulnerables= StorageValue<_, Vec>; - // Pallets use events to inform users when important changes are made. - // https://substrate.dev/docs/en/knowledgebase/runtime/events + #[pallet::storage] + #[pallet::getter(fn authors)] + pub type Authors = StorageValue<_, Vec>>; + + #[pallet::storage] + #[pallet::getter(fn max_authors)] + pub type MaxAuthors = StorageValue<_, u32>; + + #[pallet::storage] + #[pallet::getter(fn authority_bond)] + pub type AuthorityBond= StorageValue<_, T::Balance>; + + #[pallet::event] #[pallet::metadata(T::AccountId = "AccountId")] #[pallet::generate_deposit(pub(super) fn deposit_event)] @@ -59,48 +84,48 @@ pub mod pallet { } #[pallet::hooks] - impl Hooks> for Pallet {} + impl Hooks> for Pallet { + // on init add to aura set at next era + // split half the pot to the author per block + } // Dispatchable functions allows users to interact with the pallet and invoke state changes. // These functions materialize as "extrinsics", which are often compared to transactions. // Dispatchable functions must be annotated with a weight and must return a DispatchResult. #[pallet::call] impl Pallet { - /// An example dispatchable that takes a singles value as a parameter, writes the value to - /// storage and emits an event. This function must be dispatched by a signed extrinsic. - #[pallet::weight(10_000 + T::DbWeight::get().writes(1))] - pub fn do_something(origin: OriginFor, something: u32) -> DispatchResultWithPostInfo { - // Check that the extrinsic was signed and get the signer. - // This function will return an error if the extrinsic is not signed. - // https://substrate.dev/docs/en/knowledgebase/runtime/origin - let who = ensure_signed(origin)?; - - // Update storage. - >::put(something); - - // Emit an event. - Self::deposit_event(Event::SomethingStored(something, who)); - // Return a successful DispatchResultWithPostInfo + + + #[pallet::weight(10_000)] + fn set_invulnerables(origin: OriginFor, new_invulnerables: Vec) -> DispatchResultWithPostInfo { + // Protect function + // sets invulnerables Ok(().into()) + + } + + #[pallet::weight(10_000)] + fn set_max_author_count(origin: OriginFor, max_authors: u64) -> DispatchResultWithPostInfo { + // Protect function + // sets invulnerables + Ok(().into()) + } - /// An example dispatchable that may throw a custom error. - #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))] - pub fn cause_error(origin: OriginFor) -> DispatchResultWithPostInfo { - let _who = ensure_signed(origin)?; - - // Read a value from storage. - match >::get() { - // Return an error if the value has not been set. - None => Err(Error::::NoneValue)?, - Some(old) => { - // Increment the value read from storage; will error in the event of overflow. - let new = old.checked_add(1).ok_or(Error::::StorageOverflow)?; - // Update the value in storage with the incremented result. - >::put(new); - Ok(().into()) - } - } + #[pallet::weight(10_000)] + fn author_intent(origin: OriginFor) -> DispatchResultWithPostInfo { + // no stake for now? + // checks to make sure not max + // adds them to list + Ok(().into()) + + } + + #[pallet::weight(10_000)] + fn leave_intent(origin: OriginFor) -> DispatchResultWithPostInfo { + // removes them to list + Ok(().into()) + } } } diff --git a/pallets/template/src/mock.rs b/pallets/simple-staking/src/mock.rs similarity index 91% rename from pallets/template/src/mock.rs rename to pallets/simple-staking/src/mock.rs index 1ebe3be..45f8fec 100644 --- a/pallets/template/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -1,4 +1,4 @@ -use crate as pallet_template; +use crate as simple_staking; use sp_core::H256; use frame_support::parameter_types; use sp_runtime::{ @@ -17,7 +17,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event}, - TemplateModule: pallet_template::{Pallet, Call, Storage, Event}, + SimpleStaking: simple_staking::{Pallet, Call, Storage, Event}, } ); @@ -51,7 +51,7 @@ impl system::Config for Test { type SS58Prefix = SS58Prefix; } -impl pallet_template::Config for Test { +impl pallet_simple_staking::Config for Test { type Event = Event; } diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs new file mode 100644 index 0000000..136b1d9 --- /dev/null +++ b/pallets/simple-staking/src/tests.rs @@ -0,0 +1,15 @@ +use crate::{mock::*, Error}; +use frame_support::{assert_noop, assert_ok}; + +#[test] +fn it_works_for_default_value() { + new_test_ext().execute_with(|| { + + }); +} + +#[test] +fn correct_error_for_none_value() { + new_test_ext().execute_with(|| { + }); +} diff --git a/pallets/template/src/tests.rs b/pallets/template/src/tests.rs deleted file mode 100644 index aecf130..0000000 --- a/pallets/template/src/tests.rs +++ /dev/null @@ -1,23 +0,0 @@ -use crate::{mock::*, Error}; -use frame_support::{assert_noop, assert_ok}; - -#[test] -fn it_works_for_default_value() { - new_test_ext().execute_with(|| { - // Dispatch a signed extrinsic. - assert_ok!(TemplateModule::do_something(Origin::signed(1), 42)); - // Read pallet storage and assert an expected result. - assert_eq!(TemplateModule::something(), Some(42)); - }); -} - -#[test] -fn correct_error_for_none_value() { - new_test_ext().execute_with(|| { - // Ensure the expected error is thrown when no value is present. - assert_noop!( - TemplateModule::cause_error(Origin::signed(1)), - Error::::NoneValue - ); - }); -} diff --git a/runtime/statemine/Cargo.toml b/runtime/statemine/Cargo.toml index e71e569..2e3aa3e 100644 --- a/runtime/statemine/Cargo.toml +++ b/runtime/statemine/Cargo.toml @@ -259,10 +259,10 @@ git = 'https://github.com/paritytech/polkadot' branch = 'rococo-v1' default-features = false -[dependencies.template] +[dependencies.simple-staking] default-features = false -package = 'pallet-template' -path = '../../pallets/template' +package = 'pallet-simple-staking' +path = '../../pallets/simple-staking' [dependencies.runtime-common] default-features = false @@ -280,7 +280,7 @@ runtime-benchmarks = [ 'frame-system/runtime-benchmarks', 'pallet-balances/runtime-benchmarks', 'pallet-timestamp/runtime-benchmarks', - 'template/runtime-benchmarks', + 'simple-staking/runtime-benchmarks', ] std = [ 'codec/std', @@ -323,5 +323,5 @@ std = [ 'polkadot-runtime-common/std', 'runtime-common/std', 'polkadot-primitives/std', - 'template/std', + 'simple-staking/std', ] diff --git a/runtime/statemint/Cargo.toml b/runtime/statemint/Cargo.toml index f4edee5..4af500c 100644 --- a/runtime/statemint/Cargo.toml +++ b/runtime/statemint/Cargo.toml @@ -259,10 +259,10 @@ git = 'https://github.com/paritytech/polkadot' branch = 'rococo-v1' default-features = false -[dependencies.template] +[dependencies.simple-staking] default-features = false -package = 'pallet-template' -path = '../../pallets/template' +package = 'pallet-simple-staking' +path = '../../pallets/simple-staking' [dependencies.runtime-common] default-features = false @@ -280,7 +280,7 @@ runtime-benchmarks = [ 'frame-system/runtime-benchmarks', 'pallet-balances/runtime-benchmarks', 'pallet-timestamp/runtime-benchmarks', - 'template/runtime-benchmarks', + 'simple-staking/runtime-benchmarks', ] std = [ 'codec/std', @@ -323,5 +323,5 @@ std = [ 'polkadot-runtime-common/std', 'runtime-common/std', 'polkadot-primitives/std', - 'template/std', + 'simple-staking/std', ] From 7332288684989ee342f391280707d4f05662179a Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Tue, 6 Apr 2021 17:08:18 +0200 Subject: [PATCH 02/56] added try mutate --- pallets/simple-staking/src/lib.rs | 70 +++++++++++++++++++++---------- 1 file changed, 48 insertions(+), 22 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 9afb80a..9f9bd7a 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -17,7 +17,7 @@ mod benchmarking; #[frame_support::pallet] pub mod pallet { use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, traits::{Currency, Vec}}; - use frame_system::pallet_prelude::*; + use frame_system::{pallet_prelude::*, ensure_root}; use frame_system::Config as SystemConfig; use frame_support::sp_runtime::{ RuntimeDebug, @@ -36,9 +36,10 @@ pub mod pallet { #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] - pub struct AuthorInfo { + pub struct AuthorInfo { who: AccountId, - deposit: Balance + deposit: Balance, + last_block: BlockNumber } #[pallet::pallet] @@ -54,7 +55,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn authors)] - pub type Authors = StorageValue<_, Vec>>; + pub type Authors = StorageValue<_, Vec>, ValueQuery>; #[pallet::storage] #[pallet::getter(fn max_authors)] @@ -71,16 +72,18 @@ pub mod pallet { pub enum Event { /// Event documentation should end with an array that provides descriptive names for event /// parameters. [something, who] - SomethingStored(u32, T::AccountId), + NewInvulnerables(Vec), + NewMaxAuthorCount(u32), } // Errors inform users that something went wrong. #[pallet::error] pub enum Error { - /// Error names should be descriptive. - NoneValue, - /// Errors should have helpful documentation associated with them. - StorageOverflow, + MaxAuthors, + Unknown, + Permission, + AlreadyAuthor, + NotAuthor } #[pallet::hooks] @@ -97,33 +100,56 @@ pub mod pallet { #[pallet::weight(10_000)] - fn set_invulnerables(origin: OriginFor, new_invulnerables: Vec) -> DispatchResultWithPostInfo { - // Protect function - // sets invulnerables + fn set_invulnerables(origin: OriginFor, new: Vec) -> DispatchResultWithPostInfo { + //TODO chose protective scheme + ensure_root(origin)?; + >::put(&new); + Self::deposit_event(Event::NewInvulnerables(new)); Ok(().into()) - } #[pallet::weight(10_000)] - fn set_max_author_count(origin: OriginFor, max_authors: u64) -> DispatchResultWithPostInfo { - // Protect function - // sets invulnerables + fn set_max_author_count(origin: OriginFor, max_authors: u32) -> DispatchResultWithPostInfo { + //TODO chose protective scheme + ensure_root(origin)?; + >::put(&max_authors); + Self::deposit_event(Event::NewMaxAuthorCount(max_authors)); + // sets max authors Ok(().into()) } #[pallet::weight(10_000)] - fn author_intent(origin: OriginFor) -> DispatchResultWithPostInfo { - // no stake for now? - // checks to make sure not max - // adds them to list + fn author_intent(origin: OriginFor, deposit: T::Balance) -> DispatchResultWithPostInfo { + let who = ensure_signed(origin)?; + ensure!(>::decode_len().ok_or(Error::::Unknown)? + 1 <= MaxAuthors::::get().ok_or(Error::::Unknown)? as usize, Error::::MaxAuthors); + let new_author = AuthorInfo { + who: who.clone(), + deposit, + last_block: frame_system::Pallet::::block_number() + + }; + //take deposit + >::try_mutate(|authors| -> DispatchResult { + let exists = authors.into_iter().any(|author| author.who == who); + match exists { + true => Ok(authors.push(new_author)), + false => Err(Error::::AlreadyAuthor)?, + } + })?; Ok(().into()) - } #[pallet::weight(10_000)] fn leave_intent(origin: OriginFor) -> DispatchResultWithPostInfo { - // removes them to list + let who = ensure_signed(origin)?; + >::try_mutate(|authors| -> DispatchResult { + let index = authors.iter().position(|author| author.who == who).ok_or(Error::::NotAuthor)?; + authors.remove(index); + Ok(()) + })?; + + Ok(().into()) } From fbfa722cff034d510fbb8c7f8828fa0314164884 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Tue, 6 Apr 2021 17:25:29 +0200 Subject: [PATCH 03/56] add reserve and unreserve --- pallets/simple-staking/src/lib.rs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 9f9bd7a..3b4cd76 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -16,7 +16,7 @@ mod benchmarking; #[frame_support::pallet] pub mod pallet { - use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, traits::{Currency, Vec}}; + use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, traits::{Currency, ReservableCurrency, Vec}}; use frame_system::{pallet_prelude::*, ensure_root}; use frame_system::Config as SystemConfig; use frame_support::sp_runtime::{ @@ -31,8 +31,10 @@ pub mod pallet { /// Because this pallet emits events, it depends on the runtime's definition of an event. type Event: From> + IsType<::Event>; type Balance: Member + Parameter + AtLeast32BitUnsigned + Default + Copy; - + /// The currency mechanism. + type Currency: ReservableCurrency; } + type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] @@ -55,7 +57,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn authors)] - pub type Authors = StorageValue<_, Vec>, ValueQuery>; + pub type Authors = StorageValue<_, Vec, T::BlockNumber>>, ValueQuery>; #[pallet::storage] #[pallet::getter(fn max_authors)] @@ -63,7 +65,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn authority_bond)] - pub type AuthorityBond= StorageValue<_, T::Balance>; + pub type AuthorityBond= StorageValue<_, BalanceOf>; #[pallet::event] @@ -114,13 +116,13 @@ pub mod pallet { ensure_root(origin)?; >::put(&max_authors); Self::deposit_event(Event::NewMaxAuthorCount(max_authors)); - // sets max authors Ok(().into()) } #[pallet::weight(10_000)] - fn author_intent(origin: OriginFor, deposit: T::Balance) -> DispatchResultWithPostInfo { + fn author_intent(origin: OriginFor, deposit: BalanceOf) -> DispatchResultWithPostInfo { + // lock deposit to start or require min? let who = ensure_signed(origin)?; ensure!(>::decode_len().ok_or(Error::::Unknown)? + 1 <= MaxAuthors::::get().ok_or(Error::::Unknown)? as usize, Error::::MaxAuthors); let new_author = AuthorInfo { @@ -129,14 +131,15 @@ pub mod pallet { last_block: frame_system::Pallet::::block_number() }; - //take deposit >::try_mutate(|authors| -> DispatchResult { let exists = authors.into_iter().any(|author| author.who == who); + T::Currency::reserve(&who, deposit)?; match exists { true => Ok(authors.push(new_author)), false => Err(Error::::AlreadyAuthor)?, } })?; + // add event Ok(().into()) } @@ -145,11 +148,12 @@ pub mod pallet { let who = ensure_signed(origin)?; >::try_mutate(|authors| -> DispatchResult { let index = authors.iter().position(|author| author.who == who).ok_or(Error::::NotAuthor)?; + T::Currency::unreserve(&who, authors[index].deposit); authors.remove(index); Ok(()) })?; - - + + // add event Ok(().into()) } From 6b7706b038e3ca9720029a027bc4bb619af863f8 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Wed, 7 Apr 2021 14:22:06 +0200 Subject: [PATCH 04/56] tests --- pallets/simple-staking/Cargo.toml | 4 +- pallets/simple-staking/src/lib.rs | 48 ++++++++++----------- pallets/simple-staking/src/mock.rs | 37 +++++++++++++--- pallets/simple-staking/src/tests.rs | 65 +++++++++++++++++++++++++++-- 4 files changed, 117 insertions(+), 37 deletions(-) diff --git a/pallets/simple-staking/Cargo.toml b/pallets/simple-staking/Cargo.toml index 5f5432f..95ac1c3 100644 --- a/pallets/simple-staking/Cargo.toml +++ b/pallets/simple-staking/Cargo.toml @@ -20,7 +20,6 @@ std = [ 'frame-support/std', 'frame-system/std', 'frame-benchmarking/std', - 'pallet-balances/std', 'sp-runtime/std', ] @@ -30,9 +29,8 @@ features = ['derive'] package = 'parity-scale-codec' version = '2.0.0' -[dependencies.pallet-balances] +[dev-dependencies.pallet-balances] default-features = false -optional = true git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' version = '3.0.0' diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 3b4cd76..00165ef 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -19,18 +19,12 @@ pub mod pallet { use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, traits::{Currency, ReservableCurrency, Vec}}; use frame_system::{pallet_prelude::*, ensure_root}; use frame_system::Config as SystemConfig; - use frame_support::sp_runtime::{ - RuntimeDebug, - traits::{ - AtLeast32BitUnsigned, - } - }; + use frame_support::sp_runtime::{RuntimeDebug}; /// Configure the pallet by specifying the parameters and types on which it depends. #[pallet::config] pub trait Config: frame_system::Config { /// Because this pallet emits events, it depends on the runtime's definition of an event. type Event: From> + IsType<::Event>; - type Balance: Member + Parameter + AtLeast32BitUnsigned + Default + Copy; /// The currency mechanism. type Currency: ReservableCurrency; } @@ -39,9 +33,9 @@ pub mod pallet { #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] pub struct AuthorInfo { - who: AccountId, - deposit: Balance, - last_block: BlockNumber + pub who: AccountId, + pub deposit: Balance, + pub last_block: BlockNumber } #[pallet::pallet] @@ -76,6 +70,8 @@ pub mod pallet { /// parameters. [something, who] NewInvulnerables(Vec), NewMaxAuthorCount(u32), + AuthorAdded(T::AccountId, BalanceOf), + AuthorRemoved(T::AccountId) } // Errors inform users that something went wrong. @@ -90,8 +86,8 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - // on init add to aura set at next era - // split half the pot to the author per block + //TODO on init (or finalize) add to aura set at next era + //TODO split half the pot to the author per block } // Dispatchable functions allows users to interact with the pallet and invoke state changes. @@ -102,8 +98,8 @@ pub mod pallet { #[pallet::weight(10_000)] - fn set_invulnerables(origin: OriginFor, new: Vec) -> DispatchResultWithPostInfo { - //TODO chose protective scheme + pub fn set_invulnerables(origin: OriginFor, new: Vec) -> DispatchResultWithPostInfo { + //TODO chose protective scheme requires message from relay chain ensure_root(origin)?; >::put(&new); Self::deposit_event(Event::NewInvulnerables(new)); @@ -111,8 +107,8 @@ pub mod pallet { } #[pallet::weight(10_000)] - fn set_max_author_count(origin: OriginFor, max_authors: u32) -> DispatchResultWithPostInfo { - //TODO chose protective scheme + pub fn set_max_author_count(origin: OriginFor, max_authors: u32) -> DispatchResultWithPostInfo { + //TODO chose protective scheme requires message from relay chain ensure_root(origin)?; >::put(&max_authors); Self::deposit_event(Event::NewMaxAuthorCount(max_authors)); @@ -121,30 +117,33 @@ pub mod pallet { } #[pallet::weight(10_000)] - fn author_intent(origin: OriginFor, deposit: BalanceOf) -> DispatchResultWithPostInfo { + pub fn author_intent(origin: OriginFor, deposit: BalanceOf) -> DispatchResultWithPostInfo { // lock deposit to start or require min? let who = ensure_signed(origin)?; - ensure!(>::decode_len().ok_or(Error::::Unknown)? + 1 <= MaxAuthors::::get().ok_or(Error::::Unknown)? as usize, Error::::MaxAuthors); + let length = match >::decode_len() { + Some(len) => len, + None => 0 + }; + ensure!(length + 1 <= MaxAuthors::::get().ok_or(Error::::MaxAuthors)? as usize, Error::::MaxAuthors); let new_author = AuthorInfo { who: who.clone(), deposit, last_block: frame_system::Pallet::::block_number() - }; >::try_mutate(|authors| -> DispatchResult { let exists = authors.into_iter().any(|author| author.who == who); T::Currency::reserve(&who, deposit)?; match exists { - true => Ok(authors.push(new_author)), - false => Err(Error::::AlreadyAuthor)?, + false => Ok(authors.push(new_author)), + true => Err(Error::::AlreadyAuthor)?, } })?; - // add event + Self::deposit_event(Event::AuthorAdded(who, deposit)); Ok(().into()) } #[pallet::weight(10_000)] - fn leave_intent(origin: OriginFor) -> DispatchResultWithPostInfo { + pub fn leave_intent(origin: OriginFor) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; >::try_mutate(|authors| -> DispatchResult { let index = authors.iter().position(|author| author.who == who).ok_or(Error::::NotAuthor)?; @@ -152,8 +151,7 @@ pub mod pallet { authors.remove(index); Ok(()) })?; - - // add event + Self::deposit_event(Event::AuthorRemoved(who)); Ok(().into()) } diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index 45f8fec..6c2365b 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -1,3 +1,4 @@ +use super::*; use crate as simple_staking; use sp_core::H256; use frame_support::parameter_types; @@ -17,6 +18,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, SimpleStaking: simple_staking::{Pallet, Call, Storage, Event}, } ); @@ -44,18 +46,43 @@ impl system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); + type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = SS58Prefix; } -impl pallet_simple_staking::Config for Test { +parameter_types! { + pub const ExistentialDeposit: u64 = 1; +} + +impl pallet_balances::Config for Test { + type Balance = u64; type Event = Event; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type MaxLocks = (); } -// Build genesis storage according to the mock runtime. -pub fn new_test_ext() -> sp_io::TestExternalities { - system::GenesisConfig::default().build_storage::().unwrap().into() +impl Config for Test { + type Event = Event; + type Currency = Balances; } + +const A: u64 = 1; +const B: u64 = 2; + +pub fn new_test_ext() -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let genesis = pallet_balances::GenesisConfig:: { + balances: vec![ + (A, 100), + (B, 200), + ], + }; + genesis.assimilate_storage(&mut t).unwrap(); + t.into() +} \ No newline at end of file diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 136b1d9..8ed5859 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -1,15 +1,72 @@ -use crate::{mock::*, Error}; +use super::*; +use crate::{mock::*, Error, AuthorInfo}; use frame_support::{assert_noop, assert_ok}; +use super::Event as StakingEvent; +use sp_runtime::traits::BadOrigin; +use frame_system::EventRecord; +use pallet_balances::Error as BalancesError; + + +fn last_event() -> mock::Event { + frame_system::Pallet::::events().pop().expect("Event expected").event +} #[test] -fn it_works_for_default_value() { +fn it_should_set_invulnerables() { new_test_ext().execute_with(|| { - + let new_handlers = vec![1, 2, 3, 4]; + assert_ok!(SimpleStaking::set_invulnerables(Origin::root(), new_handlers.clone())); + // assert_eq!( + // last_event(), + // mock::Event::simple_staking(crate::Event::NewInvulnerables(new_handlers.clone())), + // ); + assert_noop!(SimpleStaking::set_invulnerables(Origin::signed(1), new_handlers.clone()), BadOrigin); + assert_eq!(SimpleStaking::invulnerables(), Some(new_handlers)); }); } #[test] -fn correct_error_for_none_value() { +fn set_max_author_count() { new_test_ext().execute_with(|| { + assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 7)); + assert_noop!(SimpleStaking::set_max_author_count(Origin::signed(1), 8), BadOrigin); + assert_eq!(SimpleStaking::max_authors(), Some(7)); }); } + +#[test] +fn author_intent() { + new_test_ext().execute_with(|| { + assert_noop!(SimpleStaking::author_intent(Origin::signed(1), 10), Error::::MaxAuthors); + + assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 1)); + assert_ok!(SimpleStaking::author_intent(Origin::signed(1), 10)); + + let addition = AuthorInfo { + who: 1, + deposit: 10, + last_block: 0 + }; + assert_eq!(SimpleStaking::authors(), vec![addition]); + assert_eq!(Balances::free_balance(1), 90); + assert_noop!(SimpleStaking::author_intent(Origin::signed(1), 10), Error::::MaxAuthors); + + assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 5)); + + // assert_noop!(SimpleStaking::author_intent(Origin::signed(1), 10), Error::::AlreadyAuthor); + assert_noop!(SimpleStaking::author_intent(Origin::signed(3), 10), BalancesError::::InsufficientBalance); + + }); +} + +#[test] +fn leave_intent() { + new_test_ext().execute_with(|| { + assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 1)); + assert_ok!(SimpleStaking::author_intent(Origin::signed(1), 10)); + assert_noop!(SimpleStaking::leave_intent(Origin::signed(3)), Error::::NotAuthor); + assert_ok!(SimpleStaking::leave_intent(Origin::signed(1))); + assert_eq!(SimpleStaking::authors(), vec![]); + assert_eq!(Balances::free_balance(1), 100); + }); +} \ No newline at end of file From 3fe9d0c21a4abb96a9d011cfc6a612ae1b81c50b Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Wed, 7 Apr 2021 15:15:52 +0200 Subject: [PATCH 05/56] fix no op issue --- pallets/simple-staking/src/lib.rs | 6 ++++-- pallets/simple-staking/src/tests.rs | 8 +++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 00165ef..1183e12 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -132,9 +132,11 @@ pub mod pallet { }; >::try_mutate(|authors| -> DispatchResult { let exists = authors.into_iter().any(|author| author.who == who); - T::Currency::reserve(&who, deposit)?; match exists { - false => Ok(authors.push(new_author)), + false => { + T::Currency::reserve(&who, deposit)?; + Ok(authors.push(new_author)) + }, true => Err(Error::::AlreadyAuthor)?, } })?; diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 8ed5859..409818f 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -47,15 +47,13 @@ fn author_intent() { deposit: 10, last_block: 0 }; - assert_eq!(SimpleStaking::authors(), vec![addition]); assert_eq!(Balances::free_balance(1), 90); assert_noop!(SimpleStaking::author_intent(Origin::signed(1), 10), Error::::MaxAuthors); - assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 5)); - - // assert_noop!(SimpleStaking::author_intent(Origin::signed(1), 10), Error::::AlreadyAuthor); + assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 5)); + assert_noop!(SimpleStaking::author_intent(Origin::signed(1), 10), Error::::AlreadyAuthor); assert_noop!(SimpleStaking::author_intent(Origin::signed(3), 10), BalancesError::::InsufficientBalance); - + assert_eq!(SimpleStaking::authors(), vec![addition]); }); } From f98bebc2e92381d9382ecad5a0247de915a4efaa Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Wed, 7 Apr 2021 17:14:01 +0200 Subject: [PATCH 06/56] fix build --- pallets/simple-staking/src/lib.rs | 7 ++++--- pallets/simple-staking/src/mock.rs | 1 + runtime/common/src/impls.rs | 1 + 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 1183e12..04039a3 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -16,7 +16,7 @@ mod benchmarking; #[frame_support::pallet] pub mod pallet { - use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, traits::{Currency, ReservableCurrency, Vec}}; + use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, inherent::Vec, traits::{Currency, ReservableCurrency}}; use frame_system::{pallet_prelude::*, ensure_root}; use frame_system::Config as SystemConfig; use frame_support::sp_runtime::{RuntimeDebug}; @@ -135,12 +135,13 @@ pub mod pallet { match exists { false => { T::Currency::reserve(&who, deposit)?; - Ok(authors.push(new_author)) + authors.push(new_author); + Self::deposit_event(Event::AuthorAdded(who, deposit)); + Ok(()) }, true => Err(Error::::AlreadyAuthor)?, } })?; - Self::deposit_event(Event::AuthorAdded(who, deposit)); Ok(().into()) } diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index 6c2365b..a0462d3 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -51,6 +51,7 @@ impl system::Config for Test { type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = SS58Prefix; + type OnSetCode = (); } parameter_types! { diff --git a/runtime/common/src/impls.rs b/runtime/common/src/impls.rs index 07c8d6b..2b91e45 100644 --- a/runtime/common/src/impls.rs +++ b/runtime/common/src/impls.rs @@ -130,6 +130,7 @@ mod tests { type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type OnSetCode = (); } impl pallet_balances::Config for Test { From c2274cfb67c9467b3dbcef4cfa6bd9bd2d76ce0e Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Thu, 8 Apr 2021 09:51:58 +0200 Subject: [PATCH 07/56] Update pallets/simple-staking/src/benchmarking.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/benchmarking.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index fb826ba..2a3ae12 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -3,7 +3,7 @@ use super::*; #[allow(unused)] -use crate::Module as simple_staking; +use crate::Pallet as SimpleStaking; use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; use frame_system::RawOrigin; From c9cbe28749507de77dff83021fab49f07b27be11 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Thu, 8 Apr 2021 09:52:12 +0200 Subject: [PATCH 08/56] Update pallets/simple-staking/src/benchmarking.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/benchmarking.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index 2a3ae12..372b967 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -17,4 +17,4 @@ benchmarks! { } } -impl_benchmark_test_suite!(simple_staking, crate::mock::new_test_ext(), crate::mock::Test,); +impl_benchmark_test_suite!(SimpleStaking, crate::mock::new_test_ext(), crate::mock::Test,); From c2b041487d3a7c9d96a1bfb40625f9fa3968c8d2 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Thu, 8 Apr 2021 09:52:28 +0200 Subject: [PATCH 09/56] Update pallets/simple-staking/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/lib.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 04039a3..c1e0355 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -1,8 +1,5 @@ #![cfg_attr(not(feature = "std"), no_std)] -/// Edit this file to define custom logic or remove it if it is not needed. -/// Learn more about FRAME and the core library of Substrate FRAME pallets: -/// pub use pallet::*; #[cfg(test)] From 274330c19833800494a57ab4013d09299277e234 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Thu, 8 Apr 2021 09:52:38 +0200 Subject: [PATCH 10/56] Update pallets/simple-staking/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index c1e0355..227463e 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -8,7 +8,7 @@ mod mock; #[cfg(test)] mod tests; -#[cfg(feature = "runtime-benchmarks")] +#[cfg(any(feature = "runtime-benchmarks", test))] mod benchmarking; #[frame_support::pallet] From 3d0bfc8ddd25645ec4d99f06c2fefb2e35e94dbb Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Thu, 8 Apr 2021 09:53:07 +0200 Subject: [PATCH 11/56] Update pallets/simple-staking/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 227463e..ff5a8cf 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -34,6 +34,7 @@ pub mod pallet { pub deposit: Balance, pub last_block: BlockNumber } + pub type AuthorInfoOf = AuthorInfo<::AccountId, ::Balance, ::BlockNumber>; #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] From fa6e23e957aad0eef073713f0d4af58c0cd312d5 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Thu, 8 Apr 2021 09:53:15 +0200 Subject: [PATCH 12/56] Update pallets/simple-staking/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index ff5a8cf..d3b6248 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -62,6 +62,7 @@ pub mod pallet { #[pallet::event] #[pallet::metadata(T::AccountId = "AccountId")] + #[pallet::metadata(BalanceOf = "Balance")] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// Event documentation should end with an array that provides descriptive names for event From 7cb60f8f6f007bc928f4288ca848b9c92447e9fa Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Thu, 8 Apr 2021 09:53:28 +0200 Subject: [PATCH 13/56] Update pallets/simple-staking/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/lib.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index d3b6248..983fa01 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -119,10 +119,7 @@ pub mod pallet { pub fn author_intent(origin: OriginFor, deposit: BalanceOf) -> DispatchResultWithPostInfo { // lock deposit to start or require min? let who = ensure_signed(origin)?; - let length = match >::decode_len() { - Some(len) => len, - None => 0 - }; + let length = match >::decode_len().unwrap_or_default(); ensure!(length + 1 <= MaxAuthors::::get().ok_or(Error::::MaxAuthors)? as usize, Error::::MaxAuthors); let new_author = AuthorInfo { who: who.clone(), From 9d8e37c3fd6b55efc736dc586dd4f148cc1b955a Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Thu, 8 Apr 2021 09:55:42 +0200 Subject: [PATCH 14/56] Update pallets/simple-staking/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 983fa01..794158f 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -120,7 +120,7 @@ pub mod pallet { // lock deposit to start or require min? let who = ensure_signed(origin)?; let length = match >::decode_len().unwrap_or_default(); - ensure!(length + 1 <= MaxAuthors::::get().ok_or(Error::::MaxAuthors)? as usize, Error::::MaxAuthors); + ensure!(length as u32 < MaxAuthors::::get(), Error::::MaxAuthors); let new_author = AuthorInfo { who: who.clone(), deposit, From e474f0731a2764676f8f4d7dc1c9d1621e90faec Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Thu, 8 Apr 2021 09:55:59 +0200 Subject: [PATCH 15/56] Update pallets/simple-staking/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/lib.rs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 794158f..84d6d90 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -127,15 +127,13 @@ pub mod pallet { last_block: frame_system::Pallet::::block_number() }; >::try_mutate(|authors| -> DispatchResult { - let exists = authors.into_iter().any(|author| author.who == who); - match exists { - false => { - T::Currency::reserve(&who, deposit)?; - authors.push(new_author); - Self::deposit_event(Event::AuthorAdded(who, deposit)); - Ok(()) - }, - true => Err(Error::::AlreadyAuthor)?, + if authors.into_iter().any(|author| author.who == who) { + T::Currency::reserve(&who, deposit)?; + authors.push(new_author); + Self::deposit_event(Event::AuthorAdded(who, deposit)); + Ok(()) + } else { + Err(Error::::AlreadyAuthor) } })?; Ok(().into()) From 00258ad8f6c438393df3182b3c9ca05342adaa38 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Thu, 8 Apr 2021 09:56:13 +0200 Subject: [PATCH 16/56] Update pallets/simple-staking/src/mock.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/mock.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index a0462d3..a56bf53 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -86,4 +86,4 @@ pub fn new_test_ext() -> sp_io::TestExternalities { }; genesis.assimilate_storage(&mut t).unwrap(); t.into() -} \ No newline at end of file +} From c6d3af697f869af3da7b4a0db3a8f79ad0ca4d7c Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Thu, 8 Apr 2021 10:14:54 +0200 Subject: [PATCH 17/56] build fix --- pallets/simple-staking/src/lib.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 84d6d90..299d8e8 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -34,7 +34,7 @@ pub mod pallet { pub deposit: Balance, pub last_block: BlockNumber } - pub type AuthorInfoOf = AuthorInfo<::AccountId, ::Balance, ::BlockNumber>; + pub type AuthorInfoOf = AuthorInfo<::AccountId, ::AccountId>>::Balance, ::BlockNumber>; #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] @@ -53,7 +53,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn max_authors)] - pub type MaxAuthors = StorageValue<_, u32>; + pub type MaxAuthors = StorageValue<_, u32, ValueQuery>; #[pallet::storage] #[pallet::getter(fn authority_bond)] @@ -61,8 +61,7 @@ pub mod pallet { #[pallet::event] - #[pallet::metadata(T::AccountId = "AccountId")] - #[pallet::metadata(BalanceOf = "Balance")] + #[pallet::metadata(T::AccountId = "AccountId", BalanceOf = "Balance")] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// Event documentation should end with an array that provides descriptive names for event @@ -119,8 +118,8 @@ pub mod pallet { pub fn author_intent(origin: OriginFor, deposit: BalanceOf) -> DispatchResultWithPostInfo { // lock deposit to start or require min? let who = ensure_signed(origin)?; - let length = match >::decode_len().unwrap_or_default(); - ensure!(length as u32 < MaxAuthors::::get(), Error::::MaxAuthors); + let length = >::decode_len().unwrap_or_default(); + ensure!((length as u32) < MaxAuthors::::get(), Error::::MaxAuthors); let new_author = AuthorInfo { who: who.clone(), deposit, @@ -133,7 +132,7 @@ pub mod pallet { Self::deposit_event(Event::AuthorAdded(who, deposit)); Ok(()) } else { - Err(Error::::AlreadyAuthor) + Err(Error::::AlreadyAuthor)? } })?; Ok(().into()) From 49d16b322af0250e2aad068982e4611e8e4a3a3c Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Thu, 8 Apr 2021 10:21:42 +0200 Subject: [PATCH 18/56] fix tests --- pallets/simple-staking/src/benchmarking.rs | 20 ++++++++++---------- pallets/simple-staking/src/lib.rs | 4 ++-- pallets/simple-staking/src/tests.rs | 2 +- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index 372b967..3c083e2 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -7,14 +7,14 @@ use crate::Pallet as SimpleStaking; use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; use frame_system::RawOrigin; -benchmarks! { - do_something { - let s in 0 .. 100; - let caller: T::AccountId = whitelisted_caller(); - }: _(RawOrigin::Signed(caller), s) - verify { - assert_eq!(Something::::get(), Some(s)); - } -} +// benchmarks! { +// // do_something { +// // let s in 0 .. 100; +// // let caller: T::AccountId = whitelisted_caller(); +// // }: _(RawOrigin::Signed(caller), s) +// // verify { +// // assert_eq!(Something::::get(), Some(s)); +// // } +// } -impl_benchmark_test_suite!(SimpleStaking, crate::mock::new_test_ext(), crate::mock::Test,); +// impl_benchmark_test_suite!(SimpleStaking, crate::mock::new_test_ext(), crate::mock::Test,); diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 299d8e8..95b5bf8 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -127,12 +127,12 @@ pub mod pallet { }; >::try_mutate(|authors| -> DispatchResult { if authors.into_iter().any(|author| author.who == who) { + Err(Error::::AlreadyAuthor)? + } else { T::Currency::reserve(&who, deposit)?; authors.push(new_author); Self::deposit_event(Event::AuthorAdded(who, deposit)); Ok(()) - } else { - Err(Error::::AlreadyAuthor)? } })?; Ok(().into()) diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 409818f..15f8d13 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -30,7 +30,7 @@ fn set_max_author_count() { new_test_ext().execute_with(|| { assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 7)); assert_noop!(SimpleStaking::set_max_author_count(Origin::signed(1), 8), BadOrigin); - assert_eq!(SimpleStaking::max_authors(), Some(7)); + assert_eq!(SimpleStaking::max_authors(), 7); }); } From c2dcfc8492c422fa81a1c923271695b59074b6e0 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Thu, 8 Apr 2021 12:24:58 +0200 Subject: [PATCH 19/56] tweaks --- pallets/simple-staking/src/lib.rs | 25 +++++++++++++++++++++---- pallets/simple-staking/src/tests.rs | 27 +++++++++++++++++++-------- 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 95b5bf8..d15fe81 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -32,7 +32,7 @@ pub mod pallet { pub struct AuthorInfo { pub who: AccountId, pub deposit: Balance, - pub last_block: BlockNumber + pub last_block: Option } pub type AuthorInfoOf = AuthorInfo<::AccountId, ::AccountId>>::Balance, ::BlockNumber>; @@ -55,6 +55,10 @@ pub mod pallet { #[pallet::getter(fn max_authors)] pub type MaxAuthors = StorageValue<_, u32, ValueQuery>; + #[pallet::storage] + #[pallet::getter(fn author_bond)] + pub type AuthorBond = StorageValue<_, BalanceOf, ValueQuery>; + #[pallet::storage] #[pallet::getter(fn authority_bond)] pub type AuthorityBond= StorageValue<_, BalanceOf>; @@ -68,6 +72,7 @@ pub mod pallet { /// parameters. [something, who] NewInvulnerables(Vec), NewMaxAuthorCount(u32), + NewAuthorBond(BalanceOf), AuthorAdded(T::AccountId, BalanceOf), AuthorRemoved(T::AccountId) } @@ -114,16 +119,28 @@ pub mod pallet { } + + #[pallet::weight(10_000)] + pub fn set_author_bond(origin: OriginFor, author_bond: BalanceOf) -> DispatchResultWithPostInfo { + //TODO chose protective scheme requires message from relay chain + ensure_root(origin)?; + >::put(&author_bond); + Self::deposit_event(Event::NewAuthorBond(author_bond)); + Ok(().into()) + + } + #[pallet::weight(10_000)] - pub fn author_intent(origin: OriginFor, deposit: BalanceOf) -> DispatchResultWithPostInfo { + pub fn register_as_author(origin: OriginFor) -> DispatchResultWithPostInfo { // lock deposit to start or require min? let who = ensure_signed(origin)?; + let deposit = >::get(); let length = >::decode_len().unwrap_or_default(); ensure!((length as u32) < MaxAuthors::::get(), Error::::MaxAuthors); let new_author = AuthorInfo { who: who.clone(), - deposit, - last_block: frame_system::Pallet::::block_number() + deposit, + last_block: None }; >::try_mutate(|authors| -> DispatchResult { if authors.into_iter().any(|author| author.who == who) { diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 15f8d13..46556bc 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -35,24 +35,34 @@ fn set_max_author_count() { } #[test] -fn author_intent() { +fn set_author_bond() { new_test_ext().execute_with(|| { - assert_noop!(SimpleStaking::author_intent(Origin::signed(1), 10), Error::::MaxAuthors); + assert_ok!(SimpleStaking::set_author_bond(Origin::root(), 7)); + assert_noop!(SimpleStaking::set_author_bond(Origin::signed(1), 8), BadOrigin); + assert_eq!(SimpleStaking::author_bond(), 7); + }); +} + +#[test] +fn register_as_author() { + new_test_ext().execute_with(|| { + assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::MaxAuthors); + assert_ok!(SimpleStaking::set_author_bond(Origin::root(), 10)); assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 1)); - assert_ok!(SimpleStaking::author_intent(Origin::signed(1), 10)); + assert_ok!(SimpleStaking::register_as_author(Origin::signed(1))); let addition = AuthorInfo { who: 1, deposit: 10, - last_block: 0 + last_block: None }; assert_eq!(Balances::free_balance(1), 90); - assert_noop!(SimpleStaking::author_intent(Origin::signed(1), 10), Error::::MaxAuthors); + assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::MaxAuthors); assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 5)); - assert_noop!(SimpleStaking::author_intent(Origin::signed(1), 10), Error::::AlreadyAuthor); - assert_noop!(SimpleStaking::author_intent(Origin::signed(3), 10), BalancesError::::InsufficientBalance); + assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::AlreadyAuthor); + assert_noop!(SimpleStaking::register_as_author(Origin::signed(3)), BalancesError::::InsufficientBalance); assert_eq!(SimpleStaking::authors(), vec![addition]); }); } @@ -61,7 +71,8 @@ fn author_intent() { fn leave_intent() { new_test_ext().execute_with(|| { assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 1)); - assert_ok!(SimpleStaking::author_intent(Origin::signed(1), 10)); + assert_ok!(SimpleStaking::set_author_bond(Origin::root(), 10)); + assert_ok!(SimpleStaking::register_as_author(Origin::signed(1))); assert_noop!(SimpleStaking::leave_intent(Origin::signed(3)), Error::::NotAuthor); assert_ok!(SimpleStaking::leave_intent(Origin::signed(1))); assert_eq!(SimpleStaking::authors(), vec![]); From 961335ebffdc7cb48f39c3fab819feb6a0606f3c Mon Sep 17 00:00:00 2001 From: kianenigma Date: Fri, 9 Apr 2021 13:08:50 +0200 Subject: [PATCH 20/56] Fix test build --- .gitignore | 3 ++- pallets/simple-staking/Cargo.toml | 30 ++++++++++++++---------------- pallets/simple-staking/src/lib.rs | 20 ++++++++++---------- pallets/simple-staking/src/mock.rs | 7 ++----- 4 files changed, 28 insertions(+), 32 deletions(-) diff --git a/.gitignore b/.gitignore index 240697f..3b7b8a8 100644 --- a/.gitignore +++ b/.gitignore @@ -55,4 +55,5 @@ dist configLocal.json *.json.json node_modules -polkadot \ No newline at end of file +polkadot +.vscode diff --git a/pallets/simple-staking/Cargo.toml b/pallets/simple-staking/Cargo.toml index 95ac1c3..f690b5a 100644 --- a/pallets/simple-staking/Cargo.toml +++ b/pallets/simple-staking/Cargo.toml @@ -12,17 +12,6 @@ version = '3.0.0' [package.metadata.docs.rs] targets = ['x86_64-unknown-linux-gnu'] -[features] -default = ['std'] -runtime-benchmarks = ['frame-benchmarking'] -std = [ - 'codec/std', - 'frame-support/std', - 'frame-system/std', - 'frame-benchmarking/std', - 'sp-runtime/std', -] - [dependencies.codec] default-features = false features = ['derive'] @@ -54,23 +43,32 @@ git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' version = '3.0.0' -[dev-dependencies] -serde = { version = "1.0.119" } +[dev-dependencies.serde] +version = "1.0.119" [dev-dependencies.sp-core] -default-features = false git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' version = '3.0.0' [dev-dependencies.sp-io] -default-features = false git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' version = '3.0.0' [dev-dependencies.sp-runtime] -default-features = false git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' version = '3.0.0' + +[features] +default = ['std'] +runtime-benchmarks = ['frame-benchmarking'] +std = [ + 'codec/std', + 'frame-support/std', + 'frame-system/std', + 'frame-benchmarking/std', + 'sp-runtime/std', + 'pallet-balances/std', +] diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index d15fe81..f38ff54 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -42,7 +42,7 @@ pub mod pallet { // The pallet's runtime storage items. // https://substrate.dev/docs/en/knowledgebase/runtime/storage - + #[pallet::storage] #[pallet::getter(fn invulnerables)] pub type Invulnerables= StorageValue<_, Vec>; @@ -53,17 +53,17 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn max_authors)] - pub type MaxAuthors = StorageValue<_, u32, ValueQuery>; + pub type MaxAuthors = StorageValue<_, u32, ValueQuery>; #[pallet::storage] #[pallet::getter(fn author_bond)] - pub type AuthorBond = StorageValue<_, BalanceOf, ValueQuery>; + pub type AuthorBond = StorageValue<_, BalanceOf, ValueQuery>; #[pallet::storage] #[pallet::getter(fn authority_bond)] pub type AuthorityBond= StorageValue<_, BalanceOf>; - + #[pallet::event] #[pallet::metadata(T::AccountId = "AccountId", BalanceOf = "Balance")] #[pallet::generate_deposit(pub(super) fn deposit_event)] @@ -89,7 +89,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { - //TODO on init (or finalize) add to aura set at next era + //TODO on init (or finalize) add to aura set at next era //TODO split half the pot to the author per block } @@ -102,7 +102,7 @@ pub mod pallet { #[pallet::weight(10_000)] pub fn set_invulnerables(origin: OriginFor, new: Vec) -> DispatchResultWithPostInfo { - //TODO chose protective scheme requires message from relay chain + //TODO chose protective scheme requires message from relay chain ensure_root(origin)?; >::put(&new); Self::deposit_event(Event::NewInvulnerables(new)); @@ -111,7 +111,7 @@ pub mod pallet { #[pallet::weight(10_000)] pub fn set_max_author_count(origin: OriginFor, max_authors: u32) -> DispatchResultWithPostInfo { - //TODO chose protective scheme requires message from relay chain + //TODO chose protective scheme requires message from relay chain ensure_root(origin)?; >::put(&max_authors); Self::deposit_event(Event::NewMaxAuthorCount(max_authors)); @@ -122,7 +122,7 @@ pub mod pallet { #[pallet::weight(10_000)] pub fn set_author_bond(origin: OriginFor, author_bond: BalanceOf) -> DispatchResultWithPostInfo { - //TODO chose protective scheme requires message from relay chain + //TODO chose protective scheme requires message from relay chain ensure_root(origin)?; >::put(&author_bond); Self::deposit_event(Event::NewAuthorBond(author_bond)); @@ -136,9 +136,9 @@ pub mod pallet { let who = ensure_signed(origin)?; let deposit = >::get(); let length = >::decode_len().unwrap_or_default(); - ensure!((length as u32) < MaxAuthors::::get(), Error::::MaxAuthors); + ensure!((length as u32) < MaxAuthors::::get(), Error::::MaxAuthors); let new_author = AuthorInfo { - who: who.clone(), + who: who.clone(), deposit, last_block: None }; diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index a56bf53..c319665 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -73,15 +73,12 @@ impl Config for Test { type Currency = Balances; } -const A: u64 = 1; -const B: u64 = 2; - pub fn new_test_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); let genesis = pallet_balances::GenesisConfig:: { balances: vec![ - (A, 100), - (B, 200), + (1, 100), + (1, 200), ], }; genesis.assimilate_storage(&mut t).unwrap(); From 029e3ae5cdc476f05119cd8aa8e8eec760219efa Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Mon, 12 Apr 2021 14:48:15 +0200 Subject: [PATCH 21/56] added updater origin --- pallets/simple-staking/src/lib.rs | 13 ++++++------- pallets/simple-staking/src/mock.rs | 10 ++++++++-- pallets/simple-staking/src/tests.rs | 18 +++++++++--------- 3 files changed, 23 insertions(+), 18 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index f38ff54..088e7c5 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -13,7 +13,7 @@ mod benchmarking; #[frame_support::pallet] pub mod pallet { - use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, inherent::Vec, traits::{Currency, ReservableCurrency}}; + use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, inherent::Vec, traits::{Currency, ReservableCurrency, EnsureOrigin}}; use frame_system::{pallet_prelude::*, ensure_root}; use frame_system::Config as SystemConfig; use frame_support::sp_runtime::{RuntimeDebug}; @@ -24,6 +24,8 @@ pub mod pallet { type Event: From> + IsType<::Event>; /// The currency mechanism. type Currency: ReservableCurrency; + + type UpdateOrigin: EnsureOrigin; } type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; @@ -102,8 +104,7 @@ pub mod pallet { #[pallet::weight(10_000)] pub fn set_invulnerables(origin: OriginFor, new: Vec) -> DispatchResultWithPostInfo { - //TODO chose protective scheme requires message from relay chain - ensure_root(origin)?; + T::UpdateOrigin::ensure_origin(origin)?; >::put(&new); Self::deposit_event(Event::NewInvulnerables(new)); Ok(().into()) @@ -111,8 +112,7 @@ pub mod pallet { #[pallet::weight(10_000)] pub fn set_max_author_count(origin: OriginFor, max_authors: u32) -> DispatchResultWithPostInfo { - //TODO chose protective scheme requires message from relay chain - ensure_root(origin)?; + T::UpdateOrigin::ensure_origin(origin)?; >::put(&max_authors); Self::deposit_event(Event::NewMaxAuthorCount(max_authors)); Ok(().into()) @@ -122,8 +122,7 @@ pub mod pallet { #[pallet::weight(10_000)] pub fn set_author_bond(origin: OriginFor, author_bond: BalanceOf) -> DispatchResultWithPostInfo { - //TODO chose protective scheme requires message from relay chain - ensure_root(origin)?; + T::UpdateOrigin::ensure_origin(origin)?; >::put(&author_bond); Self::deposit_event(Event::NewAuthorBond(author_bond)); Ok(().into()) diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index c319665..766a674 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -1,10 +1,11 @@ use super::*; use crate as simple_staking; use sp_core::H256; -use frame_support::parameter_types; +use frame_support::{parameter_types, ord_parameter_types}; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, testing::Header, }; +use frame_system::{EnsureSignedBy}; use frame_system as system; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -68,9 +69,14 @@ impl pallet_balances::Config for Test { type MaxLocks = (); } +ord_parameter_types! { + pub const Three: u64 = 3; +} + impl Config for Test { type Event = Event; type Currency = Balances; + type UpdateOrigin = EnsureSignedBy; } pub fn new_test_ext() -> sp_io::TestExternalities { @@ -78,7 +84,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { let genesis = pallet_balances::GenesisConfig:: { balances: vec![ (1, 100), - (1, 200), + (2, 200), ], }; genesis.assimilate_storage(&mut t).unwrap(); diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 46556bc..367744a 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -15,7 +15,7 @@ fn last_event() -> mock::Event { fn it_should_set_invulnerables() { new_test_ext().execute_with(|| { let new_handlers = vec![1, 2, 3, 4]; - assert_ok!(SimpleStaking::set_invulnerables(Origin::root(), new_handlers.clone())); + assert_ok!(SimpleStaking::set_invulnerables(Origin::signed(3), new_handlers.clone())); // assert_eq!( // last_event(), // mock::Event::simple_staking(crate::Event::NewInvulnerables(new_handlers.clone())), @@ -28,7 +28,7 @@ fn it_should_set_invulnerables() { #[test] fn set_max_author_count() { new_test_ext().execute_with(|| { - assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 7)); + assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(3), 7)); assert_noop!(SimpleStaking::set_max_author_count(Origin::signed(1), 8), BadOrigin); assert_eq!(SimpleStaking::max_authors(), 7); }); @@ -37,7 +37,7 @@ fn set_max_author_count() { #[test] fn set_author_bond() { new_test_ext().execute_with(|| { - assert_ok!(SimpleStaking::set_author_bond(Origin::root(), 7)); + assert_ok!(SimpleStaking::set_author_bond(Origin::signed(3), 7)); assert_noop!(SimpleStaking::set_author_bond(Origin::signed(1), 8), BadOrigin); assert_eq!(SimpleStaking::author_bond(), 7); }); @@ -48,8 +48,8 @@ fn register_as_author() { new_test_ext().execute_with(|| { assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::MaxAuthors); - assert_ok!(SimpleStaking::set_author_bond(Origin::root(), 10)); - assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 1)); + assert_ok!(SimpleStaking::set_author_bond(Origin::signed(3), 10)); + assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(3), 1)); assert_ok!(SimpleStaking::register_as_author(Origin::signed(1))); let addition = AuthorInfo { @@ -59,8 +59,8 @@ fn register_as_author() { }; assert_eq!(Balances::free_balance(1), 90); assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::MaxAuthors); - - assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 5)); + + assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(3), 5)); assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::AlreadyAuthor); assert_noop!(SimpleStaking::register_as_author(Origin::signed(3)), BalancesError::::InsufficientBalance); assert_eq!(SimpleStaking::authors(), vec![addition]); @@ -70,8 +70,8 @@ fn register_as_author() { #[test] fn leave_intent() { new_test_ext().execute_with(|| { - assert_ok!(SimpleStaking::set_max_author_count(Origin::root(), 1)); - assert_ok!(SimpleStaking::set_author_bond(Origin::root(), 10)); + assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(3), 1)); + assert_ok!(SimpleStaking::set_author_bond(Origin::signed(3), 10)); assert_ok!(SimpleStaking::register_as_author(Origin::signed(1))); assert_noop!(SimpleStaking::leave_intent(Origin::signed(3)), Error::::NotAuthor); assert_ok!(SimpleStaking::leave_intent(Origin::signed(1))); From acf9416a5300955a540a4f6a868c5e6fd05208d0 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Tue, 13 Apr 2021 15:06:50 +0200 Subject: [PATCH 22/56] on initalize for fee split --- Cargo.lock | 37 +++++++++++++++++++++++++++++++ pallets/simple-staking/Cargo.toml | 22 ++++++++++++++++++ pallets/simple-staking/src/lib.rs | 17 +++++++++++--- 3 files changed, 73 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a4f57dd..b191be0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4389,6 +4389,23 @@ dependencies = [ "sp-std", ] +[[package]] +name = "pallet-aura" +version = "3.0.0" +source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#3ec97a31b285181fb1beab426ee2a8e2cb1188ab" +dependencies = [ + "frame-support", + "frame-system", + "pallet-session", + "pallet-timestamp", + "parity-scale-codec", + "serde", + "sp-application-crypto", + "sp-consensus-aura", + "sp-runtime", + "sp-std", +] + [[package]] name = "pallet-authority-discovery" version = "3.0.0" @@ -4823,9 +4840,13 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-aura", + "pallet-authorship", "pallet-balances", + "pallet-timestamp", "parity-scale-codec", "serde", + "sp-consensus-aura", "sp-core", "sp-io", "sp-runtime", @@ -8780,6 +8801,22 @@ dependencies = [ "wasm-timer", ] +[[package]] +name = "sp-consensus-aura" +version = "0.9.0" +source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#3ec97a31b285181fb1beab426ee2a8e2cb1188ab" +dependencies = [ + "parity-scale-codec", + "sp-api", + "sp-application-crypto", + "sp-consensus", + "sp-consensus-slots", + "sp-inherents", + "sp-runtime", + "sp-std", + "sp-timestamp", +] + [[package]] name = "sp-consensus-babe" version = "0.9.0" diff --git a/pallets/simple-staking/Cargo.toml b/pallets/simple-staking/Cargo.toml index f690b5a..0f34aef 100644 --- a/pallets/simple-staking/Cargo.toml +++ b/pallets/simple-staking/Cargo.toml @@ -24,6 +24,12 @@ git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' version = '3.0.0' +[dependencies.pallet-authorship] +default-features = false +git = 'https://github.com/paritytech/substrate.git' +branch = 'rococo-v1' +version = '3.0.0' + [dependencies.frame-benchmarking] default-features = false optional = true @@ -61,6 +67,21 @@ git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' version = '3.0.0' +[dev-dependencies.pallet-aura] +git = 'https://github.com/paritytech/substrate.git' +branch = 'rococo-v1' +version = '3.0.0' + +[dev-dependencies.pallet-timestamp] +git = 'https://github.com/paritytech/substrate.git' +branch = 'rococo-v1' +version = '3.0.0' + +[dev-dependencies.sp-consensus-aura] +git = 'https://github.com/paritytech/substrate.git' +branch = 'rococo-v1' +version = '0.9.0' + [features] default = ['std'] runtime-benchmarks = ['frame-benchmarking'] @@ -70,5 +91,6 @@ std = [ 'frame-system/std', 'frame-benchmarking/std', 'sp-runtime/std', + 'pallet-authorship/std', 'pallet-balances/std', ] diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 088e7c5..821dd95 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -13,19 +13,23 @@ mod benchmarking; #[frame_support::pallet] pub mod pallet { - use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, inherent::Vec, traits::{Currency, ReservableCurrency, EnsureOrigin}}; + use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, inherent::Vec, traits::{Currency, ReservableCurrency, EnsureOrigin, ExistenceRequirement::{KeepAlive, AllowDeath}}}; use frame_system::{pallet_prelude::*, ensure_root}; use frame_system::Config as SystemConfig; use frame_support::sp_runtime::{RuntimeDebug}; + use pallet_authorship as authorship; + use core::ops::{Div}; /// Configure the pallet by specifying the parameters and types on which it depends. #[pallet::config] - pub trait Config: frame_system::Config { + pub trait Config: frame_system::Config + authorship::Config { /// Because this pallet emits events, it depends on the runtime's definition of an event. type Event: From> + IsType<::Event>; /// The currency mechanism. type Currency: ReservableCurrency; type UpdateOrigin: EnsureOrigin; + + type TreasuryAddress: Get; } type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; @@ -91,8 +95,15 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { + fn on_initialize(_: T::BlockNumber) -> Weight { + let author = >::author(); + let treasury = T::TreasuryAddress::get(); + let reward = T::Currency::free_balance(&treasury).div(2u32.into()); + T::Currency::transfer(&treasury, &author, reward, KeepAlive); + // weight 3 reads (author, treasury, balance) 2 writes (one transfer, write out and in) + T::DbWeight::get().reads_writes(3, 2) + } //TODO on init (or finalize) add to aura set at next era - //TODO split half the pot to the author per block } // Dispatchable functions allows users to interact with the pallet and invoke state changes. From f92d157d567b163f27f81766bb7c52bcafcc9188 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Tue, 13 Apr 2021 15:13:11 +0200 Subject: [PATCH 23/56] mock --- pallets/simple-staking/src/lib.rs | 4 ++-- pallets/simple-staking/src/mock.rs | 37 +++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 821dd95..87224dd 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -100,8 +100,8 @@ pub mod pallet { let treasury = T::TreasuryAddress::get(); let reward = T::Currency::free_balance(&treasury).div(2u32.into()); T::Currency::transfer(&treasury, &author, reward, KeepAlive); - // weight 3 reads (author, treasury, balance) 2 writes (one transfer, write out and in) - T::DbWeight::get().reads_writes(3, 2) + // TODO double check: weight 3 reads (author, treasury, balance) 1 writes (transfer) + T::DbWeight::get().reads_writes(3, 1) } //TODO on init (or finalize) add to aura set at next era } diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index 766a674..f8c4560 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -5,6 +5,7 @@ use frame_support::{parameter_types, ord_parameter_types}; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, testing::Header, }; +use sp_consensus_aura::sr25519::AuthorityId; use frame_system::{EnsureSignedBy}; use frame_system as system; @@ -19,8 +20,11 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event}, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, + Aura: pallet_aura::{Pallet, Call, Storage, Config}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, SimpleStaking: simple_staking::{Pallet, Call, Storage, Event}, + Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent}, } ); @@ -69,16 +73,47 @@ impl pallet_balances::Config for Test { type MaxLocks = (); } +parameter_types! { + pub const Author: u64 = 4; +} + +impl pallet_authorship::Config for Test { + type FindAuthor = (); + type UncleGenerations = (); + type FilterUncle = (); + type EventHandler = (); +} + +parameter_types! { + pub const MinimumPeriod: u64 = 1; +} + +impl pallet_timestamp::Config for Test { + type Moment = u64; + type OnTimestampSet = Aura; + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); +} + +impl pallet_aura::Config for Test { + type AuthorityId = AuthorityId; +} + + ord_parameter_types! { pub const Three: u64 = 3; } - +parameter_types! { + pub const TreasuryAddress: u64 = 5; +} impl Config for Test { type Event = Event; type Currency = Balances; type UpdateOrigin = EnsureSignedBy; + type TreasuryAddress = TreasuryAddress; } + pub fn new_test_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); let genesis = pallet_balances::GenesisConfig:: { From 4fd533cfdeb8bd23d0c15dc456f49e43375bfa4f Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Tue, 13 Apr 2021 16:19:14 +0200 Subject: [PATCH 24/56] on init test --- pallets/simple-staking/src/mock.rs | 17 +++++++++++------ pallets/simple-staking/src/tests.rs | 17 +++++++++++++---- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index f8c4560..2071238 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -1,9 +1,9 @@ use super::*; use crate as simple_staking; use sp_core::H256; -use frame_support::{parameter_types, ord_parameter_types}; +use frame_support::{parameter_types, ord_parameter_types, traits::{FindAuthor}}; use sp_runtime::{ - traits::{BlakeTwo256, IdentityLookup}, testing::Header, + traits::{BlakeTwo256, IdentityLookup}, testing::{Header, UintAuthorityId}, }; use sp_consensus_aura::sr25519::AuthorityId; use frame_system::{EnsureSignedBy}; @@ -73,12 +73,17 @@ impl pallet_balances::Config for Test { type MaxLocks = (); } -parameter_types! { - pub const Author: u64 = 4; +pub struct Author4; +impl FindAuthor for Author4 { + fn find_author<'a, I>(_digests: I) -> Option + where I: 'a + IntoIterator, + { + Some(4) + } } impl pallet_authorship::Config for Test { - type FindAuthor = (); + type FindAuthor = Author4; type UncleGenerations = (); type FilterUncle = (); type EventHandler = (); @@ -113,13 +118,13 @@ impl Config for Test { type TreasuryAddress = TreasuryAddress; } - pub fn new_test_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); let genesis = pallet_balances::GenesisConfig:: { balances: vec![ (1, 100), (2, 200), + (5, 100), ], }; genesis.assimilate_storage(&mut t).unwrap(); diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 367744a..44a67ff 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -1,6 +1,6 @@ use super::*; use crate::{mock::*, Error, AuthorInfo}; -use frame_support::{assert_noop, assert_ok}; +use frame_support::{assert_noop, assert_ok, traits::OnInitialize}; use super::Event as StakingEvent; use sp_runtime::traits::BadOrigin; use frame_system::EventRecord; @@ -47,14 +47,14 @@ fn set_author_bond() { fn register_as_author() { new_test_ext().execute_with(|| { assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::MaxAuthors); - + assert_ok!(SimpleStaking::set_author_bond(Origin::signed(3), 10)); assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(3), 1)); assert_ok!(SimpleStaking::register_as_author(Origin::signed(1))); let addition = AuthorInfo { - who: 1, - deposit: 10, + who: 1, + deposit: 10, last_block: None }; assert_eq!(Balances::free_balance(1), 90); @@ -78,4 +78,13 @@ fn leave_intent() { assert_eq!(SimpleStaking::authors(), vec![]); assert_eq!(Balances::free_balance(1), 100); }); +} + +#[test] +fn on_init() { + new_test_ext().execute_with(|| { + SimpleStaking::on_initialize(1); + assert_eq!(Balances::free_balance(4), 50); + assert_eq!(Balances::free_balance(5), 50); + }); } \ No newline at end of file From c48f90e260ee788b512225872346205aec913257 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Wed, 14 Apr 2021 09:55:19 +0200 Subject: [PATCH 25/56] added genesis config for invulnerables --- pallets/simple-staking/Cargo.toml | 3 ++- pallets/simple-staking/src/lib.rs | 22 +++++++++++++++++++++- pallets/simple-staking/src/mock.rs | 10 +++++++++- pallets/simple-staking/src/tests.rs | 10 +++++++++- 4 files changed, 41 insertions(+), 4 deletions(-) diff --git a/pallets/simple-staking/Cargo.toml b/pallets/simple-staking/Cargo.toml index 0f34aef..95893d0 100644 --- a/pallets/simple-staking/Cargo.toml +++ b/pallets/simple-staking/Cargo.toml @@ -49,8 +49,9 @@ git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' version = '3.0.0' -[dev-dependencies.serde] +[dependencies.serde] version = "1.0.119" +default-features = false [dev-dependencies.sp-core] git = 'https://github.com/paritytech/substrate.git' diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 87224dd..c38fc2a 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -51,7 +51,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn invulnerables)] - pub type Invulnerables= StorageValue<_, Vec>; + pub type Invulnerables= StorageValue<_, Vec, ValueQuery>; #[pallet::storage] #[pallet::getter(fn authors)] @@ -69,6 +69,26 @@ pub mod pallet { #[pallet::getter(fn authority_bond)] pub type AuthorityBond= StorageValue<_, BalanceOf>; + #[pallet::genesis_config] + pub struct GenesisConfig { + pub invulnerables: Vec, + } + + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { + invulnerables: Default::default(), + } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + >::put(&self.invulnerables); + } + } #[pallet::event] #[pallet::metadata(T::AccountId = "AccountId", BalanceOf = "Balance")] diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index 2071238..ffd4cce 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -1,7 +1,7 @@ use super::*; use crate as simple_staking; use sp_core::H256; -use frame_support::{parameter_types, ord_parameter_types, traits::{FindAuthor}}; +use frame_support::{parameter_types, ord_parameter_types, traits::{FindAuthor, GenesisBuild}}; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, testing::{Header, UintAuthorityId}, }; @@ -127,6 +127,14 @@ pub fn new_test_ext() -> sp_io::TestExternalities { (5, 100), ], }; + let genesis_staking = simple_staking::GenesisConfig:: { + invulnerables: vec![ + 1, + 2, + 3 + ], + }; genesis.assimilate_storage(&mut t).unwrap(); + genesis_staking.assimilate_storage(&mut t).unwrap(); t.into() } diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 44a67ff..94c3cb9 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -21,7 +21,7 @@ fn it_should_set_invulnerables() { // mock::Event::simple_staking(crate::Event::NewInvulnerables(new_handlers.clone())), // ); assert_noop!(SimpleStaking::set_invulnerables(Origin::signed(1), new_handlers.clone()), BadOrigin); - assert_eq!(SimpleStaking::invulnerables(), Some(new_handlers)); + assert_eq!(SimpleStaking::invulnerables(), new_handlers); }); } @@ -87,4 +87,12 @@ fn on_init() { assert_eq!(Balances::free_balance(4), 50); assert_eq!(Balances::free_balance(5), 50); }); +} + +#[test] +fn on_genesis() { + new_test_ext().execute_with(|| { + assert_eq!(SimpleStaking::invulnerables(), vec![1,2,3]); + assert_eq!(SimpleStaking::invulnerables().len(), 3); + }); } \ No newline at end of file From a6e3bc8bdba584e9675b41569336f73522a3b46c Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Wed, 14 Apr 2021 12:48:53 +0200 Subject: [PATCH 26/56] benchmarks --- pallets/simple-staking/Cargo.toml | 4 +- pallets/simple-staking/src/benchmarking.rs | 132 ++++++++++++++++++--- pallets/simple-staking/src/mock.rs | 4 +- pallets/simple-staking/src/tests.rs | 20 ++-- 4 files changed, 131 insertions(+), 29 deletions(-) diff --git a/pallets/simple-staking/Cargo.toml b/pallets/simple-staking/Cargo.toml index 95893d0..812cdcb 100644 --- a/pallets/simple-staking/Cargo.toml +++ b/pallets/simple-staking/Cargo.toml @@ -18,7 +18,7 @@ features = ['derive'] package = 'parity-scale-codec' version = '2.0.0' -[dev-dependencies.pallet-balances] +[dependencies.pallet-balances] default-features = false git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' @@ -91,7 +91,5 @@ std = [ 'frame-support/std', 'frame-system/std', 'frame-benchmarking/std', - 'sp-runtime/std', 'pallet-authorship/std', - 'pallet-balances/std', ] diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index 3c083e2..bade365 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -4,17 +4,121 @@ use super::*; #[allow(unused)] use crate::Pallet as SimpleStaking; -use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; -use frame_system::RawOrigin; - -// benchmarks! { -// // do_something { -// // let s in 0 .. 100; -// // let caller: T::AccountId = whitelisted_caller(); -// // }: _(RawOrigin::Signed(caller), s) -// // verify { -// // assert_eq!(Something::::get(), Some(s)); -// // } -// } - -// impl_benchmark_test_suite!(SimpleStaking, crate::mock::new_test_ext(), crate::mock::Test,); +use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller, Zero}; +use frame_system::{RawOrigin, EventRecord}; +use frame_support::{traits::Currency, dispatch::DispatchResult}; + +pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; + +fn assert_last_event(generic_event: ::Event) { + let events = frame_system::Module::::events(); + let system_event: ::Event = generic_event.into(); + // compare to the last event record + let EventRecord { event, .. } = &events[events.len() - 1]; + assert_eq!(event, &system_event); +} + +fn set_authors(who: T::AccountId, deposit: BalanceOf) -> DispatchResult { + let addition = AuthorInfo { + who, + deposit, + last_block: None + }; + Authors::::try_mutate(|authors| -> DispatchResult { + authors.push(addition); + Ok(()) + }) +} + +benchmarks! { + set_invulnerables { + let b in 1 .. 1000; + let caller: T::AccountId = whitelisted_caller(); + let new_invulnerables = vec![caller.clone(); b as usize]; + + }: _(RawOrigin::Signed(caller), new_invulnerables.clone()) + verify { + assert_last_event::(Event::NewInvulnerables(new_invulnerables).into()); + } + + set_max_author_count { + let b in 1 .. 1000; + let caller: T::AccountId = whitelisted_caller(); + + }: _(RawOrigin::Signed(caller), b.clone()) + verify { + assert_last_event::(Event::NewMaxAuthorCount(b).into()); + } + + set_author_bond { + let b in 1 .. 1000; + let caller: T::AccountId = whitelisted_caller(); + let new: BalanceOf = b.into(); + + }: _(RawOrigin::Signed(caller), new.clone()) + verify { + assert_last_event::(Event::NewAuthorBond(new).into()); + } + + register_as_author { + let caller: T::AccountId = whitelisted_caller(); + SimpleStaking::::set_author_bond(RawOrigin::Signed(caller.clone()).into(), 10u32.into()); + SimpleStaking::::set_max_author_count(RawOrigin::Signed(caller.clone()).into(), 1); + T::Currency::make_free_balance_be(&caller, 100_000u32.into()); + + }: _(RawOrigin::Signed(caller.clone())) + verify { + assert_last_event::(Event::AuthorAdded(caller, 10u32.into()).into()); + } + + leave_intent { + let caller: T::AccountId = whitelisted_caller(); + set_authors::(caller.clone(), 10u32.into())?; + + }: _(RawOrigin::Signed(caller.clone())) + verify { + assert_last_event::(Event::AuthorRemoved(caller).into()); + } +} +#[cfg(test)] +mod tests { + use super::*; + use crate::mock::{new_test_ext, Test}; + use frame_support::assert_ok; + + #[test] + fn set_invulnerables() { + new_test_ext().execute_with(|| { + assert_ok!(test_benchmark_set_invulnerables::()); + }); + } + + #[test] + fn set_max_author_count() { + new_test_ext().execute_with(|| { + assert_ok!(test_benchmark_set_max_author_count::()); + }); + } + + #[test] + fn set_author_bond() { + new_test_ext().execute_with(|| { + assert_ok!(test_benchmark_set_author_bond::()); + }); + } + + #[test] + fn register_as_author() { + new_test_ext().execute_with(|| { + assert_ok!(test_benchmark_register_as_author::()); + }); + } + #[test] + fn leave_intent() { + new_test_ext().execute_with(|| { + assert_ok!(test_benchmark_leave_intent::()); + }); + } +} + +impl_benchmark_test_suite!(SimpleStaking, crate::mock::new_test_ext(), crate::mock::Test,); diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index ffd4cce..5af311b 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -106,7 +106,7 @@ impl pallet_aura::Config for Test { ord_parameter_types! { - pub const Three: u64 = 3; + pub const WhitelistedCaller: u64 = 15276289921735352792; } parameter_types! { pub const TreasuryAddress: u64 = 5; @@ -114,7 +114,7 @@ parameter_types! { impl Config for Test { type Event = Event; type Currency = Balances; - type UpdateOrigin = EnsureSignedBy; + type UpdateOrigin = EnsureSignedBy; type TreasuryAddress = TreasuryAddress; } diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 94c3cb9..be447b3 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -15,7 +15,7 @@ fn last_event() -> mock::Event { fn it_should_set_invulnerables() { new_test_ext().execute_with(|| { let new_handlers = vec![1, 2, 3, 4]; - assert_ok!(SimpleStaking::set_invulnerables(Origin::signed(3), new_handlers.clone())); + assert_ok!(SimpleStaking::set_invulnerables(Origin::signed(15276289921735352792), new_handlers.clone())); // assert_eq!( // last_event(), // mock::Event::simple_staking(crate::Event::NewInvulnerables(new_handlers.clone())), @@ -28,7 +28,7 @@ fn it_should_set_invulnerables() { #[test] fn set_max_author_count() { new_test_ext().execute_with(|| { - assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(3), 7)); + assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(15276289921735352792), 7)); assert_noop!(SimpleStaking::set_max_author_count(Origin::signed(1), 8), BadOrigin); assert_eq!(SimpleStaking::max_authors(), 7); }); @@ -37,7 +37,7 @@ fn set_max_author_count() { #[test] fn set_author_bond() { new_test_ext().execute_with(|| { - assert_ok!(SimpleStaking::set_author_bond(Origin::signed(3), 7)); + assert_ok!(SimpleStaking::set_author_bond(Origin::signed(15276289921735352792), 7)); assert_noop!(SimpleStaking::set_author_bond(Origin::signed(1), 8), BadOrigin); assert_eq!(SimpleStaking::author_bond(), 7); }); @@ -48,8 +48,8 @@ fn register_as_author() { new_test_ext().execute_with(|| { assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::MaxAuthors); - assert_ok!(SimpleStaking::set_author_bond(Origin::signed(3), 10)); - assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(3), 1)); + assert_ok!(SimpleStaking::set_author_bond(Origin::signed(15276289921735352792), 10)); + assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(15276289921735352792), 1)); assert_ok!(SimpleStaking::register_as_author(Origin::signed(1))); let addition = AuthorInfo { @@ -60,9 +60,9 @@ fn register_as_author() { assert_eq!(Balances::free_balance(1), 90); assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::MaxAuthors); - assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(3), 5)); + assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(15276289921735352792), 5)); assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::AlreadyAuthor); - assert_noop!(SimpleStaking::register_as_author(Origin::signed(3)), BalancesError::::InsufficientBalance); + assert_noop!(SimpleStaking::register_as_author(Origin::signed(15276289921735352792)), BalancesError::::InsufficientBalance); assert_eq!(SimpleStaking::authors(), vec![addition]); }); } @@ -70,10 +70,10 @@ fn register_as_author() { #[test] fn leave_intent() { new_test_ext().execute_with(|| { - assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(3), 1)); - assert_ok!(SimpleStaking::set_author_bond(Origin::signed(3), 10)); + assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(15276289921735352792), 1)); + assert_ok!(SimpleStaking::set_author_bond(Origin::signed(15276289921735352792), 10)); assert_ok!(SimpleStaking::register_as_author(Origin::signed(1))); - assert_noop!(SimpleStaking::leave_intent(Origin::signed(3)), Error::::NotAuthor); + assert_noop!(SimpleStaking::leave_intent(Origin::signed(15276289921735352792)), Error::::NotAuthor); assert_ok!(SimpleStaking::leave_intent(Origin::signed(1))); assert_eq!(SimpleStaking::authors(), vec![]); assert_eq!(Balances::free_balance(1), 100); From 30255bfe2ba34e084562fc2320c16f1019aac527 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Wed, 14 Apr 2021 14:52:45 +0200 Subject: [PATCH 27/56] kian and jesse --- Cargo.lock | 1 + pallets/simple-staking/Cargo.toml | 16 ++-- pallets/simple-staking/src/benchmarking.rs | 100 ++++++++------------- pallets/simple-staking/src/lib.rs | 70 +++++++++------ pallets/simple-staking/src/mock.rs | 4 +- pallets/simple-staking/src/tests.rs | 4 +- 6 files changed, 95 insertions(+), 100 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b191be0..d0f84af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4840,6 +4840,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "log", "pallet-aura", "pallet-authorship", "pallet-balances", diff --git a/pallets/simple-staking/Cargo.toml b/pallets/simple-staking/Cargo.toml index 812cdcb..0053d04 100644 --- a/pallets/simple-staking/Cargo.toml +++ b/pallets/simple-staking/Cargo.toml @@ -12,18 +12,16 @@ version = '3.0.0' [package.metadata.docs.rs] targets = ['x86_64-unknown-linux-gnu'] +[dependencies.log] +default-features = false +version = "0.4.0" + [dependencies.codec] default-features = false features = ['derive'] package = 'parity-scale-codec' version = '2.0.0' -[dependencies.pallet-balances] -default-features = false -git = 'https://github.com/paritytech/substrate.git' -branch = 'rococo-v1' -version = '3.0.0' - [dependencies.pallet-authorship] default-features = false git = 'https://github.com/paritytech/substrate.git' @@ -83,11 +81,17 @@ git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' version = '0.9.0' +[dev-dependencies.pallet-balances] +git = 'https://github.com/paritytech/substrate.git' +branch = 'rococo-v1' +version = '3.0.0' + [features] default = ['std'] runtime-benchmarks = ['frame-benchmarking'] std = [ 'codec/std', + 'log/std', 'frame-support/std', 'frame-system/std', 'frame-benchmarking/std', diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index bade365..c5e8bc7 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -4,12 +4,14 @@ use super::*; #[allow(unused)] use crate::Pallet as SimpleStaking; -use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller, Zero}; +use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller, Zero, account}; use frame_system::{RawOrigin, EventRecord}; use frame_support::{traits::Currency, dispatch::DispatchResult}; pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +const SEED: u32 = 0; + fn assert_last_event(generic_event: ::Event) { let events = frame_system::Module::::events(); let system_event: ::Event = generic_event.into(); @@ -18,21 +20,20 @@ fn assert_last_event(generic_event: ::Event) { assert_eq!(event, &system_event); } -fn set_authors(who: T::AccountId, deposit: BalanceOf) -> DispatchResult { - let addition = AuthorInfo { - who, - deposit, - last_block: None - }; - Authors::::try_mutate(|authors| -> DispatchResult { - authors.push(addition); - Ok(()) - }) +fn set_authors(authors: Vec, deposit: BalanceOf) { + for who in authors { + let junk_addition = AuthorInfo { + who, + deposit, + last_block: None + }; + Authors::::append(junk_addition); + } } benchmarks! { set_invulnerables { - let b in 1 .. 1000; + let b in 1 .. 1000; // T::MaxInvulenrables::get() let caller: T::AccountId = whitelisted_caller(); let new_invulnerables = vec![caller.clone(); b as usize]; @@ -42,83 +43,52 @@ benchmarks! { } set_max_author_count { - let b in 1 .. 1000; + let max: u32 = 999; let caller: T::AccountId = whitelisted_caller(); - }: _(RawOrigin::Signed(caller), b.clone()) + }: _(RawOrigin::Signed(caller), max.clone()) verify { - assert_last_event::(Event::NewMaxAuthorCount(b).into()); + assert_last_event::(Event::NewMaxAuthorCount(max).into()); } set_author_bond { - let b in 1 .. 1000; + let bond: BalanceOf = T::Currency::minimum_balance() * 10u32.into(); let caller: T::AccountId = whitelisted_caller(); - let new: BalanceOf = b.into(); - }: _(RawOrigin::Signed(caller), new.clone()) + }: _(RawOrigin::Signed(caller), bond.clone()) verify { - assert_last_event::(Event::NewAuthorBond(new).into()); + assert_last_event::(Event::NewAuthorBond(bond).into()); } register_as_author { + let c in 0 .. T::MaxAuthors::get(); + + let junk_account = account("junk", 0, SEED); let caller: T::AccountId = whitelisted_caller(); - SimpleStaking::::set_author_bond(RawOrigin::Signed(caller.clone()).into(), 10u32.into()); - SimpleStaking::::set_max_author_count(RawOrigin::Signed(caller.clone()).into(), 1); - T::Currency::make_free_balance_be(&caller, 100_000u32.into()); + let junk = vec![junk_account.clone(); c as usize]; + let bond: BalanceOf = T::Currency::minimum_balance() * 2u32.into(); + set_authors::(junk, bond); + >::put(T::Currency::minimum_balance()); + >::put(c + 1); + + T::Currency::make_free_balance_be(&caller, bond.clone()); }: _(RawOrigin::Signed(caller.clone())) verify { - assert_last_event::(Event::AuthorAdded(caller, 10u32.into()).into()); + assert_last_event::(Event::AuthorAdded(caller, bond).into()); } leave_intent { - let caller: T::AccountId = whitelisted_caller(); - set_authors::(caller.clone(), 10u32.into())?; + let c in 0 .. 1000; + let junk_account = account("junk", 0, SEED); + let caller: T::AccountId = whitelisted_caller(); + let junk = vec![junk_account.clone(); c as usize]; + set_authors::(caller.clone(), junk, 10u32.into()); }: _(RawOrigin::Signed(caller.clone())) verify { assert_last_event::(Event::AuthorRemoved(caller).into()); } } -#[cfg(test)] -mod tests { - use super::*; - use crate::mock::{new_test_ext, Test}; - use frame_support::assert_ok; - - #[test] - fn set_invulnerables() { - new_test_ext().execute_with(|| { - assert_ok!(test_benchmark_set_invulnerables::()); - }); - } - - #[test] - fn set_max_author_count() { - new_test_ext().execute_with(|| { - assert_ok!(test_benchmark_set_max_author_count::()); - }); - } - - #[test] - fn set_author_bond() { - new_test_ext().execute_with(|| { - assert_ok!(test_benchmark_set_author_bond::()); - }); - } - - #[test] - fn register_as_author() { - new_test_ext().execute_with(|| { - assert_ok!(test_benchmark_register_as_author::()); - }); - } - #[test] - fn leave_intent() { - new_test_ext().execute_with(|| { - assert_ok!(test_benchmark_leave_intent::()); - }); - } -} impl_benchmark_test_suite!(SimpleStaking, crate::mock::new_test_ext(), crate::mock::Test,); diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index c38fc2a..fcf52ea 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -21,7 +21,7 @@ pub mod pallet { use core::ops::{Div}; /// Configure the pallet by specifying the parameters and types on which it depends. #[pallet::config] - pub trait Config: frame_system::Config + authorship::Config { + pub trait Config: frame_system::Config { /// Because this pallet emits events, it depends on the runtime's definition of an event. type Event: From> + IsType<::Event>; /// The currency mechanism. @@ -30,17 +30,21 @@ pub mod pallet { type UpdateOrigin: EnsureOrigin; type TreasuryAddress: Get; + + /// Maximum number of authors that we should have. This is used for benchmarking and is not + /// enforced. + /// + /// This does not take into account the invulnerables. + type MaxAuthors: Get; } type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; - #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] pub struct AuthorInfo { pub who: AccountId, pub deposit: Balance, pub last_block: Option } - pub type AuthorInfoOf = AuthorInfo<::AccountId, ::AccountId>>::Balance, ::BlockNumber>; #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] @@ -58,8 +62,8 @@ pub mod pallet { pub type Authors = StorageValue<_, Vec, T::BlockNumber>>, ValueQuery>; #[pallet::storage] - #[pallet::getter(fn max_authors)] - pub type MaxAuthors = StorageValue<_, u32, ValueQuery>; + #[pallet::getter(fn allowed_authors)] + pub type AllowedAuthors = StorageValue<_, u32, ValueQuery>; #[pallet::storage] #[pallet::getter(fn author_bond)] @@ -87,6 +91,10 @@ pub mod pallet { impl GenesisBuild for GenesisConfig { fn build(&self) { >::put(&self.invulnerables); + assert!( + T::MaxAuthors::get() > >::get(), + "genesis allowed_authors are more than T::MaxAuthors", + ); } } @@ -97,7 +105,7 @@ pub mod pallet { /// Event documentation should end with an array that provides descriptive names for event /// parameters. [something, who] NewInvulnerables(Vec), - NewMaxAuthorCount(u32), + NewAllowedAuthorCount(u32), NewAuthorBond(BalanceOf), AuthorAdded(T::AccountId, BalanceOf), AuthorRemoved(T::AccountId) @@ -106,7 +114,7 @@ pub mod pallet { // Errors inform users that something went wrong. #[pallet::error] pub enum Error { - MaxAuthors, + TooManyAuthors, Unknown, Permission, AlreadyAuthor, @@ -114,25 +122,13 @@ pub mod pallet { } #[pallet::hooks] - impl Hooks> for Pallet { - fn on_initialize(_: T::BlockNumber) -> Weight { - let author = >::author(); - let treasury = T::TreasuryAddress::get(); - let reward = T::Currency::free_balance(&treasury).div(2u32.into()); - T::Currency::transfer(&treasury, &author, reward, KeepAlive); - // TODO double check: weight 3 reads (author, treasury, balance) 1 writes (transfer) - T::DbWeight::get().reads_writes(3, 1) - } - //TODO on init (or finalize) add to aura set at next era - } + impl Hooks> for Pallet {} // Dispatchable functions allows users to interact with the pallet and invoke state changes. // These functions materialize as "extrinsics", which are often compared to transactions. // Dispatchable functions must be annotated with a weight and must return a DispatchResult. #[pallet::call] impl Pallet { - - #[pallet::weight(10_000)] pub fn set_invulnerables(origin: OriginFor, new: Vec) -> DispatchResultWithPostInfo { T::UpdateOrigin::ensure_origin(origin)?; @@ -142,22 +138,24 @@ pub mod pallet { } #[pallet::weight(10_000)] - pub fn set_max_author_count(origin: OriginFor, max_authors: u32) -> DispatchResultWithPostInfo { + pub fn set_allowed_author_count(origin: OriginFor, allowed: u32) -> DispatchResultWithPostInfo { T::UpdateOrigin::ensure_origin(origin)?; - >::put(&max_authors); - Self::deposit_event(Event::NewMaxAuthorCount(max_authors)); + if allowed > T::MaxAuthors::get() { + log::warn!( + "allowed > T::MaxAuthors; you might need to run benchmarks again" + ); + } + >::put(&allowed); + Self::deposit_event(Event::NewAllowedAuthorCount(allowed)); Ok(().into()) - } - #[pallet::weight(10_000)] pub fn set_author_bond(origin: OriginFor, author_bond: BalanceOf) -> DispatchResultWithPostInfo { T::UpdateOrigin::ensure_origin(origin)?; >::put(&author_bond); Self::deposit_event(Event::NewAuthorBond(author_bond)); Ok(().into()) - } #[pallet::weight(10_000)] @@ -166,7 +164,7 @@ pub mod pallet { let who = ensure_signed(origin)?; let deposit = >::get(); let length = >::decode_len().unwrap_or_default(); - ensure!((length as u32) < MaxAuthors::::get(), Error::::MaxAuthors); + ensure!((length as u32) < Self::allowed_authors(), Error::::TooManyAuthors); let new_author = AuthorInfo { who: who.clone(), deposit, @@ -199,4 +197,22 @@ pub mod pallet { } } + + /// Keep track of number of authored blocks per authority, uncles are counted as + /// well since they're a valid proof of being online. + impl< + T: Config + pallet_authorship::Config, + > pallet_authorship::EventHandler for Pallet + { + fn note_author(author: T::AccountId) { + let treasury = T::TreasuryAddress::get(); + let reward = T::Currency::free_balance(&treasury).div(2u32.into()); + T::Currency::transfer(&treasury, &author, reward, KeepAlive); + // frame_system::Pallet::::register_extra_weight_unchecked(T::DbWeight::reads_writes()); + //Register the extra weight + } + fn note_uncle(_author: T::AccountId, _age: T::BlockNumber) { + //TODO can we ignore this? + } + } } diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index 5af311b..5b7bbaf 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -86,7 +86,7 @@ impl pallet_authorship::Config for Test { type FindAuthor = Author4; type UncleGenerations = (); type FilterUncle = (); - type EventHandler = (); + type EventHandler = (SimpleStaking); } parameter_types! { @@ -110,12 +110,14 @@ ord_parameter_types! { } parameter_types! { pub const TreasuryAddress: u64 = 5; + pub const MaxAuthors: u64 = 5; } impl Config for Test { type Event = Event; type Currency = Balances; type UpdateOrigin = EnsureSignedBy; type TreasuryAddress = TreasuryAddress; + type MaxAuthors = MaxAuthors; } pub fn new_test_ext() -> sp_io::TestExternalities { diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index be447b3..602cd26 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -83,7 +83,9 @@ fn leave_intent() { #[test] fn on_init() { new_test_ext().execute_with(|| { - SimpleStaking::on_initialize(1); + assert_eq!(Balances::free_balance(4), 0); + assert_eq!(Balances::free_balance(5), 100); + Authorship::on_initialize(1); assert_eq!(Balances::free_balance(4), 50); assert_eq!(Balances::free_balance(5), 50); }); From a43b75bd9977afb7ebb49b4f6b9885f7d6221d80 Mon Sep 17 00:00:00 2001 From: kianenigma Date: Wed, 14 Apr 2021 16:43:44 +0200 Subject: [PATCH 28/56] Make everything build --- Cargo.lock | 1 + pallets/simple-staking/Cargo.toml | 13 ++- pallets/simple-staking/src/benchmarking.rs | 122 ++++++++++++++------- pallets/simple-staking/src/lib.rs | 62 +++++++---- pallets/simple-staking/src/mock.rs | 19 ++-- pallets/simple-staking/src/tests.rs | 69 +++++++----- runtime/statemint/Cargo.toml | 7 +- runtime/statemint/src/lib.rs | 29 ++++- 8 files changed, 219 insertions(+), 103 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d0f84af..432f784 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4851,6 +4851,7 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", + "sp-std", ] [[package]] diff --git a/pallets/simple-staking/Cargo.toml b/pallets/simple-staking/Cargo.toml index 0053d04..e8c63da 100644 --- a/pallets/simple-staking/Cargo.toml +++ b/pallets/simple-staking/Cargo.toml @@ -47,6 +47,12 @@ git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' version = '3.0.0' +[dependencies.sp-std] +default-features = false +git = 'https://github.com/paritytech/substrate.git' +branch = 'rococo-v1' +version = '3.0.0' + [dependencies.serde] version = "1.0.119" default-features = false @@ -88,10 +94,15 @@ version = '3.0.0' [features] default = ['std'] -runtime-benchmarks = ['frame-benchmarking'] +runtime-benchmarks = [ + 'frame-benchmarking', + 'frame-support/runtime-benchmarks', + 'frame-system/runtime-benchmarks', +] std = [ 'codec/std', 'log/std', + 'sp-std/std', 'frame-support/std', 'frame-system/std', 'frame-benchmarking/std', diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index c5e8bc7..1e04af7 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -4,90 +4,132 @@ use super::*; #[allow(unused)] use crate::Pallet as SimpleStaking; -use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller, Zero, account}; +use sp_std::prelude::*; +use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller, account}; use frame_system::{RawOrigin, EventRecord}; -use frame_support::{traits::Currency, dispatch::DispatchResult}; +use frame_support::{ + assert_ok, + traits::{Currency, Get, EnsureOrigin}, +}; +use pallet_authorship::EventHandler; -pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +pub type BalanceOf = + <::Currency as Currency<::AccountId>>::Balance; const SEED: u32 = 0; +// TODO: remove if this is given in substrate commit. +macro_rules! whitelist { + ($acc:ident) => { + frame_benchmarking::benchmarking::add_to_whitelist( + frame_system::Account::::hashed_key_for(&$acc).into() + ); + }; +} + fn assert_last_event(generic_event: ::Event) { - let events = frame_system::Module::::events(); + let events = frame_system::Pallet::::events(); let system_event: ::Event = generic_event.into(); // compare to the last event record let EventRecord { event, .. } = &events[events.len() - 1]; assert_eq!(event, &system_event); } -fn set_authors(authors: Vec, deposit: BalanceOf) { +fn register_authors(count: u32) { + let authors = (0..count).map(|c| account("author", c, SEED)).collect::>(); + assert!(>::get() > 0u32.into(), "Bond cannot be zero!"); for who in authors { - let junk_addition = AuthorInfo { - who, - deposit, - last_block: None - }; - Authors::::append(junk_addition); + T::Currency::make_free_balance_be(&who, >::get() * 2u32.into()); + >::register_as_author(RawOrigin::Signed(who).into()).unwrap(); } } benchmarks! { - set_invulnerables { - let b in 1 .. 1000; // T::MaxInvulenrables::get() - let caller: T::AccountId = whitelisted_caller(); - let new_invulnerables = vec![caller.clone(); b as usize]; + where_clause { where T: pallet_authorship::Config } - }: _(RawOrigin::Signed(caller), new_invulnerables.clone()) + set_invulnerables { + let b in 1 .. T::MaxInvulenrables::get(); + let new_invulnerables = (0..b).map(|c| account("author", c, SEED)).collect::>(); + let origin = T::UpdateOrigin::successful_origin(); + // whitelist!(RootAccount); // TODO + }: { + assert_ok!( + >::set_invulnerables(origin, new_invulnerables.clone()) + ); + } verify { assert_last_event::(Event::NewInvulnerables(new_invulnerables).into()); } - set_max_author_count { + set_allowed_author_count { let max: u32 = 999; - let caller: T::AccountId = whitelisted_caller(); - - }: _(RawOrigin::Signed(caller), max.clone()) + let origin = T::UpdateOrigin::successful_origin(); + // whitelist!(caller); + }: { + assert_ok!( + >::set_allowed_author_count(origin, max.clone()) + ); + } verify { - assert_last_event::(Event::NewMaxAuthorCount(max).into()); + assert_last_event::(Event::NewAllowedAuthorCount(max).into()); } set_author_bond { let bond: BalanceOf = T::Currency::minimum_balance() * 10u32.into(); - let caller: T::AccountId = whitelisted_caller(); - - }: _(RawOrigin::Signed(caller), bond.clone()) + let origin = T::UpdateOrigin::successful_origin(); + // whitelist!(caller); + }: { + assert_ok!( + >::set_author_bond(origin, bond.clone()) + ); + } verify { assert_last_event::(Event::NewAuthorBond(bond).into()); } + // worse case is when we have all the max-author slots filled except one, and we fill that one. register_as_author { - let c in 0 .. T::MaxAuthors::get(); - - let junk_account = account("junk", 0, SEED); - let caller: T::AccountId = whitelisted_caller(); - let junk = vec![junk_account.clone(); c as usize]; - let bond: BalanceOf = T::Currency::minimum_balance() * 2u32.into(); - set_authors::(junk, bond); + let c in 1 .. T::MaxAuthors::get(); >::put(T::Currency::minimum_balance()); - >::put(c + 1); + >::put(c + 1); + register_authors::(c); + let caller: T::AccountId = whitelisted_caller(); + let bond: BalanceOf = T::Currency::minimum_balance() * 2u32.into(); T::Currency::make_free_balance_be(&caller, bond.clone()); + }: _(RawOrigin::Signed(caller.clone())) verify { - assert_last_event::(Event::AuthorAdded(caller, bond).into()); + assert_last_event::(Event::AuthorAdded(caller, bond / 2u32.into()).into()); } + // worse case is the last author leaving. leave_intent { - let c in 0 .. 1000; - let junk_account = account("junk", 0, SEED); + let c in 1 .. T::MaxAuthors::get(); + >::put(T::Currency::minimum_balance()); + >::put(c); + register_authors::(c); - let caller: T::AccountId = whitelisted_caller(); - let junk = vec![junk_account.clone(); c as usize]; - set_authors::(caller.clone(), junk, 10u32.into()); - }: _(RawOrigin::Signed(caller.clone())) + let leaving = >::get().last().unwrap().who.clone(); + whitelist!(leaving); + }: _(RawOrigin::Signed(leaving.clone())) verify { - assert_last_event::(Event::AuthorRemoved(caller).into()); + assert_last_event::(Event::AuthorRemoved(leaving).into()); + } + + // worse case is paying a non-existing author account. + note_author { + T::Currency::make_free_balance_be( + &T::TreasuryAddress::get(), + T::Currency::minimum_balance() * 2u32.into(), + ); + let author = account("author", 0, SEED); + assert!(T::Currency::free_balance(&author) == 0u32.into()); + }: { + as EventHandler<_, _>>::note_author(author.clone()) + } verify { + assert!(T::Currency::free_balance(&author) > 0u32.into()); } } diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index fcf52ea..a73b98e 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -8,17 +8,25 @@ mod mock; #[cfg(test)] mod tests; -#[cfg(any(feature = "runtime-benchmarks", test))] +#[cfg(feature = "runtime-benchmarks")] mod benchmarking; #[frame_support::pallet] pub mod pallet { - use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, inherent::Vec, traits::{Currency, ReservableCurrency, EnsureOrigin, ExistenceRequirement::{KeepAlive, AllowDeath}}}; - use frame_system::{pallet_prelude::*, ensure_root}; + use frame_support::{ + dispatch::DispatchResultWithPostInfo, + pallet_prelude::*, + inherent::Vec, + traits::{Currency, ReservableCurrency, EnsureOrigin, ExistenceRequirement::KeepAlive}, + }; + use frame_system::pallet_prelude::*; use frame_system::Config as SystemConfig; - use frame_support::sp_runtime::{RuntimeDebug}; - use pallet_authorship as authorship; - use core::ops::{Div}; + use frame_support::{ + sp_runtime::{RuntimeDebug}, + weights::DispatchClass, + }; + use core::ops::Div; + /// Configure the pallet by specifying the parameters and types on which it depends. #[pallet::config] pub trait Config: frame_system::Config { @@ -36,14 +44,21 @@ pub mod pallet { /// /// This does not take into account the invulnerables. type MaxAuthors: Get; + + /// Maximum number of invulnerables. + /// + /// Used only for benchmarking. + type MaxInvulenrables: Get; } - type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; + + type BalanceOf = + <::Currency as Currency<::AccountId>>::Balance; #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] pub struct AuthorInfo { pub who: AccountId, pub deposit: Balance, - pub last_block: Option + pub last_block: Option, } #[pallet::pallet] @@ -90,11 +105,11 @@ pub mod pallet { #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { fn build(&self) { - >::put(&self.invulnerables); assert!( - T::MaxAuthors::get() > >::get(), - "genesis allowed_authors are more than T::MaxAuthors", + T::MaxInvulenrables::get() > (self.invulnerables.len() as u32), + "genesis invulnerables are more than T::MaxInvulenrables", ); + >::put(&self.invulnerables); } } @@ -130,8 +145,16 @@ pub mod pallet { #[pallet::call] impl Pallet { #[pallet::weight(10_000)] - pub fn set_invulnerables(origin: OriginFor, new: Vec) -> DispatchResultWithPostInfo { + pub fn set_invulnerables( + origin: OriginFor, + new: Vec, + ) -> DispatchResultWithPostInfo { T::UpdateOrigin::ensure_origin(origin)?; + if (new.len() as u32) > T::MaxInvulenrables::get() { + log::warn!( + "invulnerables > T::MaxInvulenrables; you might need to run benchmarks again" + ); + } >::put(&new); Self::deposit_event(Event::NewInvulnerables(new)); Ok(().into()) @@ -194,22 +217,23 @@ pub mod pallet { })?; Self::deposit_event(Event::AuthorRemoved(who)); Ok(().into()) - } } /// Keep track of number of authored blocks per authority, uncles are counted as /// well since they're a valid proof of being online. - impl< - T: Config + pallet_authorship::Config, - > pallet_authorship::EventHandler for Pallet + impl + pallet_authorship::EventHandler for Pallet { fn note_author(author: T::AccountId) { let treasury = T::TreasuryAddress::get(); let reward = T::Currency::free_balance(&treasury).div(2u32.into()); - T::Currency::transfer(&treasury, &author, reward, KeepAlive); - // frame_system::Pallet::::register_extra_weight_unchecked(T::DbWeight::reads_writes()); - //Register the extra weight + + // `reward` is half of treasury account, this should never fail. + let _success = T::Currency::transfer(&treasury, &author, reward, KeepAlive); + debug_assert!(_success.is_ok()); + + frame_system::Pallet::::register_extra_weight_unchecked(0, DispatchClass::Mandatory); } fn note_uncle(_author: T::AccountId, _age: T::BlockNumber) { //TODO can we ignore this? diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index 5b7bbaf..94db98f 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -1,9 +1,13 @@ use super::*; use crate as simple_staking; use sp_core::H256; -use frame_support::{parameter_types, ord_parameter_types, traits::{FindAuthor, GenesisBuild}}; +use frame_support::{ + parameter_types, ord_parameter_types, + traits::{FindAuthor, GenesisBuild}, +}; use sp_runtime::{ - traits::{BlakeTwo256, IdentityLookup}, testing::{Header, UintAuthorityId}, + traits::{BlakeTwo256, IdentityLookup}, + testing::{Header}, }; use sp_consensus_aura::sr25519::AuthorityId; use frame_system::{EnsureSignedBy}; @@ -86,7 +90,7 @@ impl pallet_authorship::Config for Test { type FindAuthor = Author4; type UncleGenerations = (); type FilterUncle = (); - type EventHandler = (SimpleStaking); + type EventHandler = SimpleStaking; } parameter_types! { @@ -104,20 +108,21 @@ impl pallet_aura::Config for Test { type AuthorityId = AuthorityId; } - ord_parameter_types! { - pub const WhitelistedCaller: u64 = 15276289921735352792; + pub const RootAccount: u64 = 777; } parameter_types! { pub const TreasuryAddress: u64 = 5; - pub const MaxAuthors: u64 = 5; + pub const MaxAuthors: u32 = 20; + pub const MaxInvulenrables: u32 = 20; } impl Config for Test { type Event = Event; type Currency = Balances; - type UpdateOrigin = EnsureSignedBy; + type UpdateOrigin = EnsureSignedBy; type TreasuryAddress = TreasuryAddress; type MaxAuthors = MaxAuthors; + type MaxInvulenrables = MaxInvulenrables; } pub fn new_test_ext() -> sp_io::TestExternalities { diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 602cd26..58b5b54 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -1,43 +1,37 @@ -use super::*; use crate::{mock::*, Error, AuthorInfo}; use frame_support::{assert_noop, assert_ok, traits::OnInitialize}; -use super::Event as StakingEvent; use sp_runtime::traits::BadOrigin; -use frame_system::EventRecord; use pallet_balances::Error as BalancesError; - -fn last_event() -> mock::Event { - frame_system::Pallet::::events().pop().expect("Event expected").event -} - #[test] fn it_should_set_invulnerables() { new_test_ext().execute_with(|| { let new_handlers = vec![1, 2, 3, 4]; - assert_ok!(SimpleStaking::set_invulnerables(Origin::signed(15276289921735352792), new_handlers.clone())); - // assert_eq!( - // last_event(), - // mock::Event::simple_staking(crate::Event::NewInvulnerables(new_handlers.clone())), - // ); - assert_noop!(SimpleStaking::set_invulnerables(Origin::signed(1), new_handlers.clone()), BadOrigin); + assert_ok!(SimpleStaking::set_invulnerables( + Origin::signed(RootAccount::get()), + new_handlers.clone() + )); + assert_noop!( + SimpleStaking::set_invulnerables(Origin::signed(1), new_handlers.clone()), + BadOrigin + ); assert_eq!(SimpleStaking::invulnerables(), new_handlers); }); } #[test] -fn set_max_author_count() { +fn set_allowed_author_count() { new_test_ext().execute_with(|| { - assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(15276289921735352792), 7)); - assert_noop!(SimpleStaking::set_max_author_count(Origin::signed(1), 8), BadOrigin); - assert_eq!(SimpleStaking::max_authors(), 7); + assert_ok!(SimpleStaking::set_allowed_author_count(Origin::signed(RootAccount::get()), 7)); + assert_noop!(SimpleStaking::set_allowed_author_count(Origin::signed(1), 8), BadOrigin); + assert_eq!(SimpleStaking::allowed_authors(), 7); }); } #[test] fn set_author_bond() { new_test_ext().execute_with(|| { - assert_ok!(SimpleStaking::set_author_bond(Origin::signed(15276289921735352792), 7)); + assert_ok!(SimpleStaking::set_author_bond(Origin::signed(RootAccount::get()), 7)); assert_noop!(SimpleStaking::set_author_bond(Origin::signed(1), 8), BadOrigin); assert_eq!(SimpleStaking::author_bond(), 7); }); @@ -46,10 +40,13 @@ fn set_author_bond() { #[test] fn register_as_author() { new_test_ext().execute_with(|| { - assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::MaxAuthors); + assert_noop!( + SimpleStaking::register_as_author(Origin::signed(1)), + Error::::TooManyAuthors + ); - assert_ok!(SimpleStaking::set_author_bond(Origin::signed(15276289921735352792), 10)); - assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(15276289921735352792), 1)); + assert_ok!(SimpleStaking::set_author_bond(Origin::signed(RootAccount::get()), 10)); + assert_ok!(SimpleStaking::set_allowed_author_count(Origin::signed(RootAccount::get()), 1)); assert_ok!(SimpleStaking::register_as_author(Origin::signed(1))); let addition = AuthorInfo { @@ -58,11 +55,20 @@ fn register_as_author() { last_block: None }; assert_eq!(Balances::free_balance(1), 90); - assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::MaxAuthors); + assert_noop!( + SimpleStaking::register_as_author(Origin::signed(1)), + Error::::TooManyAuthors + ); - assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(15276289921735352792), 5)); - assert_noop!(SimpleStaking::register_as_author(Origin::signed(1)), Error::::AlreadyAuthor); - assert_noop!(SimpleStaking::register_as_author(Origin::signed(15276289921735352792)), BalancesError::::InsufficientBalance); + assert_ok!(SimpleStaking::set_allowed_author_count(Origin::signed(RootAccount::get()), 5)); + assert_noop!( + SimpleStaking::register_as_author(Origin::signed(1)), + Error::::AlreadyAuthor + ); + assert_noop!( + SimpleStaking::register_as_author(Origin::signed(RootAccount::get())), + BalancesError::::InsufficientBalance + ); assert_eq!(SimpleStaking::authors(), vec![addition]); }); } @@ -70,10 +76,13 @@ fn register_as_author() { #[test] fn leave_intent() { new_test_ext().execute_with(|| { - assert_ok!(SimpleStaking::set_max_author_count(Origin::signed(15276289921735352792), 1)); - assert_ok!(SimpleStaking::set_author_bond(Origin::signed(15276289921735352792), 10)); + assert_ok!(SimpleStaking::set_allowed_author_count(Origin::signed(RootAccount::get()), 1)); + assert_ok!(SimpleStaking::set_author_bond(Origin::signed(RootAccount::get()), 10)); assert_ok!(SimpleStaking::register_as_author(Origin::signed(1))); - assert_noop!(SimpleStaking::leave_intent(Origin::signed(15276289921735352792)), Error::::NotAuthor); + assert_noop!( + SimpleStaking::leave_intent(Origin::signed(RootAccount::get())), + Error::::NotAuthor + ); assert_ok!(SimpleStaking::leave_intent(Origin::signed(1))); assert_eq!(SimpleStaking::authors(), vec![]); assert_eq!(Balances::free_balance(1), 100); @@ -97,4 +106,4 @@ fn on_genesis() { assert_eq!(SimpleStaking::invulnerables(), vec![1,2,3]); assert_eq!(SimpleStaking::invulnerables().len(), 3); }); -} \ No newline at end of file +} diff --git a/runtime/statemint/Cargo.toml b/runtime/statemint/Cargo.toml index 4af500c..7c990b6 100644 --- a/runtime/statemint/Cargo.toml +++ b/runtime/statemint/Cargo.toml @@ -259,9 +259,8 @@ git = 'https://github.com/paritytech/polkadot' branch = 'rococo-v1' default-features = false -[dependencies.simple-staking] +[dependencies.pallet-simple-staking] default-features = false -package = 'pallet-simple-staking' path = '../../pallets/simple-staking' [dependencies.runtime-common] @@ -280,7 +279,7 @@ runtime-benchmarks = [ 'frame-system/runtime-benchmarks', 'pallet-balances/runtime-benchmarks', 'pallet-timestamp/runtime-benchmarks', - 'simple-staking/runtime-benchmarks', + 'pallet-simple-staking/runtime-benchmarks', ] std = [ 'codec/std', @@ -323,5 +322,5 @@ std = [ 'polkadot-runtime-common/std', 'runtime-common/std', 'polkadot-primitives/std', - 'simple-staking/std', + 'pallet-simple-staking/std', ] diff --git a/runtime/statemint/src/lib.rs b/runtime/statemint/src/lib.rs index 39b5d50..68820d3 100644 --- a/runtime/statemint/src/lib.rs +++ b/runtime/statemint/src/lib.rs @@ -28,7 +28,7 @@ pub mod constants; use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::traits::{ - AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify, + AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify, AccountIdConversion, }; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, @@ -543,6 +543,29 @@ impl cumulus_pallet_xcm_handler::Config for Runtime { type AccountIdConverter = LocationConverter; } +parameter_types! { + pub const TreasuryAddress: u64 = 5; + pub const MaxAuthors: u32 = 1000; + pub const MaxInvulenrables: u32 = 100; +} + +frame_support::ord_parameter_types! { + pub const RelayChainCouncilOrigin: AccountId = < + sp_runtime::ModuleId + as + AccountIdConversion + >::into_account(&sp_runtime::ModuleId(*b"TODOTODO")); +} + +impl pallet_simple_staking::Config for Runtime { + type Event = Event; + type Currency = Balances; + type UpdateOrigin = frame_system::EnsureSignedBy; + type TreasuryAddress = (); // Needs to be some random inaccessible account. (`ModuleId`) + type MaxAuthors = MaxAuthors; + type MaxInvulenrables = MaxInvulenrables; +} + // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( pub enum Runtime where @@ -564,6 +587,7 @@ construct_runtime!( Multisig: pallet_multisig::{Pallet, Call, Storage, Event}, Utility: pallet_utility::{Pallet, Call, Event}, Proxy: pallet_proxy::{Pallet, Call, Storage, Event}, + SimpleStaking: pallet_simple_staking::{Pallet, Call, Storage, Event, Config}, } ); @@ -701,7 +725,7 @@ impl_runtime_apis! { ) -> Result, sp_runtime::RuntimeString> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey}; - use frame_system_benchmarking::Module as SystemBench; + use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime {} let whitelist: Vec = vec![ @@ -723,6 +747,7 @@ impl_runtime_apis! { add_benchmark!(params, batches, frame_system, SystemBench::); add_benchmark!(params, batches, pallet_balances, Balances); add_benchmark!(params, batches, pallet_timestamp, Timestamp); + add_benchmark!(params, batches, pallet_simple_staking, SimpleStaking); if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } Ok(batches) From fae7a578f5285654ada629419b6fb8abfc8e9465 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Thu, 15 Apr 2021 16:09:02 +0200 Subject: [PATCH 29/56] add invulnerables to chain spec --- node/src/chain_spec.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/node/src/chain_spec.rs b/node/src/chain_spec.rs index ff3aad1..468b3fb 100644 --- a/node/src/chain_spec.rs +++ b/node/src/chain_spec.rs @@ -124,8 +124,9 @@ fn statemint_testnet_genesis( .map(|k| (k, 1 << 60)) .collect(), }, - pallet_sudo: statemint_runtime::SudoConfig { key: root_key }, + pallet_sudo: statemint_runtime::SudoConfig { key: root_key.clone() }, parachain_info: statemint_runtime::ParachainInfoConfig { parachain_id: id }, + pallet_simple_staking: statemint_runtime::SimpleStakingConfig { invulnerables: vec![root_key] }, } } From 3b2a6e36d767803a2898ef7f970c307497096403 Mon Sep 17 00:00:00 2001 From: Alexander Popiak Date: Thu, 15 Apr 2021 16:34:14 +0200 Subject: [PATCH 30/56] Update pallets/simple-staking/src/lib.rs Co-authored-by: joe petrowski <25483142+joepetrowski@users.noreply.github.com> --- pallets/simple-staking/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index a73b98e..5e544dc 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -150,7 +150,7 @@ pub mod pallet { new: Vec, ) -> DispatchResultWithPostInfo { T::UpdateOrigin::ensure_origin(origin)?; - if (new.len() as u32) > T::MaxInvulenrables::get() { + if (new.len() as u32) > T::MaxInvulnerables::get() { log::warn!( "invulnerables > T::MaxInvulenrables; you might need to run benchmarks again" ); From a5237371b172f076bf9f8f45c3289cd6a1ac1682 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Thu, 15 Apr 2021 17:32:22 +0200 Subject: [PATCH 31/56] configs and runtime, transaction payment --- Cargo.lock | 2 +- node/src/chain_spec.rs | 3 ++- pallets/simple-staking/src/lib.rs | 22 ++++++++++++++------- pallets/simple-staking/src/mock.rs | 10 +++++----- pallets/simple-staking/src/tests.rs | 7 ++++--- runtime/common/Cargo.toml | 8 ++++---- runtime/common/src/impls.rs | 10 +++++----- runtime/statemine/Cargo.toml | 7 +++---- runtime/statemine/src/lib.rs | 30 ++++++++++++++++++++++++++--- runtime/statemint/src/lib.rs | 10 +++++----- 10 files changed, 71 insertions(+), 38 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f671701..c5e76d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7127,8 +7127,8 @@ dependencies = [ "frame-support", "frame-system", "node-primitives", - "pallet-authorship", "pallet-balances", + "pallet-simple-staking", "parity-scale-codec", "polkadot-primitives", "polkadot-runtime-common", diff --git a/node/src/chain_spec.rs b/node/src/chain_spec.rs index 468b3fb..7205cc7 100644 --- a/node/src/chain_spec.rs +++ b/node/src/chain_spec.rs @@ -220,7 +220,8 @@ fn statemine_testnet_genesis( .map(|k| (k, 1 << 60)) .collect(), }, - pallet_sudo: statemine_runtime::SudoConfig { key: root_key }, + pallet_sudo: statemine_runtime::SudoConfig { key: root_key.clone() }, parachain_info: statemine_runtime::ParachainInfoConfig { parachain_id: id }, + pallet_simple_staking: statemine_runtime::SimpleStakingConfig { invulnerables: vec![root_key] }, } } diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 5e544dc..c614a13 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -18,15 +18,17 @@ pub mod pallet { pallet_prelude::*, inherent::Vec, traits::{Currency, ReservableCurrency, EnsureOrigin, ExistenceRequirement::KeepAlive}, + PalletId }; use frame_system::pallet_prelude::*; use frame_system::Config as SystemConfig; use frame_support::{ - sp_runtime::{RuntimeDebug}, + sp_runtime::{RuntimeDebug, traits::{AccountIdConversion}}, weights::DispatchClass, }; use core::ops::Div; + /// Configure the pallet by specifying the parameters and types on which it depends. #[pallet::config] pub trait Config: frame_system::Config { @@ -37,7 +39,7 @@ pub mod pallet { type UpdateOrigin: EnsureOrigin; - type TreasuryAddress: Get; + type TreasuryId: Get; /// Maximum number of authors that we should have. This is used for benchmarking and is not /// enforced. @@ -48,7 +50,7 @@ pub mod pallet { /// Maximum number of invulnerables. /// /// Used only for benchmarking. - type MaxInvulenrables: Get; + type MaxInvulnerables: Get; } type BalanceOf = @@ -106,8 +108,8 @@ pub mod pallet { impl GenesisBuild for GenesisConfig { fn build(&self) { assert!( - T::MaxInvulenrables::get() > (self.invulnerables.len() as u32), - "genesis invulnerables are more than T::MaxInvulenrables", + T::MaxInvulnerables::get() > (self.invulnerables.len() as u32), + "genesis invulnerables are more than T::MaxInvulnerables", ); >::put(&self.invulnerables); } @@ -152,7 +154,7 @@ pub mod pallet { T::UpdateOrigin::ensure_origin(origin)?; if (new.len() as u32) > T::MaxInvulnerables::get() { log::warn!( - "invulnerables > T::MaxInvulenrables; you might need to run benchmarks again" + "invulnerables > T::MaxInvulnerables; you might need to run benchmarks again" ); } >::put(&new); @@ -220,13 +222,19 @@ pub mod pallet { } } + impl Pallet { + pub fn account_id() -> T::AccountId { + T::TreasuryId::get().into_account() + } + } + /// Keep track of number of authored blocks per authority, uncles are counted as /// well since they're a valid proof of being online. impl pallet_authorship::EventHandler for Pallet { fn note_author(author: T::AccountId) { - let treasury = T::TreasuryAddress::get(); + let treasury = Self::account_id(); let reward = T::Currency::free_balance(&treasury).div(2u32.into()); // `reward` is half of treasury account, this should never fail. diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index 94db98f..715f4b9 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -4,6 +4,7 @@ use sp_core::H256; use frame_support::{ parameter_types, ord_parameter_types, traits::{FindAuthor, GenesisBuild}, + PalletId }; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -112,17 +113,17 @@ ord_parameter_types! { pub const RootAccount: u64 = 777; } parameter_types! { - pub const TreasuryAddress: u64 = 5; + pub const TreasuryId: PalletId = PalletId(*b"Treasury"); pub const MaxAuthors: u32 = 20; - pub const MaxInvulenrables: u32 = 20; + pub const MaxInvulnerables: u32 = 20; } impl Config for Test { type Event = Event; type Currency = Balances; type UpdateOrigin = EnsureSignedBy; - type TreasuryAddress = TreasuryAddress; + type TreasuryId = TreasuryId; type MaxAuthors = MaxAuthors; - type MaxInvulenrables = MaxInvulenrables; + type MaxInvulnerables = MaxInvulnerables; } pub fn new_test_ext() -> sp_io::TestExternalities { @@ -131,7 +132,6 @@ pub fn new_test_ext() -> sp_io::TestExternalities { balances: vec![ (1, 100), (2, 200), - (5, 100), ], }; let genesis_staking = simple_staking::GenesisConfig:: { diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 58b5b54..799bf83 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -1,5 +1,5 @@ use crate::{mock::*, Error, AuthorInfo}; -use frame_support::{assert_noop, assert_ok, traits::OnInitialize}; +use frame_support::{assert_noop, assert_ok, traits::{OnInitialize, Currency}}; use sp_runtime::traits::BadOrigin; use pallet_balances::Error as BalancesError; @@ -92,11 +92,12 @@ fn leave_intent() { #[test] fn on_init() { new_test_ext().execute_with(|| { + Balances::make_free_balance_be(&SimpleStaking::account_id(), 100); assert_eq!(Balances::free_balance(4), 0); - assert_eq!(Balances::free_balance(5), 100); + assert_eq!(Balances::free_balance(SimpleStaking::account_id()), 100); Authorship::on_initialize(1); assert_eq!(Balances::free_balance(4), 50); - assert_eq!(Balances::free_balance(5), 50); + assert_eq!(Balances::free_balance(SimpleStaking::account_id()), 50); }); } diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index 8f0e134..7fb90ac 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -74,10 +74,9 @@ git = 'https://github.com/paritytech/polkadot' branch = 'rococo-v1' default-features = false -[dependencies.pallet-authorship] +[dependencies.pallet-simple-staking] default-features = false -git = 'https://github.com/paritytech/substrate.git' -branch = 'rococo-v1' +path = '../../pallets/simple-staking' [dev-dependencies] serde = { version = "1.0.119" } @@ -106,10 +105,11 @@ std = [ 'codec/std', 'sp-std/std', 'sp-io/std', + 'sp-runtime/std', 'frame-support/std', 'frame-executive/std', 'frame-system/std', - 'pallet-authorship/std', + 'pallet-simple-staking/std', 'pallet-balances/std', 'node-primitives/std', 'polkadot-runtime-common/std', diff --git a/runtime/common/src/impls.rs b/runtime/common/src/impls.rs index 2b91e45..032839b 100644 --- a/runtime/common/src/impls.rs +++ b/runtime/common/src/impls.rs @@ -24,20 +24,20 @@ pub type NegativeImbalance = as Currency<(sp_std::marker::PhantomData); impl OnUnbalanced> for ToAuthor where - R: pallet_balances::Config + pallet_authorship::Config, + R: pallet_balances::Config + pallet_simple_staking::Config, ::AccountId: From, ::AccountId: Into, ::Event: From>, { fn on_nonzero_unbalanced(amount: NegativeImbalance) { let numeric_amount = amount.peek(); - let author = >::author(); + let treasury = >::account_id(); >::resolve_creating( - &>::author(), + &treasury, amount, ); >::deposit_event(pallet_balances::Event::Deposit( - author, + treasury, numeric_amount, )); } @@ -46,7 +46,7 @@ where pub struct DealWithFees(sp_std::marker::PhantomData); impl OnUnbalanced> for DealWithFees where - R: pallet_balances::Config + pallet_authorship::Config, + R: pallet_balances::Config + pallet_simple_staking::Config, ::AccountId: From, ::AccountId: Into, ::Event: From>, diff --git a/runtime/statemine/Cargo.toml b/runtime/statemine/Cargo.toml index b0bd530..50dd723 100644 --- a/runtime/statemine/Cargo.toml +++ b/runtime/statemine/Cargo.toml @@ -274,9 +274,8 @@ git = 'https://github.com/paritytech/polkadot' branch = 'rococo-v1' default-features = false -[dependencies.simple-staking] +[dependencies.pallet-simple-staking] default-features = false -package = 'pallet-simple-staking' path = '../../pallets/simple-staking' [dependencies.runtime-common] @@ -295,7 +294,7 @@ runtime-benchmarks = [ 'frame-system/runtime-benchmarks', 'pallet-balances/runtime-benchmarks', 'pallet-timestamp/runtime-benchmarks', - 'simple-staking/runtime-benchmarks', + 'pallet-simple-staking/runtime-benchmarks', ] std = [ 'codec/std', @@ -341,5 +340,5 @@ std = [ 'polkadot-runtime-common/std', 'runtime-common/std', 'polkadot-primitives/std', - 'simple-staking/std', + 'pallet-simple-staking/std', ] diff --git a/runtime/statemine/src/lib.rs b/runtime/statemine/src/lib.rs index 906e4b4..3c9404b 100644 --- a/runtime/statemine/src/lib.rs +++ b/runtime/statemine/src/lib.rs @@ -28,7 +28,7 @@ pub mod constants; use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::traits::{ - AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify, + AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify, AccountIdConversion }; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, @@ -70,7 +70,7 @@ pub use frame_support::{ constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_SECOND}, DispatchClass, IdentityFee, Weight, }, - RuntimeDebug, StorageValue, + RuntimeDebug, StorageValue, PalletId }; use runtime_common::impls::DealWithFees; pub use pallet_balances::Call as BalancesCall; @@ -611,6 +611,29 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { type ChannelInfo = ParachainSystem; } +parameter_types! { + pub const TreasuryId: PalletId = PalletId(*b"Treasury"); + pub const MaxAuthors: u32 = 1000; + pub const MaxInvulnerables: u32 = 100; +} + +frame_support::ord_parameter_types! { + pub const RelayChainCouncilOrigin: AccountId = < + frame_support::PalletId + as + AccountIdConversion + >::into_account(&frame_support::PalletId(*b"TODOTODO")); +} + +impl pallet_simple_staking::Config for Runtime { + type Event = Event; + type Currency = Balances; + type UpdateOrigin = frame_system::EnsureSignedBy; + type TreasuryId = TreasuryId; // Needs to be some random inaccessible account. (`ModuleId`) + type MaxAuthors = MaxAuthors; + type MaxInvulnerables = MaxInvulnerables; +} + // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( pub enum Runtime where @@ -631,7 +654,7 @@ construct_runtime!( Multisig: pallet_multisig::{Pallet, Call, Storage, Event}, Utility: pallet_utility::{Pallet, Call, Event}, Proxy: pallet_proxy::{Pallet, Call, Storage, Event}, - + SimpleStaking: pallet_simple_staking::{Pallet, Call, Storage, Event, Config}, // XCM helpers. XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event}, PolkadotXcm: pallet_xcm::{Pallet, Call, Event, Origin}, @@ -795,6 +818,7 @@ impl_runtime_apis! { add_benchmark!(params, batches, frame_system, SystemBench::); add_benchmark!(params, batches, pallet_balances, Balances); add_benchmark!(params, batches, pallet_timestamp, Timestamp); + add_benchmark!(params, batches, pallet_simple_staking, SimpleStaking); if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } Ok(batches) diff --git a/runtime/statemint/src/lib.rs b/runtime/statemint/src/lib.rs index 83c3ba5..9c3dd06 100644 --- a/runtime/statemint/src/lib.rs +++ b/runtime/statemint/src/lib.rs @@ -70,7 +70,7 @@ pub use frame_support::{ constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_SECOND}, DispatchClass, IdentityFee, Weight, }, - RuntimeDebug, StorageValue, + RuntimeDebug, StorageValue, PalletId }; use runtime_common::impls::DealWithFees; pub use pallet_balances::Call as BalancesCall; @@ -612,9 +612,9 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { } parameter_types! { - pub const TreasuryAddress: u64 = 5; + pub const TreasuryId: PalletId = PalletId(*b"Treasury"); pub const MaxAuthors: u32 = 1000; - pub const MaxInvulenrables: u32 = 100; + pub const MaxInvulnerables: u32 = 100; } frame_support::ord_parameter_types! { @@ -629,9 +629,9 @@ impl pallet_simple_staking::Config for Runtime { type Event = Event; type Currency = Balances; type UpdateOrigin = frame_system::EnsureSignedBy; - type TreasuryAddress = (); // Needs to be some random inaccessible account. (`ModuleId`) + type TreasuryId = TreasuryId; // Needs to be some random inaccessible account. (`ModuleId`) type MaxAuthors = MaxAuthors; - type MaxInvulenrables = MaxInvulenrables; + type MaxInvulnerables = MaxInvulnerables; } // Create the runtime by composing the FRAME pallets that were previously configured. From bbaf6f69c491ebe593ab9624f2b8b189bc0003a9 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Thu, 15 Apr 2021 17:36:30 +0200 Subject: [PATCH 32/56] changes on joe's recommendation --- pallets/simple-staking/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index c614a13..92b1fc2 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -108,7 +108,7 @@ pub mod pallet { impl GenesisBuild for GenesisConfig { fn build(&self) { assert!( - T::MaxInvulnerables::get() > (self.invulnerables.len() as u32), + T::MaxInvulnerables::get() >= (self.invulnerables.len() as u32), "genesis invulnerables are more than T::MaxInvulnerables", ); >::put(&self.invulnerables); @@ -152,6 +152,7 @@ pub mod pallet { new: Vec, ) -> DispatchResultWithPostInfo { T::UpdateOrigin::ensure_origin(origin)?; + // we trust origin calls, this is just a for more accurate benchmarking if (new.len() as u32) > T::MaxInvulnerables::get() { log::warn!( "invulnerables > T::MaxInvulnerables; you might need to run benchmarks again" @@ -165,6 +166,7 @@ pub mod pallet { #[pallet::weight(10_000)] pub fn set_allowed_author_count(origin: OriginFor, allowed: u32) -> DispatchResultWithPostInfo { T::UpdateOrigin::ensure_origin(origin)?; + // we trust origin calls, this is just a for more accurate benchmarking if allowed > T::MaxAuthors::get() { log::warn!( "allowed > T::MaxAuthors; you might need to run benchmarks again" From 13717abf78292bb6c8b3657411516034c03a1230 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Fri, 16 Apr 2021 09:47:37 +0200 Subject: [PATCH 33/56] Update pallets/simple-staking/src/benchmarking.rs Co-authored-by: Alan Sapede --- pallets/simple-staking/src/benchmarking.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index 1e04af7..0620df2 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -48,7 +48,7 @@ benchmarks! { where_clause { where T: pallet_authorship::Config } set_invulnerables { - let b in 1 .. T::MaxInvulenrables::get(); + let b in 1 .. T::MaxInvulnerables::get(); let new_invulnerables = (0..b).map(|c| account("author", c, SEED)).collect::>(); let origin = T::UpdateOrigin::successful_origin(); // whitelist!(RootAccount); // TODO From e9ffb9845032be39b43ed5049022e3dccd935ad9 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Fri, 16 Apr 2021 17:31:11 +0200 Subject: [PATCH 34/56] weights (not done) --- Cargo.lock | 76 ++++++++++++++++++- node/Cargo.toml | 14 ++-- node/src/cli.rs | 4 + node/src/command.rs | 11 +++ node/src/service.rs | 1 + pallets/simple-staking/src/benchmarking.rs | 2 +- pallets/simple-staking/src/lib.rs | 52 ++++++++++++- pallets/simple-staking/src/mock.rs | 1 + runtime/common/Cargo.toml | 3 - runtime/statemine/Cargo.toml | 14 +++- runtime/statemine/src/lib.rs | 14 +++- runtime/statemine/src/weights/mod.rs | 1 + .../src/weights/pallet_simple_staking.rs | 72 ++++++++++++++++++ runtime/statemint/Cargo.toml | 16 ++-- runtime/statemint/src/lib.rs | 11 ++- runtime/statemint/src/weights/mod.rs | 1 + .../src/weights/pallet_simple_staking.rs | 72 ++++++++++++++++++ 17 files changed, 337 insertions(+), 28 deletions(-) create mode 100644 runtime/statemine/src/weights/mod.rs create mode 100644 runtime/statemine/src/weights/pallet_simple_staking.rs create mode 100644 runtime/statemint/src/weights/mod.rs create mode 100644 runtime/statemint/src/weights/pallet_simple_staking.rs diff --git a/Cargo.lock b/Cargo.lock index c5e76d2..71d3250 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3209,11 +3209,14 @@ source = "git+https://github.com/paritytech/polkadot?branch=rococo-v1#943038a888 dependencies = [ "beefy-primitives", "bitvec", + "frame-benchmarking", "frame-executive", "frame-support", "frame-system", + "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", + "hex-literal 0.3.1", "log", "pallet-authority-discovery", "pallet-authorship", @@ -3233,11 +3236,13 @@ dependencies = [ "pallet-multisig", "pallet-nicks", "pallet-offences", + "pallet-offences-benchmarking", "pallet-proxy", "pallet-randomness-collective-flip", "pallet-recovery", "pallet-scheduler", "pallet-session", + "pallet-session-benchmarking", "pallet-society", "pallet-staking", "pallet-staking-reward-curve", @@ -4439,7 +4444,7 @@ dependencies = [ [[package]] name = "pallet-aura" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#3ec97a31b285181fb1beab426ee2a8e2cb1188ab" +source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ "frame-support", "frame-system", @@ -4543,6 +4548,7 @@ name = "pallet-bounties" version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ + "frame-benchmarking", "frame-support", "frame-system", "pallet-treasury", @@ -4557,6 +4563,7 @@ name = "pallet-collective" version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ + "frame-benchmarking", "frame-support", "frame-system", "log", @@ -4588,11 +4595,13 @@ name = "pallet-election-provider-multi-phase" version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ + "frame-benchmarking", "frame-election-provider-support", "frame-support", "frame-system", "log", "parity-scale-codec", + "rand 0.7.3", "serde", "sp-arithmetic", "sp-io", @@ -4607,6 +4616,7 @@ name = "pallet-elections-phragmen" version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ + "frame-benchmarking", "frame-support", "frame-system", "log", @@ -4660,6 +4670,7 @@ name = "pallet-im-online" version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ + "frame-benchmarking", "frame-support", "frame-system", "log", @@ -4679,6 +4690,7 @@ name = "pallet-indices" version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ + "frame-benchmarking", "frame-support", "frame-system", "parity-scale-codec", @@ -4761,6 +4773,7 @@ name = "pallet-multisig" version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ + "frame-benchmarking", "frame-support", "frame-system", "parity-scale-codec", @@ -4801,11 +4814,34 @@ dependencies = [ "sp-std", ] +[[package]] +name = "pallet-offences-benchmarking" +version = "3.0.0" +source = "git+https://github.com/paritytech/substrate?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" +dependencies = [ + "frame-benchmarking", + "frame-election-provider-support", + "frame-support", + "frame-system", + "pallet-babe", + "pallet-balances", + "pallet-grandpa", + "pallet-im-online", + "pallet-offences", + "pallet-session", + "pallet-staking", + "parity-scale-codec", + "sp-runtime", + "sp-staking", + "sp-std", +] + [[package]] name = "pallet-proxy" version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ + "frame-benchmarking", "frame-support", "frame-system", "parity-scale-codec", @@ -4880,6 +4916,22 @@ dependencies = [ "sp-trie", ] +[[package]] +name = "pallet-session-benchmarking" +version = "3.0.0" +source = "git+https://github.com/paritytech/substrate?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" +dependencies = [ + "frame-benchmarking", + "frame-support", + "frame-system", + "pallet-session", + "pallet-staking", + "rand 0.7.3", + "sp-runtime", + "sp-session", + "sp-std", +] + [[package]] name = "pallet-simple-staking" version = "3.0.0" @@ -4920,6 +4972,7 @@ name = "pallet-staking" version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ + "frame-benchmarking", "frame-election-provider-support", "frame-support", "frame-system", @@ -4928,6 +4981,7 @@ dependencies = [ "pallet-session", "parity-scale-codec", "paste 1.0.5", + "rand_chacha 0.2.2", "serde", "sp-application-crypto", "sp-io", @@ -4986,6 +5040,7 @@ name = "pallet-tips" version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ + "frame-benchmarking", "frame-support", "frame-system", "pallet-treasury", @@ -5044,6 +5099,7 @@ name = "pallet-treasury" version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ + "frame-benchmarking", "frame-support", "frame-system", "impl-trait-for-tuples", @@ -5059,6 +5115,7 @@ name = "pallet-utility" version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ + "frame-benchmarking", "frame-support", "frame-system", "parity-scale-codec", @@ -5075,6 +5132,7 @@ version = "3.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ "enumflags2", + "frame-benchmarking", "frame-support", "frame-system", "parity-scale-codec", @@ -6155,11 +6213,14 @@ source = "git+https://github.com/paritytech/polkadot?branch=rococo-v1#943038a888 dependencies = [ "beefy-primitives", "bitvec", + "frame-benchmarking", "frame-executive", "frame-support", "frame-system", + "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", + "hex-literal 0.3.1", "log", "pallet-authority-discovery", "pallet-authorship", @@ -6179,10 +6240,12 @@ dependencies = [ "pallet-multisig", "pallet-nicks", "pallet-offences", + "pallet-offences-benchmarking", "pallet-proxy", "pallet-randomness-collective-flip", "pallet-scheduler", "pallet-session", + "pallet-session-benchmarking", "pallet-staking", "pallet-staking-reward-curve", "pallet-timestamp", @@ -6225,12 +6288,14 @@ source = "git+https://github.com/paritytech/polkadot?branch=rococo-v1#943038a888 dependencies = [ "beefy-primitives", "bitvec", + "frame-benchmarking", "frame-support", "frame-system", "impl-trait-for-tuples", "libsecp256k1", "log", "pallet-authorship", + "pallet-babe", "pallet-balances", "pallet-beefy", "pallet-mmr", @@ -6267,8 +6332,10 @@ source = "git+https://github.com/paritytech/polkadot?branch=rococo-v1#943038a888 dependencies = [ "bitvec", "derive_more 0.99.13", + "frame-benchmarking", "frame-support", "frame-system", + "libsecp256k1", "log", "pallet-authority-discovery", "pallet-authorship", @@ -8778,7 +8845,7 @@ dependencies = [ [[package]] name = "sp-consensus-aura" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#3ec97a31b285181fb1beab426ee2a8e2cb1188ab" +source = "git+https://github.com/paritytech/substrate.git?branch=rococo-v1#68cfc326fa0e3d96d0d92509e4db1a104b9da9bb" dependencies = [ "parity-scale-codec", "sp-api", @@ -10947,11 +11014,14 @@ source = "git+https://github.com/paritytech/polkadot?branch=rococo-v1#943038a888 dependencies = [ "beefy-primitives", "bitvec", + "frame-benchmarking", "frame-executive", "frame-support", "frame-system", + "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", + "hex-literal 0.3.1", "log", "pallet-authority-discovery", "pallet-authorship", @@ -10972,11 +11042,13 @@ dependencies = [ "pallet-multisig", "pallet-nicks", "pallet-offences", + "pallet-offences-benchmarking", "pallet-proxy", "pallet-randomness-collective-flip", "pallet-recovery", "pallet-scheduler", "pallet-session", + "pallet-session-benchmarking", "pallet-society", "pallet-staking", "pallet-staking-reward-curve", diff --git a/node/Cargo.toml b/node/Cargo.toml index 302bdcb..ed9ebab 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -1,10 +1,6 @@ [[bin]] name = 'statemint' -[features] -default = [] -runtime-benchmarks = ['statemint-runtime/runtime-benchmarks'] - [package] authors = ['Anonymous'] build = 'build.rs' @@ -215,4 +211,12 @@ branch = 'rococo-v1' [build-dependencies.substrate-build-script-utils] git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' -version = '3.0.0' \ No newline at end of file +version = '3.0.0' + +[features] +default = [] +runtime-benchmarks = [ + 'polkadot-service/runtime-benchmarks', + 'statemint-runtime/runtime-benchmarks', + 'statemine-runtime/runtime-benchmarks', +] \ No newline at end of file diff --git a/node/src/cli.rs b/node/src/cli.rs index 692b896..75c7750 100644 --- a/node/src/cli.rs +++ b/node/src/cli.rs @@ -34,6 +34,10 @@ pub enum Subcommand { /// Revert the chain to a previous state. Revert(sc_cli::RevertCmd), + + /// The custom benchmark subcommmand benchmarking runtime pallets. + #[structopt(name = "benchmark", about = "Benchmark runtime pallets.")] + Benchmark(frame_benchmarking_cli::BenchmarkCmd), } /// Command for exporting the genesis state of the parachain diff --git a/node/src/command.rs b/node/src/command.rs index cd3cf01..dc93b42 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -36,6 +36,7 @@ use sp_core::hexdisplay::HexDisplay; use sp_runtime::traits::Block as BlockT; use statemint_runtime::Block; use std::{io::Write, net::SocketAddr}; +use crate::service::Executor; fn load_spec( id: &str, @@ -214,6 +215,16 @@ pub fn run() -> Result<()> { Ok((cmd.run(client, backend), task_manager)) }) } + Some(Subcommand::Benchmark(cmd)) => { + if cfg!(feature = "runtime-benchmarks") { + let runner = cli.create_runner(cmd)?; + + runner.sync_run(|config| cmd.run::(config)) + } else { + Err("Benchmarking wasn't enabled when building the node. \ + You can enable it with `--features runtime-benchmarks`.".into()) + } + } Some(Subcommand::ExportGenesisState(params)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); diff --git a/node/src/service.rs b/node/src/service.rs index f33e1fd..6381cb5 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -21,6 +21,7 @@ native_executor_instance!( pub Executor, statemint_runtime::api::dispatch, statemint_runtime::native_version, + frame_benchmarking::benchmarking::HostFunctions, ); /// Starts a `ServiceBuilder` for a full service. diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index 0620df2..cb18451 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -121,7 +121,7 @@ benchmarks! { // worse case is paying a non-existing author account. note_author { T::Currency::make_free_balance_be( - &T::TreasuryAddress::get(), + &>::account_id(), T::Currency::minimum_balance() * 2u32.into(), ); let author = account("author", 0, SEED); diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 92b1fc2..b24725c 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -51,7 +51,37 @@ pub mod pallet { /// /// Used only for benchmarking. type MaxInvulnerables: Get; + + type WeightInfo: WeightInfo; + } + + // The weight info trait for `pallet_escrow`. +pub trait WeightInfo { + fn set_invulnerables(_b: u32) -> Weight; + fn set_allowed_author_count() -> Weight; + fn set_author_bond() -> Weight; + fn register_as_author(_c: u32) -> Weight; + fn leave_intent(_c: u32) -> Weight; +} + +// default weights for tests +impl WeightInfo for () { + fn set_invulnerables(_b: u32) -> Weight { + 0 + } + fn set_allowed_author_count() -> Weight { + 0 + } + fn set_author_bond() -> Weight { + 0 } + fn register_as_author(_c: u32) -> Weight { + 0 + } + fn leave_intent(_c: u32) -> Weight { + 0 + } +} type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; @@ -139,7 +169,10 @@ pub mod pallet { } #[pallet::hooks] - impl Hooks> for Pallet {} + impl Hooks> for Pallet { + //TODO add in on init hook to concat invulnerables with Authors and set as aura authorities + // Also consider implementing era's of X block + } // Dispatchable functions allows users to interact with the pallet and invoke state changes. // These functions materialize as "extrinsics", which are often compared to transactions. @@ -185,7 +218,16 @@ pub mod pallet { Ok(().into()) } - #[pallet::weight(10_000)] + // 1. worse case + // #[pallet::weight(T::WeightInfo::register_as_author(T::MaxAuthors::get()))] + // 2. accurate, provided by user, checked by chain + // #[pallet::weight(T::WeightInfo::register_as_author(authors_count))] + // pub fn register_as_author(origin: OriginFor, authors_count: u32) -> DispatchResultWithPostInfo {} + // 3. refund + // #[pallet::weight(T::WeightInfo::register_as_author(T::MaxAuthors::get()))] + // in case of successful transaction, return `Ok(Some(refund).into())` + + #[pallet::weight(1000)] pub fn register_as_author(origin: OriginFor) -> DispatchResultWithPostInfo { // lock deposit to start or require min? let who = ensure_signed(origin)?; @@ -243,7 +285,11 @@ pub mod pallet { let _success = T::Currency::transfer(&treasury, &author, reward, KeepAlive); debug_assert!(_success.is_ok()); - frame_system::Pallet::::register_extra_weight_unchecked(0, DispatchClass::Mandatory); + frame_system::Pallet::::register_extra_weight_unchecked( + // T::WeightInfo::note_author(), + 0, + DispatchClass::Mandatory, + ); } fn note_uncle(_author: T::AccountId, _age: T::BlockNumber) { //TODO can we ignore this? diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index 715f4b9..6b86955 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -124,6 +124,7 @@ impl Config for Test { type TreasuryId = TreasuryId; type MaxAuthors = MaxAuthors; type MaxInvulnerables = MaxInvulnerables; + type WeightInfo = (); } pub fn new_test_ext() -> sp_io::TestExternalities { diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index 7fb90ac..7d73ccb 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -61,13 +61,11 @@ default-features = false git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' - [dependencies.polkadot-runtime-common] git = 'https://github.com/paritytech/polkadot' branch = 'rococo-v1' default-features = false - # Polkadot dependencies [dependencies.polkadot-primitives] git = 'https://github.com/paritytech/polkadot' @@ -105,7 +103,6 @@ std = [ 'codec/std', 'sp-std/std', 'sp-io/std', - 'sp-runtime/std', 'frame-support/std', 'frame-executive/std', 'frame-system/std', diff --git a/runtime/statemine/Cargo.toml b/runtime/statemine/Cargo.toml index 50dd723..ece0770 100644 --- a/runtime/statemine/Cargo.toml +++ b/runtime/statemine/Cargo.toml @@ -280,21 +280,28 @@ path = '../../pallets/simple-staking' [dependencies.runtime-common] default-features = false +version = "0.8.30" path = '../common' [features] default = ['std'] runtime-benchmarks = [ + 'hex-literal', + 'xcm-builder/runtime-benchmarks', 'sp-runtime/runtime-benchmarks', 'frame-benchmarking', 'frame-support/runtime-benchmarks', 'frame-system-benchmarking', - 'hex-literal', 'frame-system/runtime-benchmarks', + 'pallet-assets/runtime-benchmarks', 'pallet-balances/runtime-benchmarks', + 'pallet-multisig/runtime-benchmarks', + 'pallet-proxy/runtime-benchmarks', + 'pallet-utility/runtime-benchmarks', 'pallet-timestamp/runtime-benchmarks', 'pallet-simple-staking/runtime-benchmarks', + 'pallet-xcm/runtime-benchmarks', ] std = [ 'codec/std', @@ -319,15 +326,15 @@ std = [ 'pallet-balances/std', 'pallet-multisig/std', 'pallet-proxy/std', - 'pallet-balances/std', 'pallet-utility/std', 'pallet-randomness-collective-flip/std', 'pallet-transaction-payment-rpc-runtime-api/std', 'pallet-timestamp/std', 'pallet-sudo/std', 'pallet-xcm/std', - 'node-primitives/std', 'pallet-transaction-payment/std', + 'pallet-simple-staking/std', + 'node-primitives/std', 'parachain-info/std', 'cumulus-pallet-parachain-system/std', "cumulus-pallet-xcmp-queue/std", @@ -340,5 +347,4 @@ std = [ 'polkadot-runtime-common/std', 'runtime-common/std', 'polkadot-primitives/std', - 'pallet-simple-staking/std', ] diff --git a/runtime/statemine/src/lib.rs b/runtime/statemine/src/lib.rs index 9394f41..30ca4b3 100644 --- a/runtime/statemine/src/lib.rs +++ b/runtime/statemine/src/lib.rs @@ -128,6 +128,8 @@ pub mod opaque { } } +// mod weights; + pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("statemine"), impl_name: create_runtime_str!("statemine"), @@ -632,6 +634,7 @@ impl pallet_simple_staking::Config for Runtime { type TreasuryId = TreasuryId; // Needs to be some random inaccessible account. (`ModuleId`) type MaxAuthors = MaxAuthors; type MaxInvulnerables = MaxInvulnerables; + type WeightInfo = (); } // Create the runtime by composing the FRAME pallets that were previously configured. @@ -796,7 +799,7 @@ impl_runtime_apis! { ) -> Result, sp_runtime::RuntimeString> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey}; - use frame_system_benchmarking::Module as SystemBench; + use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime {} let whitelist: Vec = vec![ @@ -816,8 +819,13 @@ impl_runtime_apis! { let params = (&config, &whitelist); add_benchmark!(params, batches, frame_system, SystemBench::); - add_benchmark!(params, batches, pallet_balances, Balances); - add_benchmark!(params, batches, pallet_timestamp, Timestamp); + //TODO we should re run all benchmarks for used pallets together + // add_benchmark!(params, batches, pallet_assets, Assets); + // add_benchmark!(params, batches, pallet_balances, Balances); + // add_benchmark!(params, batches, pallet_multisig, Multisig); + // add_benchmark!(params, batches, pallet_proxy, Proxy); + // add_benchmark!(params, batches, pallet_utility, Utility); + // add_benchmark!(params, batches, pallet_timestamp, Timestamp); add_benchmark!(params, batches, pallet_simple_staking, SimpleStaking); if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } diff --git a/runtime/statemine/src/weights/mod.rs b/runtime/statemine/src/weights/mod.rs new file mode 100644 index 0000000..aa58e41 --- /dev/null +++ b/runtime/statemine/src/weights/mod.rs @@ -0,0 +1 @@ +pub mod pallet_simple_staking; \ No newline at end of file diff --git a/runtime/statemine/src/weights/pallet_simple_staking.rs b/runtime/statemine/src/weights/pallet_simple_staking.rs new file mode 100644 index 0000000..81e9b39 --- /dev/null +++ b/runtime/statemine/src/weights/pallet_simple_staking.rs @@ -0,0 +1,72 @@ + +//! Autogenerated weights for pallet_simple_staking +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 +//! DATE: 2021-04-16, STEPS: `[20, ]`, REPEAT: 10, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 128 + +// Executed Command: +// ./target/release/statemint +// benchmark +// --chain +// statemint-dev +// --execution +// wasm +// --wasm-execution +// compiled +// --pallet +// pallet_simple_staking +// --extrinsic +// * +// --steps +// 20 +// --repeat +// 10 +// --raw +// --output +// ./ + + +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for pallet_simple_staking. +pub struct WeightInfo(PhantomData); +impl pallet_simple_staking::WeightInfo for WeightInfo { + fn set_invulnerables(b: u32, ) -> Weight { + (28_060_000 as Weight) + // Standard Error: 1_000 + .saturating_add((118_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn set_allowed_author_count() -> Weight { + (25_000_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn set_author_bond() -> Weight { + (25_000_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn register_as_author(c: u32, ) -> Weight { + (82_496_000 as Weight) + // Standard Error: 1_000 + .saturating_add((266_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn leave_intent(c: u32, ) -> Weight { + (65_836_000 as Weight) + // Standard Error: 2_000 + .saturating_add((273_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn note_author() -> Weight { + (97_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } +} diff --git a/runtime/statemint/Cargo.toml b/runtime/statemint/Cargo.toml index ae11228..eb8e89f 100644 --- a/runtime/statemint/Cargo.toml +++ b/runtime/statemint/Cargo.toml @@ -280,20 +280,27 @@ path = '../../pallets/simple-staking' [dependencies.runtime-common] default-features = false +version = "0.8.30" path = '../common' [features] default = ['std'] runtime-benchmarks = [ + 'hex-literal', 'sp-runtime/runtime-benchmarks', + 'xcm-builder/runtime-benchmarks', 'frame-benchmarking', - 'frame-support/runtime-benchmarks', 'frame-system-benchmarking', - 'hex-literal', + 'frame-support/runtime-benchmarks', 'frame-system/runtime-benchmarks', + 'pallet-assets/runtime-benchmarks', 'pallet-balances/runtime-benchmarks', + 'pallet-multisig/runtime-benchmarks', + 'pallet-proxy/runtime-benchmarks', + 'pallet-utility/runtime-benchmarks', 'pallet-timestamp/runtime-benchmarks', + 'pallet-xcm/runtime-benchmarks', 'pallet-simple-staking/runtime-benchmarks', ] std = [ @@ -319,15 +326,15 @@ std = [ 'pallet-balances/std', 'pallet-multisig/std', 'pallet-proxy/std', - 'pallet-balances/std', 'pallet-utility/std', 'pallet-randomness-collective-flip/std', 'pallet-transaction-payment-rpc-runtime-api/std', 'pallet-timestamp/std', 'pallet-sudo/std', 'pallet-xcm/std', - 'node-primitives/std', 'pallet-transaction-payment/std', + 'pallet-simple-staking/std', + 'node-primitives/std', 'parachain-info/std', 'cumulus-pallet-parachain-system/std', "cumulus-pallet-xcmp-queue/std", @@ -340,5 +347,4 @@ std = [ 'polkadot-runtime-common/std', 'runtime-common/std', 'polkadot-primitives/std', - 'pallet-simple-staking/std', ] diff --git a/runtime/statemint/src/lib.rs b/runtime/statemint/src/lib.rs index 20edb6d..3ad1bb1 100644 --- a/runtime/statemint/src/lib.rs +++ b/runtime/statemint/src/lib.rs @@ -632,6 +632,7 @@ impl pallet_simple_staking::Config for Runtime { type TreasuryId = TreasuryId; // Needs to be some random inaccessible account. (`ModuleId`) type MaxAuthors = MaxAuthors; type MaxInvulnerables = MaxInvulnerables; + type WeightInfo = (); } // Create the runtime by composing the FRAME pallets that were previously configured. @@ -817,8 +818,14 @@ impl_runtime_apis! { let params = (&config, &whitelist); add_benchmark!(params, batches, frame_system, SystemBench::); - add_benchmark!(params, batches, pallet_balances, Balances); - add_benchmark!(params, batches, pallet_timestamp, Timestamp); + + //TODO we should re run all benchmarks for used pallets together + // add_benchmark!(params, batches, pallet_assets, Assets); + // add_benchmark!(params, batches, pallet_balances, Balances); + // add_benchmark!(params, batches, pallet_multisig, Multisig); + // add_benchmark!(params, batches, pallet_proxy, Proxy); + // add_benchmark!(params, batches, pallet_utility, Utility); + // add_benchmark!(params, batches, pallet_timestamp, Timestamp); add_benchmark!(params, batches, pallet_simple_staking, SimpleStaking); if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } diff --git a/runtime/statemint/src/weights/mod.rs b/runtime/statemint/src/weights/mod.rs new file mode 100644 index 0000000..aa58e41 --- /dev/null +++ b/runtime/statemint/src/weights/mod.rs @@ -0,0 +1 @@ +pub mod pallet_simple_staking; \ No newline at end of file diff --git a/runtime/statemint/src/weights/pallet_simple_staking.rs b/runtime/statemint/src/weights/pallet_simple_staking.rs new file mode 100644 index 0000000..81e9b39 --- /dev/null +++ b/runtime/statemint/src/weights/pallet_simple_staking.rs @@ -0,0 +1,72 @@ + +//! Autogenerated weights for pallet_simple_staking +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 +//! DATE: 2021-04-16, STEPS: `[20, ]`, REPEAT: 10, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 128 + +// Executed Command: +// ./target/release/statemint +// benchmark +// --chain +// statemint-dev +// --execution +// wasm +// --wasm-execution +// compiled +// --pallet +// pallet_simple_staking +// --extrinsic +// * +// --steps +// 20 +// --repeat +// 10 +// --raw +// --output +// ./ + + +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for pallet_simple_staking. +pub struct WeightInfo(PhantomData); +impl pallet_simple_staking::WeightInfo for WeightInfo { + fn set_invulnerables(b: u32, ) -> Weight { + (28_060_000 as Weight) + // Standard Error: 1_000 + .saturating_add((118_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn set_allowed_author_count() -> Weight { + (25_000_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn set_author_bond() -> Weight { + (25_000_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn register_as_author(c: u32, ) -> Weight { + (82_496_000 as Weight) + // Standard Error: 1_000 + .saturating_add((266_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn leave_intent(c: u32, ) -> Weight { + (65_836_000 as Weight) + // Standard Error: 2_000 + .saturating_add((273_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn note_author() -> Weight { + (97_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } +} From 4e1570979be2202640e11cd6f3921db4c5ba6083 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Fri, 16 Apr 2021 19:03:45 +0200 Subject: [PATCH 35/56] added wight attributes --- pallets/simple-staking/src/lib.rs | 54 +++++++++++++++++-------------- runtime/statemine/src/lib.rs | 4 +-- runtime/statemint/src/lib.rs | 5 ++- 3 files changed, 35 insertions(+), 28 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index b24725c..fae3fde 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -62,6 +62,7 @@ pub trait WeightInfo { fn set_author_bond() -> Weight; fn register_as_author(_c: u32) -> Weight; fn leave_intent(_c: u32) -> Weight; + fn note_author() -> Weight; } // default weights for tests @@ -81,6 +82,9 @@ impl WeightInfo for () { fn leave_intent(_c: u32) -> Weight { 0 } + fn note_author() -> Weight { + 0 + } } type BalanceOf = @@ -179,7 +183,8 @@ impl WeightInfo for () { // Dispatchable functions must be annotated with a weight and must return a DispatchResult. #[pallet::call] impl Pallet { - #[pallet::weight(10_000)] + + #[pallet::weight(T::WeightInfo::set_invulnerables(new.len() as u32))] pub fn set_invulnerables( origin: OriginFor, new: Vec, @@ -196,7 +201,7 @@ impl WeightInfo for () { Ok(().into()) } - #[pallet::weight(10_000)] + #[pallet::weight(T::WeightInfo::set_allowed_author_count())] pub fn set_allowed_author_count(origin: OriginFor, allowed: u32) -> DispatchResultWithPostInfo { T::UpdateOrigin::ensure_origin(origin)?; // we trust origin calls, this is just a for more accurate benchmarking @@ -210,7 +215,7 @@ impl WeightInfo for () { Ok(().into()) } - #[pallet::weight(10_000)] + #[pallet::weight(T::WeightInfo::set_author_bond())] pub fn set_author_bond(origin: OriginFor, author_bond: BalanceOf) -> DispatchResultWithPostInfo { T::UpdateOrigin::ensure_origin(origin)?; >::put(&author_bond); @@ -227,7 +232,7 @@ impl WeightInfo for () { // #[pallet::weight(T::WeightInfo::register_as_author(T::MaxAuthors::get()))] // in case of successful transaction, return `Ok(Some(refund).into())` - #[pallet::weight(1000)] + #[pallet::weight(T::WeightInfo::register_as_author(T::MaxAuthors::get()))] pub fn register_as_author(origin: OriginFor) -> DispatchResultWithPostInfo { // lock deposit to start or require min? let who = ensure_signed(origin)?; @@ -239,30 +244,30 @@ impl WeightInfo for () { deposit, last_block: None }; - >::try_mutate(|authors| -> DispatchResult { - if authors.into_iter().any(|author| author.who == who) { - Err(Error::::AlreadyAuthor)? - } else { - T::Currency::reserve(&who, deposit)?; - authors.push(new_author); - Self::deposit_event(Event::AuthorAdded(who, deposit)); - Ok(()) - } - })?; - Ok(().into()) + let author_count = >::try_mutate(|authors| -> Result { + if authors.into_iter().any(|author| author.who == who) { + Err(Error::::AlreadyAuthor)? + } else { + T::Currency::reserve(&who, deposit)?; + authors.push(new_author); + Self::deposit_event(Event::AuthorAdded(who, deposit)); + Ok(authors.len()) + } + })?; + Ok(Some(T::WeightInfo::register_as_author(author_count as u32)).into()) } - #[pallet::weight(10_000)] + #[pallet::weight(T::WeightInfo::leave_intent(T::MaxAuthors::get()))] pub fn leave_intent(origin: OriginFor) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; - >::try_mutate(|authors| -> DispatchResult { - let index = authors.iter().position(|author| author.who == who).ok_or(Error::::NotAuthor)?; - T::Currency::unreserve(&who, authors[index].deposit); - authors.remove(index); - Ok(()) - })?; + let author_count = >::try_mutate(|authors| -> Result { + let index = authors.iter().position(|author| author.who == who).ok_or(Error::::NotAuthor)?; + T::Currency::unreserve(&who, authors[index].deposit); + authors.remove(index); + Ok(authors.len()) + })?; Self::deposit_event(Event::AuthorRemoved(who)); - Ok(().into()) + Ok(Some(T::WeightInfo::leave_intent(author_count as u32)).into()) } } @@ -286,8 +291,7 @@ impl WeightInfo for () { debug_assert!(_success.is_ok()); frame_system::Pallet::::register_extra_weight_unchecked( - // T::WeightInfo::note_author(), - 0, + T::WeightInfo::note_author(), DispatchClass::Mandatory, ); } diff --git a/runtime/statemine/src/lib.rs b/runtime/statemine/src/lib.rs index 30ca4b3..d781833 100644 --- a/runtime/statemine/src/lib.rs +++ b/runtime/statemine/src/lib.rs @@ -128,7 +128,7 @@ pub mod opaque { } } -// mod weights; +mod weights; pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("statemine"), @@ -634,7 +634,7 @@ impl pallet_simple_staking::Config for Runtime { type TreasuryId = TreasuryId; // Needs to be some random inaccessible account. (`ModuleId`) type MaxAuthors = MaxAuthors; type MaxInvulnerables = MaxInvulnerables; - type WeightInfo = (); + type WeightInfo = weights::pallet_simple_staking::WeightInfo; } // Create the runtime by composing the FRAME pallets that were previously configured. diff --git a/runtime/statemint/src/lib.rs b/runtime/statemint/src/lib.rs index 3ad1bb1..ce8e03f 100644 --- a/runtime/statemint/src/lib.rs +++ b/runtime/statemint/src/lib.rs @@ -128,6 +128,9 @@ pub mod opaque { } } +mod weights; + + pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("statemint"), impl_name: create_runtime_str!("statemint"), @@ -632,7 +635,7 @@ impl pallet_simple_staking::Config for Runtime { type TreasuryId = TreasuryId; // Needs to be some random inaccessible account. (`ModuleId`) type MaxAuthors = MaxAuthors; type MaxInvulnerables = MaxInvulnerables; - type WeightInfo = (); + type WeightInfo = weights::pallet_simple_staking::WeightInfo; } // Create the runtime by composing the FRAME pallets that were previously configured. From 4f0fff088fc6d09800974ff515abd38f10fc3a60 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Mon, 19 Apr 2021 10:05:17 +0200 Subject: [PATCH 36/56] test for impl fees --- Cargo.lock | 1 + runtime/common/Cargo.toml | 8 ++++++++ runtime/common/src/impls.rs | 24 +++++++++++++++++++++--- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 71d3250..ee350a7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7194,6 +7194,7 @@ dependencies = [ "frame-support", "frame-system", "node-primitives", + "pallet-authorship", "pallet-balances", "pallet-simple-staking", "parity-scale-codec", diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index 7d73ccb..e44649a 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -97,6 +97,14 @@ git = 'https://github.com/paritytech/substrate.git' branch = 'rococo-v1' version = '3.0.0' +[dev-dependencies.pallet-authorship] +default-features = false +git = 'https://github.com/paritytech/substrate.git' +branch = 'rococo-v1' +version = '3.0.0' + + + [features] default = ["std"] std = [ diff --git a/runtime/common/src/impls.rs b/runtime/common/src/impls.rs index 032839b..b7538c7 100644 --- a/runtime/common/src/impls.rs +++ b/runtime/common/src/impls.rs @@ -69,8 +69,8 @@ where mod tests { use super::*; use frame_support::traits::FindAuthor; - use frame_support::{parameter_types, weights::DispatchClass}; - use frame_system::limits; + use frame_support::{parameter_types, weights::DispatchClass, PalletId}; + use frame_system::{limits, EnsureRoot}; use polkadot_primitives::v1::AccountId; use sp_core::H256; use sp_runtime::{ @@ -90,6 +90,7 @@ mod tests { { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + SimpleStaking: pallet_simple_staking::{Pallet, Call, Storage, Event}, } ); @@ -152,6 +153,23 @@ mod tests { Some(Default::default()) } } + + + parameter_types! { + pub const TreasuryId: PalletId = PalletId(*b"Treasury"); + pub const MaxAuthors: u32 = 20; + pub const MaxInvulnerables: u32 = 20; + } + impl pallet_simple_staking::Config for Test { + type Event = Event; + type Currency = Balances; + type UpdateOrigin = EnsureRoot; + type TreasuryId = TreasuryId; + type MaxAuthors = MaxAuthors; + type MaxInvulnerables = MaxInvulnerables; + type WeightInfo = (); + } + impl pallet_authorship::Config for Test { type FindAuthor = OneAuthor; type UncleGenerations = (); @@ -181,7 +199,7 @@ mod tests { DealWithFees::on_unbalanceds(vec![fee, tip].into_iter()); // Author gets 100% of tip and 100% of fee = 30 - assert_eq!(Balances::free_balance(AccountId::default()), 30); + assert_eq!(Balances::free_balance(SimpleStaking::account_id()), 30); }); } } From 425393e2e9a11cbee7dba397c0874482daa91098 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 10:20:23 +0200 Subject: [PATCH 37/56] Update node/Cargo.toml Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- node/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/node/Cargo.toml b/node/Cargo.toml index ed9ebab..1078150 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -219,4 +219,4 @@ runtime-benchmarks = [ 'polkadot-service/runtime-benchmarks', 'statemint-runtime/runtime-benchmarks', 'statemine-runtime/runtime-benchmarks', -] \ No newline at end of file +] From 3e5bce1d8420e40e81969dc6c6b02bbbe12cc54c Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 10:20:31 +0200 Subject: [PATCH 38/56] Update pallets/simple-staking/src/benchmarking.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/benchmarking.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index cb18451..8c6d616 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -1,4 +1,4 @@ -//! Benchmarking setup for pallet-template +//! Benchmarking setup for pallet-simple-staking use super::*; From 942caf5b9590159ba13931a22377b4b6fc5cf199 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 10:20:45 +0200 Subject: [PATCH 39/56] Update pallets/simple-staking/src/benchmarking.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/benchmarking.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index 8c6d616..60bc9b2 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -22,8 +22,8 @@ const SEED: u32 = 0; macro_rules! whitelist { ($acc:ident) => { frame_benchmarking::benchmarking::add_to_whitelist( - frame_system::Account::::hashed_key_for(&$acc).into() - ); + frame_system::Account::::hashed_key_for(&$acc).into() + ); }; } From b3900338a02d8fe9133fd843005590b44f0c6594 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 10:21:03 +0200 Subject: [PATCH 40/56] Update pallets/simple-staking/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/lib.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index fae3fde..7b7bd8c 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -36,9 +36,11 @@ pub mod pallet { type Event: From> + IsType<::Event>; /// The currency mechanism. type Currency: ReservableCurrency; - + + /// Origin that can dictate updating parameters of this pallet. type UpdateOrigin: EnsureOrigin; + /// Account Identifier using which the internal treasury account is generated. type TreasuryId: Get; /// Maximum number of authors that we should have. This is used for benchmarking and is not @@ -52,6 +54,7 @@ pub mod pallet { /// Used only for benchmarking. type MaxInvulnerables: Get; + /// The weight information of this pallet. type WeightInfo: WeightInfo; } From d9cd21e07e328c1f46a6b6939a213c4d799dd588 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:28:08 +0200 Subject: [PATCH 41/56] Update pallets/simple-staking/src/benchmarking.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/benchmarking.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index 60bc9b2..474d0d1 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -51,7 +51,6 @@ benchmarks! { let b in 1 .. T::MaxInvulnerables::get(); let new_invulnerables = (0..b).map(|c| account("author", c, SEED)).collect::>(); let origin = T::UpdateOrigin::successful_origin(); - // whitelist!(RootAccount); // TODO }: { assert_ok!( >::set_invulnerables(origin, new_invulnerables.clone()) From 8be8865ec9aa24948a306d557694e03eab41fbf9 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:28:17 +0200 Subject: [PATCH 42/56] Update pallets/simple-staking/src/benchmarking.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/benchmarking.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index 474d0d1..0394454 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -63,7 +63,6 @@ benchmarks! { set_allowed_author_count { let max: u32 = 999; let origin = T::UpdateOrigin::successful_origin(); - // whitelist!(caller); }: { assert_ok!( >::set_allowed_author_count(origin, max.clone()) From 3d0a7b20a9929410c2f671eaefadc94bb9a684e0 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:28:29 +0200 Subject: [PATCH 43/56] Update pallets/simple-staking/src/benchmarking.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/benchmarking.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index 0394454..7c1f890 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -75,7 +75,6 @@ benchmarks! { set_author_bond { let bond: BalanceOf = T::Currency::minimum_balance() * 10u32.into(); let origin = T::UpdateOrigin::successful_origin(); - // whitelist!(caller); }: { assert_ok!( >::set_author_bond(origin, bond.clone()) From f8a9669a264807eb1ef6abace0aae5372a21573f Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:32:33 +0200 Subject: [PATCH 44/56] Update pallets/simple-staking/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 7b7bd8c..3f3b288 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -186,7 +186,6 @@ impl WeightInfo for () { // Dispatchable functions must be annotated with a weight and must return a DispatchResult. #[pallet::call] impl Pallet { - #[pallet::weight(T::WeightInfo::set_invulnerables(new.len() as u32))] pub fn set_invulnerables( origin: OriginFor, From 07c83831c5012defd17e00b34021cd7bd261fd78 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:32:43 +0200 Subject: [PATCH 45/56] Update pallets/simple-staking/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/lib.rs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 3f3b288..8fa7342 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -225,15 +225,6 @@ impl WeightInfo for () { Ok(().into()) } - // 1. worse case - // #[pallet::weight(T::WeightInfo::register_as_author(T::MaxAuthors::get()))] - // 2. accurate, provided by user, checked by chain - // #[pallet::weight(T::WeightInfo::register_as_author(authors_count))] - // pub fn register_as_author(origin: OriginFor, authors_count: u32) -> DispatchResultWithPostInfo {} - // 3. refund - // #[pallet::weight(T::WeightInfo::register_as_author(T::MaxAuthors::get()))] - // in case of successful transaction, return `Ok(Some(refund).into())` - #[pallet::weight(T::WeightInfo::register_as_author(T::MaxAuthors::get()))] pub fn register_as_author(origin: OriginFor) -> DispatchResultWithPostInfo { // lock deposit to start or require min? From 0ec019b5dd5f5422599b37e9de264e401b9818f6 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:36:31 +0200 Subject: [PATCH 46/56] Update pallets/simple-staking/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 8fa7342..8a072ab 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -288,6 +288,7 @@ impl WeightInfo for () { DispatchClass::Mandatory, ); } + fn note_uncle(_author: T::AccountId, _age: T::BlockNumber) { //TODO can we ignore this? } From dff932fae930bb2481cb79bd599579520d26413d Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:36:39 +0200 Subject: [PATCH 47/56] Update pallets/simple-staking/src/mock.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/mock.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index 6b86955..edc3847 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -139,7 +139,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { invulnerables: vec![ 1, 2, - 3 + 3, ], }; genesis.assimilate_storage(&mut t).unwrap(); From 8da9ff61ddfccbd227a5efd9710bb41ced022e2b Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:36:57 +0200 Subject: [PATCH 48/56] Update pallets/simple-staking/src/tests.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/tests.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 799bf83..daa4215 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -95,8 +95,12 @@ fn on_init() { Balances::make_free_balance_be(&SimpleStaking::account_id(), 100); assert_eq!(Balances::free_balance(4), 0); assert_eq!(Balances::free_balance(SimpleStaking::account_id()), 100); + // triggers `note_author` Authorship::on_initialize(1); + + // half of the pot goes to the author. assert_eq!(Balances::free_balance(4), 50); + // half stays. assert_eq!(Balances::free_balance(SimpleStaking::account_id()), 50); }); } From bcde167b048b8881fc1905ecbfa0c0a3e18387bd Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:37:57 +0200 Subject: [PATCH 49/56] Update pallets/simple-staking/src/tests.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index daa4215..c0f42f7 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -93,6 +93,7 @@ fn leave_intent() { fn on_init() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&SimpleStaking::account_id(), 100); + // 4 is the default author. assert_eq!(Balances::free_balance(4), 0); assert_eq!(Balances::free_balance(SimpleStaking::account_id()), 100); // triggers `note_author` From 0f5cda51118c72cd233db9355291cd03353842cf Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:38:05 +0200 Subject: [PATCH 50/56] Update pallets/simple-staking/src/tests.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index c0f42f7..1464fb0 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -90,7 +90,7 @@ fn leave_intent() { } #[test] -fn on_init() { +fn authorship_event_handler() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&SimpleStaking::account_id(), 100); // 4 is the default author. From f391e8888f48821bcfd472ac328fadbc086ba786 Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:38:39 +0200 Subject: [PATCH 51/56] Update pallets/simple-staking/src/tests.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 1464fb0..8962e44 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -79,6 +79,7 @@ fn leave_intent() { assert_ok!(SimpleStaking::set_allowed_author_count(Origin::signed(RootAccount::get()), 1)); assert_ok!(SimpleStaking::set_author_bond(Origin::signed(RootAccount::get()), 10)); assert_ok!(SimpleStaking::register_as_author(Origin::signed(1))); + assert_eq!(Balances::free_balance(1), 90); assert_noop!( SimpleStaking::leave_intent(Origin::signed(RootAccount::get())), Error::::NotAuthor From 96b0606112405e6f1b2a4290a979b0ddcf274b1a Mon Sep 17 00:00:00 2001 From: JesseAbram <33698952+JesseAbram@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:39:57 +0200 Subject: [PATCH 52/56] Update pallets/simple-staking/src/tests.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- pallets/simple-staking/src/tests.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 8962e44..8effc32 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -47,29 +47,39 @@ fn register_as_author() { assert_ok!(SimpleStaking::set_author_bond(Origin::signed(RootAccount::get()), 10)); assert_ok!(SimpleStaking::set_allowed_author_count(Origin::signed(RootAccount::get()), 1)); + + // can add 1 new assert_ok!(SimpleStaking::register_as_author(Origin::signed(1))); - let addition = AuthorInfo { who: 1, deposit: 10, last_block: None }; + assert_eq!(SimpleStaking::authors(), vec![addition]); assert_eq!(Balances::free_balance(1), 90); + + // but no more assert_noop!( SimpleStaking::register_as_author(Origin::signed(1)), Error::::TooManyAuthors ); + // increase limit assert_ok!(SimpleStaking::set_allowed_author_count(Origin::signed(RootAccount::get()), 5)); + // but still won't accept dupe.. assert_noop!( SimpleStaking::register_as_author(Origin::signed(1)), Error::::AlreadyAuthor ); + // or poor author (3 is not endowed) assert_noop!( - SimpleStaking::register_as_author(Origin::signed(RootAccount::get())), + SimpleStaking::register_as_author(Origin::signed(3)), BalancesError::::InsufficientBalance ); - assert_eq!(SimpleStaking::authors(), vec![addition]); + // but an endowed account works now + assert_ok!(SimpleStaking::register_as_author(Origin::signed(2))); + + assert_eq!(SimpleStaking::authors().len(), 2); }); } From 8b13bb3b42e064db6e70395b03d8edb630321bea Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Mon, 19 Apr 2021 12:09:27 +0200 Subject: [PATCH 53/56] format and potId --- pallets/simple-staking/src/lib.rs | 22 +++++++++++----------- pallets/simple-staking/src/mock.rs | 4 ++-- runtime/common/src/impls.rs | 4 ++-- runtime/statemine/src/lib.rs | 4 ++-- runtime/statemint/src/lib.rs | 4 ++-- 5 files changed, 19 insertions(+), 19 deletions(-) diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 8a072ab..40805a4 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -36,12 +36,12 @@ pub mod pallet { type Event: From> + IsType<::Event>; /// The currency mechanism. type Currency: ReservableCurrency; - + /// Origin that can dictate updating parameters of this pallet. type UpdateOrigin: EnsureOrigin; - /// Account Identifier using which the internal treasury account is generated. - type TreasuryId: Get; + /// Account Identifier using which the internal treasury account is generated. + type PotId: Get; /// Maximum number of authors that we should have. This is used for benchmarking and is not /// enforced. @@ -54,7 +54,7 @@ pub mod pallet { /// Used only for benchmarking. type MaxInvulnerables: Get; - /// The weight information of this pallet. + /// The weight information of this pallet. type WeightInfo: WeightInfo; } @@ -254,11 +254,11 @@ impl WeightInfo for () { pub fn leave_intent(origin: OriginFor) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; let author_count = >::try_mutate(|authors| -> Result { - let index = authors.iter().position(|author| author.who == who).ok_or(Error::::NotAuthor)?; - T::Currency::unreserve(&who, authors[index].deposit); - authors.remove(index); - Ok(authors.len()) - })?; + let index = authors.iter().position(|author| author.who == who).ok_or(Error::::NotAuthor)?; + T::Currency::unreserve(&who, authors[index].deposit); + authors.remove(index); + Ok(authors.len()) + })?; Self::deposit_event(Event::AuthorRemoved(who)); Ok(Some(T::WeightInfo::leave_intent(author_count as u32)).into()) } @@ -266,7 +266,7 @@ impl WeightInfo for () { impl Pallet { pub fn account_id() -> T::AccountId { - T::TreasuryId::get().into_account() + T::PotId::get().into_account() } } @@ -288,7 +288,7 @@ impl WeightInfo for () { DispatchClass::Mandatory, ); } - + fn note_uncle(_author: T::AccountId, _age: T::BlockNumber) { //TODO can we ignore this? } diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index edc3847..1d09c49 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -113,7 +113,7 @@ ord_parameter_types! { pub const RootAccount: u64 = 777; } parameter_types! { - pub const TreasuryId: PalletId = PalletId(*b"Treasury"); + pub const PotId: PalletId = PalletId(*b"PotStake"); pub const MaxAuthors: u32 = 20; pub const MaxInvulnerables: u32 = 20; } @@ -121,7 +121,7 @@ impl Config for Test { type Event = Event; type Currency = Balances; type UpdateOrigin = EnsureSignedBy; - type TreasuryId = TreasuryId; + type PotId = PotId; type MaxAuthors = MaxAuthors; type MaxInvulnerables = MaxInvulnerables; type WeightInfo = (); diff --git a/runtime/common/src/impls.rs b/runtime/common/src/impls.rs index b7538c7..d470d90 100644 --- a/runtime/common/src/impls.rs +++ b/runtime/common/src/impls.rs @@ -156,7 +156,7 @@ mod tests { parameter_types! { - pub const TreasuryId: PalletId = PalletId(*b"Treasury"); + pub const PotId: PalletId = PalletId(*b"PotStake"); pub const MaxAuthors: u32 = 20; pub const MaxInvulnerables: u32 = 20; } @@ -164,7 +164,7 @@ mod tests { type Event = Event; type Currency = Balances; type UpdateOrigin = EnsureRoot; - type TreasuryId = TreasuryId; + type PotId = PotId; type MaxAuthors = MaxAuthors; type MaxInvulnerables = MaxInvulnerables; type WeightInfo = (); diff --git a/runtime/statemine/src/lib.rs b/runtime/statemine/src/lib.rs index d781833..be0fe0d 100644 --- a/runtime/statemine/src/lib.rs +++ b/runtime/statemine/src/lib.rs @@ -614,7 +614,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { } parameter_types! { - pub const TreasuryId: PalletId = PalletId(*b"Treasury"); + pub const PotId: PalletId = PalletId(*b"PotStake"); pub const MaxAuthors: u32 = 1000; pub const MaxInvulnerables: u32 = 100; } @@ -631,7 +631,7 @@ impl pallet_simple_staking::Config for Runtime { type Event = Event; type Currency = Balances; type UpdateOrigin = frame_system::EnsureSignedBy; - type TreasuryId = TreasuryId; // Needs to be some random inaccessible account. (`ModuleId`) + type PotId = PotId; type MaxAuthors = MaxAuthors; type MaxInvulnerables = MaxInvulnerables; type WeightInfo = weights::pallet_simple_staking::WeightInfo; diff --git a/runtime/statemint/src/lib.rs b/runtime/statemint/src/lib.rs index ce8e03f..e3eaf22 100644 --- a/runtime/statemint/src/lib.rs +++ b/runtime/statemint/src/lib.rs @@ -615,7 +615,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { } parameter_types! { - pub const TreasuryId: PalletId = PalletId(*b"Treasury"); + pub const PotId: PalletId = PalletId(*b"PotStake"); pub const MaxAuthors: u32 = 1000; pub const MaxInvulnerables: u32 = 100; } @@ -632,7 +632,7 @@ impl pallet_simple_staking::Config for Runtime { type Event = Event; type Currency = Balances; type UpdateOrigin = frame_system::EnsureSignedBy; - type TreasuryId = TreasuryId; // Needs to be some random inaccessible account. (`ModuleId`) + type PotId = PotId; // Needs to be some random inaccessible account. (`ModuleId`) type MaxAuthors = MaxAuthors; type MaxInvulnerables = MaxInvulnerables; type WeightInfo = weights::pallet_simple_staking::WeightInfo; From 37fc3a9552fb7b1b9dcc34fac64c1ec82be176b4 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Mon, 19 Apr 2021 12:14:40 +0200 Subject: [PATCH 54/56] license --- pallets/simple-staking/src/benchmarking.rs | 14 ++++++++++++++ pallets/simple-staking/src/lib.rs | 15 +++++++++++++++ pallets/simple-staking/src/mock.rs | 15 +++++++++++++++ pallets/simple-staking/src/tests.rs | 15 +++++++++++++++ 4 files changed, 59 insertions(+) diff --git a/pallets/simple-staking/src/benchmarking.rs b/pallets/simple-staking/src/benchmarking.rs index 7c1f890..6c54c1f 100644 --- a/pallets/simple-staking/src/benchmarking.rs +++ b/pallets/simple-staking/src/benchmarking.rs @@ -1,3 +1,17 @@ +// Copyright (C) 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. //! Benchmarking setup for pallet-simple-staking use super::*; diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index 40805a4..e8f1b8b 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -1,3 +1,18 @@ +// Copyright (C) 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. + #![cfg_attr(not(feature = "std"), no_std)] pub use pallet::*; diff --git a/pallets/simple-staking/src/mock.rs b/pallets/simple-staking/src/mock.rs index 1d09c49..169f687 100644 --- a/pallets/simple-staking/src/mock.rs +++ b/pallets/simple-staking/src/mock.rs @@ -1,3 +1,18 @@ +// Copyright (C) 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. + use super::*; use crate as simple_staking; use sp_core::H256; diff --git a/pallets/simple-staking/src/tests.rs b/pallets/simple-staking/src/tests.rs index 8effc32..be9d359 100644 --- a/pallets/simple-staking/src/tests.rs +++ b/pallets/simple-staking/src/tests.rs @@ -1,3 +1,18 @@ +// Copyright (C) 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. + use crate::{mock::*, Error, AuthorInfo}; use frame_support::{assert_noop, assert_ok, traits::{OnInitialize, Currency}}; use sp_runtime::traits::BadOrigin; From b57f2acff8ca9113f00c6c5de4d20568cf36c5b6 Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Mon, 19 Apr 2021 12:17:59 +0200 Subject: [PATCH 55/56] rename --- runtime/common/src/impls.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/runtime/common/src/impls.rs b/runtime/common/src/impls.rs index d470d90..72ee436 100644 --- a/runtime/common/src/impls.rs +++ b/runtime/common/src/impls.rs @@ -21,8 +21,8 @@ use frame_support::traits::{Currency, Imbalance, OnUnbalanced}; pub type NegativeImbalance = as Currency<::AccountId>>::NegativeImbalance; /// Logic for the author to get a portion of fees. -pub struct ToAuthor(sp_std::marker::PhantomData); -impl OnUnbalanced> for ToAuthor +pub struct ToStakingPot(sp_std::marker::PhantomData); +impl OnUnbalanced> for ToStakingPot where R: pallet_balances::Config + pallet_simple_staking::Config, ::AccountId: From, @@ -31,13 +31,13 @@ where { fn on_nonzero_unbalanced(amount: NegativeImbalance) { let numeric_amount = amount.peek(); - let treasury = >::account_id(); + let staking_pot = >::account_id(); >::resolve_creating( - &treasury, + &staking_pot, amount, ); >::deposit_event(pallet_balances::Event::Deposit( - treasury, + staking_pot, numeric_amount, )); } @@ -60,7 +60,7 @@ where if let Some(tips) = fees_then_tips.next() { tips.merge_into(&mut fees); } - as OnUnbalanced<_>>::on_unbalanced(fees); + as OnUnbalanced<_>>::on_unbalanced(fees); } } } From 739520e7c93f71e84b6673b4a2b6cea3361b015e Mon Sep 17 00:00:00 2001 From: JesseAbram Date: Mon, 19 Apr 2021 14:01:44 +0200 Subject: [PATCH 56/56] move weight impl to own file --- pallets/simple-staking/src/lib.rs | 34 +------- pallets/simple-staking/src/weights.rs | 108 ++++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 32 deletions(-) create mode 100644 pallets/simple-staking/src/weights.rs diff --git a/pallets/simple-staking/src/lib.rs b/pallets/simple-staking/src/lib.rs index e8f1b8b..0b11570 100644 --- a/pallets/simple-staking/src/lib.rs +++ b/pallets/simple-staking/src/lib.rs @@ -25,6 +25,7 @@ mod tests; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; +pub mod weights; #[frame_support::pallet] pub mod pallet { @@ -42,6 +43,7 @@ pub mod pallet { weights::DispatchClass, }; use core::ops::Div; + pub use crate::weights::WeightInfo; /// Configure the pallet by specifying the parameters and types on which it depends. @@ -73,38 +75,6 @@ pub mod pallet { type WeightInfo: WeightInfo; } - // The weight info trait for `pallet_escrow`. -pub trait WeightInfo { - fn set_invulnerables(_b: u32) -> Weight; - fn set_allowed_author_count() -> Weight; - fn set_author_bond() -> Weight; - fn register_as_author(_c: u32) -> Weight; - fn leave_intent(_c: u32) -> Weight; - fn note_author() -> Weight; -} - -// default weights for tests -impl WeightInfo for () { - fn set_invulnerables(_b: u32) -> Weight { - 0 - } - fn set_allowed_author_count() -> Weight { - 0 - } - fn set_author_bond() -> Weight { - 0 - } - fn register_as_author(_c: u32) -> Weight { - 0 - } - fn leave_intent(_c: u32) -> Weight { - 0 - } - fn note_author() -> Weight { - 0 - } -} - type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; diff --git a/pallets/simple-staking/src/weights.rs b/pallets/simple-staking/src/weights.rs new file mode 100644 index 0000000..767c413 --- /dev/null +++ b/pallets/simple-staking/src/weights.rs @@ -0,0 +1,108 @@ +// This file is part of Substrate. + +// Copyright (C) 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. + +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +// The weight info trait for `pallet_simple_staking`. +pub trait WeightInfo { + fn set_invulnerables(_b: u32) -> Weight; + fn set_allowed_author_count() -> Weight; + fn set_author_bond() -> Weight; + fn register_as_author(_c: u32) -> Weight; + fn leave_intent(_c: u32) -> Weight; + fn note_author() -> Weight; +} + +/// Weights for pallet_simple_staking using the Substrate node and recommended hardware. +pub struct SubstrateWeight(PhantomData); +impl WeightInfo for SubstrateWeight { + fn set_invulnerables(b: u32, ) -> Weight { + (28_060_000 as Weight) + // Standard Error: 1_000 + .saturating_add((118_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn set_allowed_author_count() -> Weight { + (25_000_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn set_author_bond() -> Weight { + (25_000_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn register_as_author(c: u32, ) -> Weight { + (82_496_000 as Weight) + // Standard Error: 1_000 + .saturating_add((266_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn leave_intent(c: u32, ) -> Weight { + (65_836_000 as Weight) + // Standard Error: 2_000 + .saturating_add((273_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn note_author() -> Weight { + (97_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } +} + + +// For backwards compatibility and tests +impl WeightInfo for () { + fn set_invulnerables(b: u32, ) -> Weight { + (28_060_000 as Weight) + // Standard Error: 1_000 + .saturating_add((118_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + fn set_allowed_author_count() -> Weight { + (25_000_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + fn set_author_bond() -> Weight { + (25_000_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + fn register_as_author(c: u32, ) -> Weight { + (82_496_000 as Weight) + // Standard Error: 1_000 + .saturating_add((266_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + fn leave_intent(c: u32, ) -> Weight { + (65_836_000 as Weight) + // Standard Error: 2_000 + .saturating_add((273_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + fn note_author() -> Weight { + (97_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } +} \ No newline at end of file