From a76f37d8547e0752b270f6847e19582d02c91a8e Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Tue, 26 Oct 2021 13:59:33 +0200 Subject: [PATCH 01/47] No need for lookup here we always only want to use accountIDs other lookups are not wanted --- pallets/crowdloan/src/lib.rs | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index 5d584fd76..4ea608355 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -66,6 +66,7 @@ pub mod pallet { pub(crate) type AccountIdOf = ::AccountId; pub(crate) type BalanceOf = <::Currency as Currency>>::Balance; + pub(crate) type WeightInfoOf = ::WeightInfo; pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); @@ -155,7 +156,7 @@ pub mod pallet { /// Weight: O(1) /// - Reads: [Origin Account], RegistrarAccount /// - Writes: RegistrarAccount - #[pallet::weight(T::WeightInfo::set_registrar_account())] + #[pallet::weight(WeightInfoOf::::set_registrar_account())] pub fn set_registrar_account( origin: OriginFor, new_account: ::Source, @@ -191,19 +192,18 @@ pub mod pallet { /// Weight: O(1) /// - Reads: [Origin Account], RegistrarAccount, Contributions /// - Writes: Contributions - #[pallet::weight(T::WeightInfo::set_contribution())] + #[pallet::weight(WeightInfoOf::::set_contribution())] pub fn set_contribution( origin: OriginFor, - contributor_account: ::Source, + contributor: AccountIdOf, amount: BalanceOf, ) -> DispatchResult { let who = ensure_signed(origin)?; ensure!(who == RegistrarAccount::::get(), BadOrigin); - let looked_up_account = ::Lookup::lookup(contributor_account)?; - let old_amount = Contributions::::mutate(&looked_up_account, |entry| entry.replace(amount)); + let old_amount = Contributions::::mutate(&contributor, |entry| entry.replace(amount)); - Self::deposit_event(Event::ContributionSet(looked_up_account, old_amount, amount)); + Self::deposit_event(Event::ContributionSet(contributor, old_amount, amount)); Ok(()) } @@ -221,18 +221,14 @@ pub mod pallet { /// Weight: O(1) /// - Reads: [Origin Account], RegistrarAccount, Contributions /// - Writes: Contributions - #[pallet::weight(T::WeightInfo::remove_contribution())] - pub fn remove_contribution( - origin: OriginFor, - contributor_account: ::Source, - ) -> DispatchResult { + #[pallet::weight(WeightInfoOf::::remove_contribution())] + pub fn remove_contribution(origin: OriginFor, contributor: AccountIdOf) -> DispatchResult { let who = ensure_signed(origin)?; ensure!(who == RegistrarAccount::::get(), BadOrigin); - let looked_up_account = ::Lookup::lookup(contributor_account)?; - Contributions::::take(&looked_up_account).ok_or(Error::::ContributorNotPresent)?; + Contributions::::take(&contributor).ok_or(Error::::ContributorNotPresent)?; - Self::deposit_event(Event::ContributionRemoved(looked_up_account)); + Self::deposit_event(Event::ContributionRemoved(contributor)); Ok(()) } From 6299284114f03234c3208450e358b169c7e2806f Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Tue, 26 Oct 2021 14:33:11 +0200 Subject: [PATCH 02/47] gratitude functionallity --- Cargo.lock | 1 + pallets/crowdloan/Cargo.toml | 14 +- pallets/crowdloan/src/default_weights.rs | 33 +++++ pallets/crowdloan/src/lib.rs | 155 +++++++++++++++++++- pallets/crowdloan/src/storage.rs | 33 +++++ runtimes/peregrine/src/lib.rs | 2 + runtimes/peregrine/src/weights/crowdloan.rs | 15 ++ runtimes/spiritnet/src/lib.rs | 2 + runtimes/spiritnet/src/weights/crowdloan.rs | 15 ++ runtimes/standalone/src/lib.rs | 16 +- 10 files changed, 271 insertions(+), 15 deletions(-) create mode 100644 pallets/crowdloan/src/storage.rs diff --git a/Cargo.lock b/Cargo.lock index 51d52d0b8..66214822f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1349,6 +1349,7 @@ dependencies = [ "frame-system", "kilt-primitives", "pallet-balances", + "pallet-vesting", "parity-scale-codec", "scale-info", "serde", diff --git a/pallets/crowdloan/Cargo.toml b/pallets/crowdloan/Cargo.toml index 330e8b9e2..1178f8b71 100644 --- a/pallets/crowdloan/Cargo.toml +++ b/pallets/crowdloan/Cargo.toml @@ -13,24 +13,28 @@ targets = ["x86_64-unknown-linux-gnu"] substrate-wasm-builder-runner = {version = "3.0.0"} [dev-dependencies] -kilt-primitives = {default-features = false, path = "../../primitives"} pallet-balances = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} serde = {version = "1.0.101"} -sp-keystore = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} sp-io = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} +sp-keystore = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} [dependencies] serde = {optional = true, version = "1.0.101"} -# Substrate dependencies codec = {default-features = false, features = ["derive"], package = "parity-scale-codec", version = "2.0.0"} +scale-info = {version = "1.0", default-features = false, features = ["derive"]} + +# Substrate dependencies frame-benchmarking = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate", optional = true} frame-support = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} frame-system = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} -scale-info = { version = "1.0", default-features = false, features = ["derive"] } +pallet-vesting = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} sp-runtime = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} sp-std = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} +# KILT dependencies +kilt-primitives = {default-features = false, path = "../../primitives"} + [features] default = ["std"] @@ -46,6 +50,8 @@ std = [ "scale-info/std", "sp-runtime/std", "sp-std/std", + "pallet-vesting/std", + "kilt-primitives/std", ] try-runtime = [ diff --git a/pallets/crowdloan/src/default_weights.rs b/pallets/crowdloan/src/default_weights.rs index 33cfc7c03..019f61560 100644 --- a/pallets/crowdloan/src/default_weights.rs +++ b/pallets/crowdloan/src/default_weights.rs @@ -47,13 +47,21 @@ use sp_std::marker::PhantomData; /// Weight functions needed for crowdloan. pub trait WeightInfo { fn set_registrar_account() -> Weight; + fn set_reserve_accounts() -> Weight; fn set_contribution() -> Weight; fn remove_contribution() -> Weight; + fn receive_gratitude() -> Weight; + fn set_config() -> Weight; } /// Weights for crowdloan using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { + fn set_reserve_accounts() -> Weight { + (18_544_000_u64) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } fn set_registrar_account() -> Weight { (18_544_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) @@ -69,10 +77,25 @@ impl WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } + fn receive_gratitude() -> Weight { + (21_661_000_u64) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + fn set_config() -> Weight { + (21_661_000_u64) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } } // For backwards compatibility and tests impl WeightInfo for () { + fn set_reserve_accounts() -> Weight { + (18_544_000_u64) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } fn set_registrar_account() -> Weight { (18_544_000_u64) .saturating_add(RocksDbWeight::get().reads(1_u64)) @@ -88,4 +111,14 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } + fn receive_gratitude() -> Weight { + (21_661_000_u64) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + fn set_config() -> Weight { + (21_661_000_u64) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } } diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index 4ea608355..4f5dbf03c 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -49,31 +49,41 @@ mod mock; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; -pub use crate::{default_weights::WeightInfo, pallet::*}; +mod storage; + +pub use crate::{default_weights::WeightInfo, pallet::*, storage::*}; #[frame_support::pallet] pub mod pallet { use super::WeightInfo; use frame_support::{ pallet_prelude::*, - traits::{Currency, StorageVersion}, + traits::{Currency, ExistenceRequirement, StorageVersion, VestingSchedule, WithdrawReasons}, }; use frame_system::{pallet_prelude::*, EnsureOneOf, EnsureSigned}; use sp_runtime::{ - traits::{BadOrigin, StaticLookup}, + traits::{BadOrigin, Saturating, StaticLookup}, Either, }; + use sp_std::vec; + + use crate::storage::{GratitudeConfig, ReserveAccounts}; pub(crate) type AccountIdOf = ::AccountId; pub(crate) type BalanceOf = <::Currency as Currency>>::Balance; + pub(crate) type CurrencyOf = ::Currency; + pub(crate) type VestingOf = ::Vesting; pub(crate) type WeightInfoOf = ::WeightInfo; + pub(crate) type BlockNumberOf = ::BlockNumber; pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); #[pallet::config] pub trait Config: frame_system::Config { /// Currency type. - type Currency: Currency>; + type Currency: Currency, Balance = Self::Balance>; + type Vesting: VestingSchedule, Currency = Self::Currency, Moment = BlockNumberOf>; + type Balance: sp_runtime::traits::AtLeast32BitUnsigned + Parameter + Copy + Default + From; /// Overarching event type. type Event: From> + IsType<::Event>; /// The origin allowed to change the registrar account. @@ -116,6 +126,16 @@ pub mod pallet { #[pallet::getter(fn registrar_account)] pub type RegistrarAccount = StorageValue<_, AccountIdOf, ValueQuery>; + /// The account from which the vested amount is transferred. + #[pallet::storage] + #[pallet::getter(fn reserve)] + pub type Reserve = StorageValue<_, ReserveAccounts>, ValueQuery>; + + /// The account from which the free amount is transferred. + #[pallet::storage] + #[pallet::getter(fn configuration)] + pub type Configuration = StorageValue<_, GratitudeConfig<::BlockNumber>, ValueQuery>; + /// The set of contributions. /// /// It maps from contributor's account to amount contributed. @@ -129,12 +149,27 @@ pub mod pallet { /// A new registrar has been set. /// \[old registrar account, new registrar account\] NewRegistrarAccountSet(AccountIdOf, AccountIdOf), + + /// New reserve accounts have been set. + /// \[old vested reserve account, old free reserve account, new vested + /// reserve account, new free reserve account\] + NewReserveAccounts(AccountIdOf, AccountIdOf, AccountIdOf, AccountIdOf), + /// A contribution has been set. /// \[contributor account, old amount (OPTIONAL), new amount\] ContributionSet(AccountIdOf, Option>, BalanceOf), + /// A contribution has been removed. /// \[contributor account\] ContributionRemoved(AccountIdOf), + + /// Our gratitude goes out to the \[account\]. + /// \[contributor account\] + GratitudeReceived(AccountIdOf), + + /// A new configuration was set. + /// \[new configuration\] + UpdatedConfig(GratitudeConfig>), } #[pallet::error] @@ -180,6 +215,50 @@ pub mod pallet { Ok(()) } + #[pallet::weight(WeightInfoOf::::set_reserve_accounts())] + pub fn set_reserve_accounts( + origin: OriginFor, + new_vested_reserve: ::Source, + new_free_reserve: ::Source, + ) -> DispatchResult { + let who = ensure_signed(origin)?; + ensure!(who == RegistrarAccount::::get(), BadOrigin); + + let new_vested_reserve_acc = ::Lookup::lookup(new_vested_reserve)?; + let new_free_reserve_acc = ::Lookup::lookup(new_free_reserve)?; + + let ReserveAccounts { + vested: old_vested, + free: old_free, + } = Reserve::::get(); + + Reserve::::set(ReserveAccounts { + vested: new_vested_reserve_acc.clone(), + free: new_free_reserve_acc.clone(), + }); + + Self::deposit_event(Event::NewReserveAccounts( + old_vested, + old_free, + new_vested_reserve_acc, + new_free_reserve_acc, + )); + + Ok(()) + } + + #[pallet::weight(WeightInfoOf::::set_config())] + pub fn set_config(origin: OriginFor, new_config: GratitudeConfig>) -> DispatchResult { + let who = ensure_signed(origin)?; + ensure!(who == RegistrarAccount::::get(), BadOrigin); + + Configuration::::set(new_config.clone()); + + Self::deposit_event(Event::UpdatedConfig(new_config)); + + Ok(()) + } + /// Sets a new contribution amount for a given contributor's account. /// /// If a previous contribution is present, it is overridden. @@ -232,5 +311,73 @@ pub mod pallet { Ok(()) } + + /// Receive the gratitude. + /// + /// Moves tokens to the given account according to the vote that was + /// giving in favour of our parachain. + #[pallet::weight((WeightInfoOf::::receive_gratitude(), DispatchClass::Normal, Pays::No))] + pub fn receive_gratitude(origin: OriginFor, receiver: AccountIdOf) -> DispatchResult { + ensure_none(origin)?; + + let amount = Contributions::::get(&receiver).ok_or(Error::::ContributorNotPresent)?; + let config = Configuration::::get(); + let reserve = Reserve::::get(); + + // A two without any trait bounds (no From). + let vested = config.vested_share.mul_floor(amount); + let free = amount.saturating_sub(vested); + + let vested_acc_balance = CurrencyOf::::free_balance(&reserve.vested); + let free_acc_balance = CurrencyOf::::free_balance(&reserve.vested); + CurrencyOf::::ensure_can_withdraw(&reserve.vested, free, WithdrawReasons::TRANSFER, vested_acc_balance)?; + CurrencyOf::::ensure_can_withdraw(&reserve.free, free, WithdrawReasons::TRANSFER, free_acc_balance)?; + + Contributions::::remove(&receiver); + // *** No failure beyond this point! The contributor was removed. *** + + // Transfer the free amount. Should not fail since checked we ensure_can_withdraw. + CurrencyOf::::transfer(&reserve.free, &receiver, free, ExistenceRequirement::AllowDeath)?; + + // Transfer the vested amount and set the vesting schedule. Should not fail since checked we ensure_can_withdraw. + CurrencyOf::::transfer(&reserve.vested, &receiver, vested, ExistenceRequirement::AllowDeath)?; + let per_block = config.per_block_vesting.mul_ceil(vested); + // vesting should not fail since we have transferred enough free balance. + VestingOf::::add_vesting_schedule(&receiver, vested, per_block, config.start_block)?; + + Self::deposit_event(Event::GratitudeReceived(receiver)); + + Ok(()) + } + } + + #[pallet::validate_unsigned] + impl ValidateUnsigned for Pallet { + type Call = Call; + + fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { + const PRIORITY: u64 = 100; + + let claiming_account = match call { + // + // The weight of this logic must be included in the `receive_gratitude` call. + // + Call::receive_gratitude { receiver: account } => account, + _ => return Err(InvalidTransaction::Call.into()), + }; + + ensure!( + Contributions::::contains_key(claiming_account), + InvalidTransaction::BadProof + ); + + Ok(ValidTransaction { + priority: PRIORITY, + requires: vec![], + provides: vec![("gratitude", claiming_account).encode()], + longevity: TransactionLongevity::max_value(), + propagate: true, + }) + } } } diff --git a/pallets/crowdloan/src/storage.rs b/pallets/crowdloan/src/storage.rs new file mode 100644 index 000000000..43b9c9338 --- /dev/null +++ b/pallets/crowdloan/src/storage.rs @@ -0,0 +1,33 @@ +// KILT Blockchain – https://botlabs.org +// Copyright (C) 2019-2021 BOTLabs GmbH + +// The KILT Blockchain is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// The KILT Blockchain is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// If you feel like getting in touch with us, you can do so at info@botlabs.org +use codec::{Decode, Encode}; +use scale_info::TypeInfo; +use sp_runtime::Perquintill; + +#[derive(Clone, Debug, Default, Decode, Encode, TypeInfo)] +pub struct ReserveAccounts { + pub vested: A, + pub free: A, +} + +#[derive(Clone, Debug, Default, Decode, Encode, PartialEq, TypeInfo)] +pub struct GratitudeConfig { + pub vested_share: Perquintill, + pub start_block: BlockNumber, + pub per_block_vesting: Perquintill, +} diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index 31cccc38e..3bceea112 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -616,6 +616,8 @@ impl did::Config for Runtime { impl crowdloan::Config for Runtime { type Currency = Balances; + type Vesting = Vesting; + type Balance = Balance; type EnsureRegistrarOrigin = MoreThanHalfCouncil; type Event = Event; type WeightInfo = weights::crowdloan::WeightInfo; diff --git a/runtimes/peregrine/src/weights/crowdloan.rs b/runtimes/peregrine/src/weights/crowdloan.rs index 8e02bb2ac..7859e3b2b 100644 --- a/runtimes/peregrine/src/weights/crowdloan.rs +++ b/runtimes/peregrine/src/weights/crowdloan.rs @@ -47,6 +47,11 @@ use sp_std::marker::PhantomData; /// Weights for crowdloan using the recommended hardware. pub struct WeightInfo(PhantomData); impl crowdloan::WeightInfo for WeightInfo { + fn set_reserve_accounts() -> Weight { + (18_544_000_u64) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } fn set_registrar_account() -> Weight { (21_643_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) @@ -62,4 +67,14 @@ impl crowdloan::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } + fn receive_gratitude() -> Weight { + (21_661_000_u64) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + fn set_config() -> Weight { + (21_661_000_u64) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } } diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index 73a0306e7..8246637bb 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -693,6 +693,8 @@ impl pallet_randomness_collective_flip::Config for Runtime {} impl crowdloan::Config for Runtime { type Currency = Balances; + type Vesting = Vesting; + type Balance = Balance; type EnsureRegistrarOrigin = MoreThanHalfCouncil; type Event = Event; type WeightInfo = weights::crowdloan::WeightInfo; diff --git a/runtimes/spiritnet/src/weights/crowdloan.rs b/runtimes/spiritnet/src/weights/crowdloan.rs index 8e02bb2ac..7859e3b2b 100644 --- a/runtimes/spiritnet/src/weights/crowdloan.rs +++ b/runtimes/spiritnet/src/weights/crowdloan.rs @@ -47,6 +47,11 @@ use sp_std::marker::PhantomData; /// Weights for crowdloan using the recommended hardware. pub struct WeightInfo(PhantomData); impl crowdloan::WeightInfo for WeightInfo { + fn set_reserve_accounts() -> Weight { + (18_544_000_u64) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } fn set_registrar_account() -> Weight { (21_643_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) @@ -62,4 +67,14 @@ impl crowdloan::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } + fn receive_gratitude() -> Weight { + (21_661_000_u64) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + fn set_config() -> Weight { + (21_661_000_u64) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } } diff --git a/runtimes/standalone/src/lib.rs b/runtimes/standalone/src/lib.rs index 714c92f0b..91f349e61 100644 --- a/runtimes/standalone/src/lib.rs +++ b/runtimes/standalone/src/lib.rs @@ -438,6 +438,15 @@ impl did::Config for Runtime { type WeightInfo = (); } +impl crowdloan::Config for Runtime { + type Currency = Balances; + type Vesting = Vesting; + type Balance = Balance; + type EnsureRegistrarOrigin = EnsureRoot; + type Event = Event; + type WeightInfo = (); +} + parameter_types! { pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); pub const Period: u64 = 0xFFFF_FFFF_FFFF_FFFF; @@ -558,13 +567,6 @@ impl did::DeriveDidCallAuthorizationVerificationKeyRelationship for Call { } } -impl crowdloan::Config for Runtime { - type Currency = Balances; - type EnsureRegistrarOrigin = EnsureRoot; - type Event = Event; - type WeightInfo = (); -} - /// The address format for describing accounts. pub type Address = sp_runtime::MultiAddress; /// Block header type as expected by this runtime. From 4995444a8a08a99b431b8925679b3bd1774de949 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Tue, 26 Oct 2021 16:58:58 +0200 Subject: [PATCH 03/47] test: receive_gratitude --- pallets/crowdloan/Cargo.toml | 9 +- pallets/crowdloan/src/benchmarking.rs | 4 +- pallets/crowdloan/src/lib.rs | 44 ++++- pallets/crowdloan/src/mock.rs | 52 +++++- pallets/crowdloan/src/storage.rs | 2 +- pallets/crowdloan/src/tests.rs | 255 +++++++++++++++++++++++++- 6 files changed, 342 insertions(+), 24 deletions(-) diff --git a/pallets/crowdloan/Cargo.toml b/pallets/crowdloan/Cargo.toml index 1178f8b71..8dbbe6777 100644 --- a/pallets/crowdloan/Cargo.toml +++ b/pallets/crowdloan/Cargo.toml @@ -13,7 +13,9 @@ targets = ["x86_64-unknown-linux-gnu"] substrate-wasm-builder-runner = {version = "3.0.0"} [dev-dependencies] +kilt-primitives = {default-features = false, path = "../../primitives"} pallet-balances = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} +pallet-vesting = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} serde = {version = "1.0.101"} sp-io = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} sp-keystore = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} @@ -28,13 +30,9 @@ scale-info = {version = "1.0", default-features = false, features = ["derive"]} frame-benchmarking = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate", optional = true} frame-support = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} frame-system = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} -pallet-vesting = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} sp-runtime = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} sp-std = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} -# KILT dependencies -kilt-primitives = {default-features = false, path = "../../primitives"} - [features] default = ["std"] @@ -50,8 +48,9 @@ std = [ "scale-info/std", "sp-runtime/std", "sp-std/std", - "pallet-vesting/std", "kilt-primitives/std", + "pallet-balances/std", + "pallet-vesting/std", ] try-runtime = [ diff --git a/pallets/crowdloan/src/benchmarking.rs b/pallets/crowdloan/src/benchmarking.rs index e7218922c..366be1c44 100644 --- a/pallets/crowdloan/src/benchmarking.rs +++ b/pallets/crowdloan/src/benchmarking.rs @@ -44,7 +44,7 @@ benchmarks! { let contributor: AccountIdOf = account("contributor", 0, SEED_2); let contribution: BalanceOf = BalanceOf::::one(); RegistrarAccount::::set(registrar.clone()); - }: _(RawOrigin::Signed(registrar), T::Lookup::unlookup(contributor.clone()), contribution) + }: _(RawOrigin::Signed(registrar), contributor.clone(), contribution) verify { assert_eq!( Contributions::::get(&contributor), @@ -59,7 +59,7 @@ benchmarks! { let contribution: BalanceOf = BalanceOf::::one(); RegistrarAccount::::set(registrar.clone()); Contributions::::insert(&contributor, contribution); - }: _(RawOrigin::Signed(registrar), T::Lookup::unlookup(contributor.clone())) + }: _(RawOrigin::Signed(registrar), contributor.clone()) verify { assert!( Contributions::::get(&contributor).is_none(), diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index 4f5dbf03c..705fa3352 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -62,7 +62,7 @@ pub mod pallet { }; use frame_system::{pallet_prelude::*, EnsureOneOf, EnsureSigned}; use sp_runtime::{ - traits::{BadOrigin, Saturating, StaticLookup}, + traits::{BadOrigin, CheckedDiv, CheckedSub, Saturating, StaticLookup}, Either, }; use sp_std::vec; @@ -79,7 +79,10 @@ pub mod pallet { pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); #[pallet::config] - pub trait Config: frame_system::Config { + pub trait Config: frame_system::Config + where + Self::Balance: From>, + { /// Currency type. type Currency: Currency, Balance = Self::Balance>; type Vesting: VestingSchedule, Currency = Self::Currency, Moment = BlockNumberOf>; @@ -176,6 +179,9 @@ pub mod pallet { pub enum Error { /// The contribution is not present. ContributorNotPresent, + + /// The reserve account run out of funds. + InsufficientBalance, } #[pallet::call] @@ -328,20 +334,40 @@ pub mod pallet { let vested = config.vested_share.mul_floor(amount); let free = amount.saturating_sub(vested); - let vested_acc_balance = CurrencyOf::::free_balance(&reserve.vested); - let free_acc_balance = CurrencyOf::::free_balance(&reserve.vested); - CurrencyOf::::ensure_can_withdraw(&reserve.vested, free, WithdrawReasons::TRANSFER, vested_acc_balance)?; - CurrencyOf::::ensure_can_withdraw(&reserve.free, free, WithdrawReasons::TRANSFER, free_acc_balance)?; + let new_free_acc_balance = CurrencyOf::::free_balance(&reserve.free) + .checked_sub(&free) + .ok_or(Error::::InsufficientBalance)?; + let mut new_vested_acc_balance = CurrencyOf::::free_balance(&reserve.vested) + .checked_sub(&vested) + .ok_or(Error::::InsufficientBalance)?; + if reserve.free == reserve.vested { + // if free and vested are the same we need to make sure that we can withdraw + // both from the same account + new_vested_acc_balance = new_vested_acc_balance + .checked_sub(&free) + .ok_or(Error::::InsufficientBalance)?; + } + CurrencyOf::::ensure_can_withdraw(&reserve.free, free, WithdrawReasons::TRANSFER, new_free_acc_balance)?; + CurrencyOf::::ensure_can_withdraw( + &reserve.vested, + vested, + WithdrawReasons::TRANSFER, + new_vested_acc_balance, + )?; Contributions::::remove(&receiver); // *** No failure beyond this point! The contributor was removed. *** - // Transfer the free amount. Should not fail since checked we ensure_can_withdraw. + // Transfer the free amount. Should not fail since checked we + // ensure_can_withdraw. CurrencyOf::::transfer(&reserve.free, &receiver, free, ExistenceRequirement::AllowDeath)?; - // Transfer the vested amount and set the vesting schedule. Should not fail since checked we ensure_can_withdraw. + // Transfer the vested amount and set the vesting schedule. Should not fail + // since checked we ensure_can_withdraw. CurrencyOf::::transfer(&reserve.vested, &receiver, vested, ExistenceRequirement::AllowDeath)?; - let per_block = config.per_block_vesting.mul_ceil(vested); + let per_block = vested + .checked_div(&BalanceOf::::from(config.vesting_length)) + .unwrap_or(vested); // vesting should not fail since we have transferred enough free balance. VestingOf::::add_vesting_schedule(&receiver, vested, per_block, config.start_block)?; diff --git a/pallets/crowdloan/src/mock.rs b/pallets/crowdloan/src/mock.rs index 3eda73050..4327f8def 100644 --- a/pallets/crowdloan/src/mock.rs +++ b/pallets/crowdloan/src/mock.rs @@ -16,13 +16,13 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org -use crate::pallet as pallet_crowdloan; +use crate::{pallet as pallet_crowdloan, GratitudeConfig, ReserveAccounts}; use frame_support::parameter_types; use frame_system::{EnsureRoot, EventRecord}; use kilt_primitives::{constants::KILT, AccountId, Balance, BlockNumber, Hash, Index}; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, ConvertInto, IdentityLookup}, }; type TestUncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -39,6 +39,7 @@ frame_support::construct_runtime!( { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Event}, + Vesting: pallet_vesting::{Pallet, Call, Storage, Event}, Crowdloan: pallet_crowdloan::{Pallet, Call, Config, Storage, Event} } ); @@ -92,8 +93,24 @@ impl pallet_balances::Config for Test { type WeightInfo = (); } +parameter_types! { + pub const MinVestedTransfer: TestBalance = 500; +} + +impl pallet_vesting::Config for Test { + type Event = Event; + type Currency = Balances; + type BlockNumberToBalance = ConvertInto; + // disable vested transfers by setting min amount to max balance + type MinVestedTransfer = MinVestedTransfer; + type WeightInfo = (); + const MAX_VESTING_SCHEDULES: u32 = kilt_primitives::constants::MAX_VESTING_SCHEDULES; +} + impl pallet_crowdloan::Config for Test { type Currency = Balances; + type Vesting = Vesting; + type Balance = TestBalance; type EnsureRegistrarOrigin = TestOrigin; type Event = Event; type WeightInfo = (); @@ -101,9 +118,13 @@ impl pallet_crowdloan::Config for Test { pub(crate) const ACCOUNT_00: TestAccountId = AccountId::new([0u8; 32]); pub(crate) const ACCOUNT_01: TestAccountId = AccountId::new([1u8; 32]); +pub(crate) const ACCOUNT_02: TestAccountId = AccountId::new([2u8; 32]); +pub(crate) const ACCOUNT_03: TestAccountId = AccountId::new([3u8; 32]); #[allow(clippy::identity_op)] pub(crate) const BALANCE_01: TestBalance = 1 * KILT; pub(crate) const BALANCE_02: TestBalance = 2 * KILT; +pub(crate) const BALANCE_03: TestBalance = 3 * KILT; +pub(crate) const BALANCE_04: TestBalance = 4 * KILT; pub(crate) fn get_generated_events() -> Vec> { let events = System::events(); @@ -117,6 +138,9 @@ pub(crate) fn get_generated_events() -> Vec, + config: GratitudeConfig, + reserve: ReserveAccounts, + balances: Vec<(TestAccountId, TestBalance)>, } impl ExtBuilder { @@ -130,14 +154,36 @@ impl ExtBuilder { self } + pub(crate) fn with_configuration(mut self, config: GratitudeConfig) -> Self { + self.config = config; + self + } + + pub(crate) fn with_reserve(mut self, reserve: ReserveAccounts) -> Self { + self.reserve = reserve; + self + } + + pub(crate) fn with_balances(mut self, balances: Vec<(TestAccountId, TestBalance)>) -> Self { + self.balances = balances; + self + } + pub(crate) fn build(self) -> sp_io::TestExternalities { - let storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + pallet_balances::GenesisConfig:: { + balances: self.balances.clone(), + } + .assimilate_storage(&mut storage) + .expect("assimilate should not fail"); let mut ext = sp_io::TestExternalities::new(storage); ext.execute_with(|| { // Needed to test event generation. System::set_block_number(1); pallet_crowdloan::RegistrarAccount::::set(self.registrar_account); + pallet_crowdloan::Reserve::::set(self.reserve); + pallet_crowdloan::Configuration::::set(self.config); for (contributor_account, contribution_amount) in self.contributions.iter() { pallet_crowdloan::Contributions::::insert(contributor_account, contribution_amount); diff --git a/pallets/crowdloan/src/storage.rs b/pallets/crowdloan/src/storage.rs index 43b9c9338..0afa16745 100644 --- a/pallets/crowdloan/src/storage.rs +++ b/pallets/crowdloan/src/storage.rs @@ -29,5 +29,5 @@ pub struct ReserveAccounts { pub struct GratitudeConfig { pub vested_share: Perquintill, pub start_block: BlockNumber, - pub per_block_vesting: Perquintill, + pub vesting_length: BlockNumber, } diff --git a/pallets/crowdloan/src/tests.rs b/pallets/crowdloan/src/tests.rs index 5dbc42504..e6beb2aa2 100644 --- a/pallets/crowdloan/src/tests.rs +++ b/pallets/crowdloan/src/tests.rs @@ -16,10 +16,17 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org -use frame_support::{assert_noop, assert_ok}; -use sp_runtime::traits::BadOrigin; - -use crate::mock::*; +use codec::Encode; +use frame_support::{ + assert_noop, assert_ok, + pallet_prelude::{InvalidTransaction, TransactionLongevity, ValidTransaction}, +}; +use sp_runtime::{ + traits::{BadOrigin, Zero}, + Perquintill, +}; + +use crate::{mock::*, GratitudeConfig, ReserveAccounts}; // set_registrar_account @@ -241,3 +248,243 @@ fn test_remove_contribution_absent_error() { ); }); } + +#[test] +fn test_send_gratitude_success() { + let registrar = ACCOUNT_00; + let contributor = ACCOUNT_01; + let free_reserve = ACCOUNT_02; + let vested_reserve = ACCOUNT_03; + + ExtBuilder::default() + .with_reserve(ReserveAccounts { + vested: vested_reserve.clone(), + free: free_reserve.clone(), + }) + .with_registrar_account(registrar.clone()) + .with_balances(vec![ + (free_reserve.clone(), BALANCE_01), + (vested_reserve.clone(), BALANCE_01), + ]) + .with_contributions(vec![(contributor.clone(), BALANCE_02)]) + .with_configuration(GratitudeConfig { + vested_share: Perquintill::from_percent(50), + start_block: 1, + vesting_length: 10, + }) + .build() + .execute_with(|| { + assert_ok!(Crowdloan::receive_gratitude(Origin::none(), contributor.clone())); + assert_eq!( + pallet_balances::Pallet::::free_balance(contributor.clone()), + BALANCE_02 + ); + assert!(pallet_balances::Pallet::::free_balance(free_reserve.clone()).is_zero()); + assert!(pallet_balances::Pallet::::free_balance(vested_reserve.clone()).is_zero()); + assert!(crate::Contributions::::get(&contributor).is_none()); + + assert_noop!( + Crowdloan::receive_gratitude(Origin::none(), contributor.clone()), + crate::Error::::ContributorNotPresent + ); + }); +} + +#[test] +fn test_send_gratitude_empty_free_reserve() { + let registrar = ACCOUNT_00; + let contributor = ACCOUNT_01; + let free_reserve = ACCOUNT_02; + let vested_reserve = ACCOUNT_03; + + ExtBuilder::default() + .with_reserve(ReserveAccounts { + vested: vested_reserve.clone(), + free: free_reserve.clone(), + }) + .with_registrar_account(registrar.clone()) + .with_balances(vec![(vested_reserve.clone(), BALANCE_02)]) + .with_contributions(vec![(contributor.clone(), BALANCE_02)]) + .with_configuration(GratitudeConfig { + vested_share: Perquintill::from_percent(50), + start_block: 1, + vesting_length: 10, + }) + .build() + .execute_with(|| { + assert_noop!( + Crowdloan::receive_gratitude(Origin::none(), contributor), + crate::Error::::InsufficientBalance + ); + }); +} + +#[test] +fn test_send_gratitude_empty_vest_reserve() { + let registrar = ACCOUNT_00; + let contributor = ACCOUNT_01; + let free_reserve = ACCOUNT_02; + let vested_reserve = ACCOUNT_03; + + ExtBuilder::default() + .with_reserve(ReserveAccounts { + vested: vested_reserve.clone(), + free: free_reserve.clone(), + }) + .with_registrar_account(registrar.clone()) + .with_balances(vec![(free_reserve.clone(), BALANCE_02)]) + .with_contributions(vec![(contributor.clone(), BALANCE_02)]) + .with_configuration(GratitudeConfig { + vested_share: Perquintill::from_percent(50), + start_block: 1, + vesting_length: 10, + }) + .build() + .execute_with(|| { + assert_noop!( + Crowdloan::receive_gratitude(Origin::none(), contributor), + crate::Error::::InsufficientBalance + ); + }); +} + +#[test] +fn test_send_gratitude_same_account_success() { + let registrar = ACCOUNT_00; + let contributor = ACCOUNT_01; + let free_reserve = ACCOUNT_02; + let vested_reserve = ACCOUNT_02; + + ExtBuilder::default() + .with_reserve(ReserveAccounts { + vested: vested_reserve.clone(), + free: free_reserve.clone(), + }) + .with_registrar_account(registrar.clone()) + .with_balances(vec![(free_reserve.clone(), BALANCE_02)]) + .with_contributions(vec![(contributor.clone(), BALANCE_02)]) + .with_configuration(GratitudeConfig { + vested_share: Perquintill::from_percent(50), + start_block: 1, + vesting_length: 10, + }) + .build() + .execute_with(|| { + assert_ok!(Crowdloan::receive_gratitude(Origin::none(), contributor.clone())); + assert_eq!( + pallet_balances::Pallet::::free_balance(contributor.clone()), + BALANCE_02 + ); + assert!(pallet_balances::Pallet::::free_balance(free_reserve.clone()).is_zero()); + assert!(crate::Contributions::::get(&contributor).is_none()); + + assert_noop!( + Crowdloan::receive_gratitude(Origin::none(), contributor.clone()), + crate::Error::::ContributorNotPresent + ); + }); +} + +#[test] +fn test_send_gratitude_same_account_out_of_funds() { + let registrar = ACCOUNT_00; + let contributor = ACCOUNT_01; + let free_reserve = ACCOUNT_02; + let vested_reserve = ACCOUNT_02; + + ExtBuilder::default() + .with_reserve(ReserveAccounts { + vested: vested_reserve.clone(), + free: free_reserve.clone(), + }) + .with_registrar_account(registrar.clone()) + .with_balances(vec![(free_reserve.clone(), BALANCE_01)]) + .with_contributions(vec![(contributor.clone(), BALANCE_02)]) + .with_configuration(GratitudeConfig { + vested_share: Perquintill::from_percent(50), + start_block: 1, + vesting_length: 10, + }) + .build() + .execute_with(|| { + assert_noop!( + Crowdloan::receive_gratitude(Origin::none(), contributor), + crate::Error::::InsufficientBalance + ); + }); +} + +#[test] +fn test_send_gratitude_contribution_not_found() { + let registrar = ACCOUNT_00; + let contributor = ACCOUNT_01; + let free_reserve = ACCOUNT_02; + let vested_reserve = ACCOUNT_02; + + ExtBuilder::default() + .with_reserve(ReserveAccounts { + vested: vested_reserve.clone(), + free: free_reserve.clone(), + }) + .with_registrar_account(registrar.clone()) + .with_balances(vec![(free_reserve.clone(), BALANCE_01)]) + .with_configuration(GratitudeConfig { + vested_share: Perquintill::from_percent(50), + start_block: 1, + vesting_length: 10, + }) + .build() + .execute_with(|| { + assert_noop!( + Crowdloan::receive_gratitude(Origin::none(), contributor), + crate::Error::::ContributorNotPresent + ); + }); +} + +#[test] +fn validate_unsigned_works() { + use sp_runtime::traits::ValidateUnsigned; + let source = sp_runtime::transaction_validity::TransactionSource::External; + let contributor = || ACCOUNT_00.clone(); + ExtBuilder::default() + .with_contributions(vec![(contributor(), BALANCE_02)]) + .build() + .execute_with(|| { + assert_eq!( + crate::Pallet::::validate_unsigned( + source, + &crate::Call::receive_gratitude { + receiver: contributor() + } + ), + Ok(ValidTransaction { + priority: 100, + requires: vec![], + provides: vec![("gratitude", contributor()).encode()], + longevity: TransactionLongevity::max_value(), + propagate: true, + }) + ); + + assert_eq!( + crate::Pallet::::validate_unsigned( + source, + &crate::Call::receive_gratitude { + receiver: ACCOUNT_02.clone() + } + ), + Err(InvalidTransaction::BadProof.into()) + ); + + assert_eq!( + crate::Pallet::::validate_unsigned( + source, + &crate::Call::remove_contribution { + contributor: ACCOUNT_02.clone() + } + ), + Err(InvalidTransaction::Call.into()) + ); + }) +} From fe3312bee63532e2bbecd9a6baada547c75be34a Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Tue, 26 Oct 2021 17:39:15 +0200 Subject: [PATCH 04/47] feat: benchmark --- pallets/crowdloan/src/benchmarking.rs | 84 ++++++++++++++++++++++++++- pallets/crowdloan/src/mock.rs | 3 +- pallets/crowdloan/src/storage.rs | 2 +- pallets/crowdloan/src/tests.rs | 83 ++++++++++++++++++++++++++ 4 files changed, 168 insertions(+), 4 deletions(-) diff --git a/pallets/crowdloan/src/benchmarking.rs b/pallets/crowdloan/src/benchmarking.rs index 366be1c44..0e6e4a216 100644 --- a/pallets/crowdloan/src/benchmarking.rs +++ b/pallets/crowdloan/src/benchmarking.rs @@ -18,14 +18,21 @@ use crate::*; +use codec::{Decode, Encode}; use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite}; +use frame_support::{dispatch::UnfilteredDispatchable, traits::Currency, unsigned::ValidateUnsigned}; use frame_system::RawOrigin; -use sp_runtime::traits::{One, StaticLookup}; +use sp_runtime::{ + traits::{One, StaticLookup}, + Perquintill, +}; const SEED_1: u32 = 1; const SEED_2: u32 = 2; benchmarks! { + where_clause { where ::BlockNumber: From } + set_registrar_account { let registrar: AccountIdOf = account("registrar", 0, SEED_1); let new_registrar: AccountIdOf = account("new_registrar", 0, SEED_2); @@ -53,6 +60,81 @@ benchmarks! { ); } + set_config { + let registrar: AccountIdOf = account("registrar", 0, SEED_1); + RegistrarAccount::::set(registrar.clone()); + + let config = GratitudeConfig:: { + vested_share: Perquintill::from_percent(42), + start_block: 1.into(), + vesting_length: 10.into(), + }; + }: _(RawOrigin::Signed(registrar), config.clone()) + verify { + assert_eq!( + Configuration::::get(), + config, + ); + } + + set_reserve_accounts { + let registrar: AccountIdOf = account("registrar", 0, SEED_1); + let reserve_free: AccountIdOf = account("reserve_free", 0, SEED_1); + let reserve_vested: AccountIdOf = account("reserve_vested", 0, SEED_1); + RegistrarAccount::::set(registrar.clone()); + + }: _( + RawOrigin::Signed(registrar), + T::Lookup::unlookup(reserve_vested.clone()), + T::Lookup::unlookup(reserve_free.clone()) + ) + verify { + assert_eq!( + crate::Reserve::::get(), + ReserveAccounts { + vested: reserve_vested, + free: reserve_free, + } + ); + } + + // receive_gratitude is benchmarked together with validate_unsigned to accommodate for the additional cost of validate_unsigned + receive_gratitude { + let registrar: AccountIdOf = account("registrar", 0, SEED_1); + let reserve_free: AccountIdOf = account("reserve_free", 0, SEED_1); + let reserve_vested: AccountIdOf = account("reserve_vested", 0, SEED_1); + let contributor: AccountIdOf = account("contributor", 0, SEED_1); + + let contribution: BalanceOf = CurrencyOf::::minimum_balance() + + CurrencyOf::::minimum_balance() + + CurrencyOf::::minimum_balance(); + + RegistrarAccount::::set(registrar.clone()); + Reserve::::set(ReserveAccounts { + vested: reserve_vested.clone(), + free: reserve_free.clone(), + }); + Contributions::::insert(&contributor, contribution); + Configuration::::set(GratitudeConfig { + vested_share: Perquintill::from_percent(50), + start_block: 1.into(), + vesting_length: 10.into(), + }); + + let source = sp_runtime::transaction_validity::TransactionSource::External; + let call_enc = Call::::receive_gratitude { + receiver: contributor.clone(), + }.encode(); + }: { + let call = as Decode>::decode(&mut &*call_enc) + .expect("call is encoded above, encoding must be correct"); + crate::Pallet::::validate_unsigned(source, &call).map_err(|e| -> &'static str { e.into() })?; + call.dispatch_bypass_filter(RawOrigin::None.into())?; + } + verify { + assert!(crate::Contributions::::get(contributor).is_none()); + } + remove_contribution { let registrar: AccountIdOf = account("registrar", 0, SEED_1); let contributor: AccountIdOf = account("contributor", 0, SEED_2); diff --git a/pallets/crowdloan/src/mock.rs b/pallets/crowdloan/src/mock.rs index 4327f8def..4b1eba834 100644 --- a/pallets/crowdloan/src/mock.rs +++ b/pallets/crowdloan/src/mock.rs @@ -120,11 +120,10 @@ pub(crate) const ACCOUNT_00: TestAccountId = AccountId::new([0u8; 32]); pub(crate) const ACCOUNT_01: TestAccountId = AccountId::new([1u8; 32]); pub(crate) const ACCOUNT_02: TestAccountId = AccountId::new([2u8; 32]); pub(crate) const ACCOUNT_03: TestAccountId = AccountId::new([3u8; 32]); +pub(crate) const ACCOUNT_04: TestAccountId = AccountId::new([4u8; 32]); #[allow(clippy::identity_op)] pub(crate) const BALANCE_01: TestBalance = 1 * KILT; pub(crate) const BALANCE_02: TestBalance = 2 * KILT; -pub(crate) const BALANCE_03: TestBalance = 3 * KILT; -pub(crate) const BALANCE_04: TestBalance = 4 * KILT; pub(crate) fn get_generated_events() -> Vec> { let events = System::events(); diff --git a/pallets/crowdloan/src/storage.rs b/pallets/crowdloan/src/storage.rs index 0afa16745..0cda58823 100644 --- a/pallets/crowdloan/src/storage.rs +++ b/pallets/crowdloan/src/storage.rs @@ -19,7 +19,7 @@ use codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::Perquintill; -#[derive(Clone, Debug, Default, Decode, Encode, TypeInfo)] +#[derive(Clone, Debug, Default, Decode, PartialEq, Encode, TypeInfo)] pub struct ReserveAccounts { pub vested: A, pub free: A, diff --git a/pallets/crowdloan/src/tests.rs b/pallets/crowdloan/src/tests.rs index e6beb2aa2..9ca9a9ee3 100644 --- a/pallets/crowdloan/src/tests.rs +++ b/pallets/crowdloan/src/tests.rs @@ -28,6 +28,7 @@ use sp_runtime::{ use crate::{mock::*, GratitudeConfig, ReserveAccounts}; +// ############################################################################# // set_registrar_account #[test] @@ -114,6 +115,7 @@ fn test_set_registrar_account_bad_origin_error() { }); } +// ############################################################################# // set_contribution #[test] @@ -184,6 +186,7 @@ fn test_set_contribution_bad_origin_error() { }); } +// ############################################################################# // remove_contribution #[test] @@ -249,6 +252,9 @@ fn test_remove_contribution_absent_error() { }); } +// ############################################################################# +// Send Gratitude + #[test] fn test_send_gratitude_success() { let registrar = ACCOUNT_00; @@ -442,6 +448,9 @@ fn test_send_gratitude_contribution_not_found() { }); } +// ############################################################################# +// validate_unsigned + #[test] fn validate_unsigned_works() { use sp_runtime::traits::ValidateUnsigned; @@ -488,3 +497,77 @@ fn validate_unsigned_works() { ); }) } + +// ############################################################################# +// Set configuration + +#[test] +fn test_set_configuration() { + let registrar = ACCOUNT_00; + let contributor = ACCOUNT_01; + let free_reserve = ACCOUNT_02; + let vested_reserve = ACCOUNT_02; + let config = GratitudeConfig { + vested_share: Perquintill::from_percent(50), + start_block: 1, + vesting_length: 10, + }; + + ExtBuilder::default() + .with_reserve(ReserveAccounts { + vested: vested_reserve.clone(), + free: free_reserve.clone(), + }) + .with_registrar_account(registrar.clone()) + .build() + .execute_with(|| { + assert!(crate::Configuration::::get() != config); + assert_ok!(Crowdloan::set_config(Origin::signed(registrar), config.clone())); + assert_eq!(crate::Configuration::::get(), config); + assert_noop!(Crowdloan::set_config(Origin::signed(contributor), config), BadOrigin); + }); +} + +// ############################################################################# +// Set reserve + +#[test] +fn test_set_reserve() { + let registrar = || ACCOUNT_00.clone(); + let contributor = || ACCOUNT_01.clone(); + let free_reserve_old = || ACCOUNT_01.clone(); + let vested_reserve_old = || ACCOUNT_02.clone(); + let free_reserve_new = || ACCOUNT_03.clone(); + let vested_reserve_new = || ACCOUNT_04.clone(); + + ExtBuilder::default() + .with_reserve(ReserveAccounts { + vested: vested_reserve_old(), + free: free_reserve_old(), + }) + .with_registrar_account(registrar()) + .build() + .execute_with(|| { + assert_ok!(Crowdloan::set_reserve_accounts( + Origin::signed(registrar()), + vested_reserve_new(), + free_reserve_new() + )); + assert_eq!( + crate::Reserve::::get(), + ReserveAccounts { + vested: vested_reserve_new(), + free: free_reserve_new(), + } + ); + + assert_noop!( + Crowdloan::set_reserve_accounts( + Origin::signed(contributor()), + vested_reserve_old(), + free_reserve_old() + ), + BadOrigin + ); + }); +} From 7760917819de186267f71a824185988a3a8b51d1 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Tue, 26 Oct 2021 17:59:55 +0200 Subject: [PATCH 05/47] fix benchmarks --- Cargo.lock | 4 ++-- pallets/crowdloan/Cargo.toml | 11 ++++++++++- support/Cargo.toml | 2 +- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 66214822f..6dd6d8a47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1342,7 +1342,7 @@ dependencies = [ [[package]] name = "crowdloan" -version = "0.26.2" +version = "1.0.0" dependencies = [ "frame-benchmarking", "frame-support", @@ -3605,7 +3605,7 @@ dependencies = [ [[package]] name = "kilt-support" -version = "0.26.1" +version = "1.0.0" dependencies = [ "frame-support", "parity-scale-codec", diff --git a/pallets/crowdloan/Cargo.toml b/pallets/crowdloan/Cargo.toml index 8dbbe6777..8508e8d64 100644 --- a/pallets/crowdloan/Cargo.toml +++ b/pallets/crowdloan/Cargo.toml @@ -4,7 +4,7 @@ description = "Substrate pallet allowing to register crowdloan contributors." edition = "2018" name = "crowdloan" repository = "https://github.com/KILTprotocol/mashnet-node" -version = "0.26.2" +version = "1.0.0" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -33,11 +33,20 @@ frame-system = {branch = "polkadot-v0.9.11", default-features = false, git = "ht sp-runtime = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} sp-std = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} +pallet-balances = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate", optional = true} +pallet-vesting = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate", optional = true} +kilt-primitives = {default-features = false, path = "../../primitives", optional = true} + [features] default = ["std"] runtime-benchmarks = [ "frame-benchmarking", + "pallet-balances", + "pallet-balances/frame-benchmarking", + "pallet-vesting", + "pallet-vesting/frame-benchmarking", + "kilt-primitives", ] std = [ diff --git a/support/Cargo.toml b/support/Cargo.toml index 05527ec5d..2cba8d382 100644 --- a/support/Cargo.toml +++ b/support/Cargo.toml @@ -4,7 +4,7 @@ description = "Shared traits and structs used across the KILT pallets" edition = "2018" name = "kilt-support" repository = "https://github.com/KILTprotocol/mashnet-node" -version = "0.26.1" +version = "1.0.0" [dependencies] codec = {default-features = false, features = ["derive"], package = "parity-scale-codec", version = "2.3.1"} From 11237fb51f6b7971ae25926303d56281b9471acc Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 07:16:23 +0200 Subject: [PATCH 06/47] fix benchmark --- pallets/crowdloan/src/benchmarking.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pallets/crowdloan/src/benchmarking.rs b/pallets/crowdloan/src/benchmarking.rs index 0e6e4a216..09f2b57a5 100644 --- a/pallets/crowdloan/src/benchmarking.rs +++ b/pallets/crowdloan/src/benchmarking.rs @@ -120,6 +120,8 @@ benchmarks! { start_block: 1.into(), vesting_length: 10.into(), }); + CurrencyOf::::make_free_balance_be(&reserve_vested, contribution); + CurrencyOf::::make_free_balance_be(&reserve_free, contribution); let source = sp_runtime::transaction_validity::TransactionSource::External; let call_enc = Call::::receive_gratitude { From e037a8fd3c8bc11271122782d75f4e20b5fef373 Mon Sep 17 00:00:00 2001 From: kiltbot <> Date: Wed, 27 Oct 2021 07:20:20 +0200 Subject: [PATCH 07/47] cargo run --quiet --release -p kilt-parachain --features=runtime-benchmarks -- benchmark --chain=spiritnet-dev --steps=50 --repeat=20 --pallet=crowdloan --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./runtimes/spiritnet/src/weights/crowdloan.rs --template=.maintain/runtime-weight-template.hbs --- runtimes/spiritnet/src/weights/crowdloan.rs | 32 ++++++++++----------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/runtimes/spiritnet/src/weights/crowdloan.rs b/runtimes/spiritnet/src/weights/crowdloan.rs index 7859e3b2b..ddf142620 100644 --- a/runtimes/spiritnet/src/weights/crowdloan.rs +++ b/runtimes/spiritnet/src/weights/crowdloan.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for crowdloan //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-10-20, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2021-10-27, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("spiritnet-dev"), DB CACHE: 128 // Executed Command: @@ -47,34 +47,34 @@ use sp_std::marker::PhantomData; /// Weights for crowdloan using the recommended hardware. pub struct WeightInfo(PhantomData); impl crowdloan::WeightInfo for WeightInfo { - fn set_reserve_accounts() -> Weight { - (18_544_000_u64) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } fn set_registrar_account() -> Weight { - (21_643_000_u64) + (20_486_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_contribution() -> Weight { - (24_614_000_u64) + (23_339_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - fn remove_contribution() -> Weight { - (25_340_000_u64) - .saturating_add(T::DbWeight::get().reads(2_u64)) + fn set_config() -> Weight { + (20_299_000_u64) + .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - fn receive_gratitude() -> Weight { - (21_661_000_u64) + fn set_reserve_accounts() -> Weight { + (24_210_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - fn set_config() -> Weight { - (21_661_000_u64) + fn receive_gratitude() -> Weight { + (164_039_000_u64) + .saturating_add(T::DbWeight::get().reads(8_u64)) + .saturating_add(T::DbWeight::get().writes(6_u64)) + } + fn remove_contribution() -> Weight { + (24_835_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } -} +} \ No newline at end of file From 21ebaffdf68c3b8aac72af4910fdd4bd2bbf0519 Mon Sep 17 00:00:00 2001 From: kiltbot <> Date: Wed, 27 Oct 2021 08:12:20 +0200 Subject: [PATCH 08/47] cargo run --quiet --release -p kilt-parachain --features=runtime-benchmarks -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=crowdloan --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./runtimes/peregrine/src/weights/crowdloan.rs --template=.maintain/runtime-weight-template.hbs --- runtimes/peregrine/src/weights/crowdloan.rs | 38 ++++++++++----------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/runtimes/peregrine/src/weights/crowdloan.rs b/runtimes/peregrine/src/weights/crowdloan.rs index 7859e3b2b..aedc2492f 100644 --- a/runtimes/peregrine/src/weights/crowdloan.rs +++ b/runtimes/peregrine/src/weights/crowdloan.rs @@ -19,13 +19,13 @@ //! Autogenerated weights for crowdloan //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-10-20, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("spiritnet-dev"), DB CACHE: 128 +//! DATE: 2021-10-27, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 // Executed Command: // target/release/kilt-parachain // benchmark -// --chain=spiritnet-dev +// --chain=dev // --steps=50 // --repeat=20 // --pallet=crowdloan @@ -33,7 +33,7 @@ // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --output=./runtimes/spiritnet/src/weights/crowdloan.rs +// --output=./runtimes/peregrine/src/weights/crowdloan.rs // --template=.maintain/runtime-weight-template.hbs @@ -47,34 +47,34 @@ use sp_std::marker::PhantomData; /// Weights for crowdloan using the recommended hardware. pub struct WeightInfo(PhantomData); impl crowdloan::WeightInfo for WeightInfo { - fn set_reserve_accounts() -> Weight { - (18_544_000_u64) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } fn set_registrar_account() -> Weight { - (21_643_000_u64) + (20_725_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_contribution() -> Weight { - (24_614_000_u64) + (23_337_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - fn remove_contribution() -> Weight { - (25_340_000_u64) - .saturating_add(T::DbWeight::get().reads(2_u64)) + fn set_config() -> Weight { + (20_508_000_u64) + .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - fn receive_gratitude() -> Weight { - (21_661_000_u64) + fn set_reserve_accounts() -> Weight { + (24_087_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - fn set_config() -> Weight { - (21_661_000_u64) + fn receive_gratitude() -> Weight { + (170_326_000_u64) + .saturating_add(T::DbWeight::get().reads(8_u64)) + .saturating_add(T::DbWeight::get().writes(6_u64)) + } + fn remove_contribution() -> Weight { + (25_155_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } -} +} \ No newline at end of file From 1403f6f2d7286b9fc33374d56e1109e20f2c5606 Mon Sep 17 00:00:00 2001 From: kiltbot <> Date: Wed, 27 Oct 2021 08:16:19 +0200 Subject: [PATCH 09/47] cargo run --quiet --release -p kilt-parachain --features=runtime-benchmarks -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=crowdloan --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=pallets/crowdloan/src/default_weights.rs --template=.maintain/weight-template.hbs --- pallets/crowdloan/src/default_weights.rs | 64 ++++++++++++------------ 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/pallets/crowdloan/src/default_weights.rs b/pallets/crowdloan/src/default_weights.rs index 019f61560..d49aa15d4 100644 --- a/pallets/crowdloan/src/default_weights.rs +++ b/pallets/crowdloan/src/default_weights.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for crowdloan //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-10-20, STEPS: {{cmd.steps}}\, REPEAT: {{cmd.repeat}}\, LOW RANGE: {{cmd.lowest_range_values}}\, HIGH RANGE: {{cmd.highest_range_values}}\ +//! DATE: 2021-10-27, STEPS: {{cmd.steps}}\, REPEAT: {{cmd.repeat}}\, LOW RANGE: {{cmd.lowest_range_values}}\, HIGH RANGE: {{cmd.highest_range_values}}\ //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 // Executed Command: @@ -47,43 +47,43 @@ use sp_std::marker::PhantomData; /// Weight functions needed for crowdloan. pub trait WeightInfo { fn set_registrar_account() -> Weight; - fn set_reserve_accounts() -> Weight; fn set_contribution() -> Weight; - fn remove_contribution() -> Weight; - fn receive_gratitude() -> Weight; fn set_config() -> Weight; + fn set_reserve_accounts() -> Weight; + fn receive_gratitude() -> Weight; + fn remove_contribution() -> Weight; } /// Weights for crowdloan using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - fn set_reserve_accounts() -> Weight { - (18_544_000_u64) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } fn set_registrar_account() -> Weight { - (18_544_000_u64) + (21_644_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_contribution() -> Weight { - (20_679_000_u64) + (23_815_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - fn remove_contribution() -> Weight { - (21_661_000_u64) - .saturating_add(T::DbWeight::get().reads(2_u64)) + fn set_config() -> Weight { + (21_247_000_u64) + .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - fn receive_gratitude() -> Weight { - (21_661_000_u64) + fn set_reserve_accounts() -> Weight { + (24_336_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - fn set_config() -> Weight { - (21_661_000_u64) + fn receive_gratitude() -> Weight { + (178_299_000_u64) + .saturating_add(T::DbWeight::get().reads(8_u64)) + .saturating_add(T::DbWeight::get().writes(6_u64)) + } + fn remove_contribution() -> Weight { + (25_459_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -91,33 +91,33 @@ impl WeightInfo for SubstrateWeight { // For backwards compatibility and tests impl WeightInfo for () { - fn set_reserve_accounts() -> Weight { - (18_544_000_u64) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } fn set_registrar_account() -> Weight { - (18_544_000_u64) + (21_644_000_u64) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } fn set_contribution() -> Weight { - (20_679_000_u64) + (23_815_000_u64) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - fn remove_contribution() -> Weight { - (21_661_000_u64) - .saturating_add(RocksDbWeight::get().reads(2_u64)) + fn set_config() -> Weight { + (21_247_000_u64) + .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - fn receive_gratitude() -> Weight { - (21_661_000_u64) + fn set_reserve_accounts() -> Weight { + (24_336_000_u64) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - fn set_config() -> Weight { - (21_661_000_u64) + fn receive_gratitude() -> Weight { + (178_299_000_u64) + .saturating_add(RocksDbWeight::get().reads(8_u64)) + .saturating_add(RocksDbWeight::get().writes(6_u64)) + } + fn remove_contribution() -> Weight { + (25_459_000_u64) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } From 09655f47150a469856a01ade0c18b18d2dd192d6 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 08:26:40 +0200 Subject: [PATCH 10/47] doc: document changes --- pallets/crowdloan/src/lib.rs | 22 ++++++++++++++++++++++ pallets/crowdloan/src/storage.rs | 7 +++++++ 2 files changed, 29 insertions(+) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index 705fa3352..2104f3fb8 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -221,6 +221,14 @@ pub mod pallet { Ok(()) } + /// Change the reserve accounts. + /// + /// Only the registrar can change the reserve accounts. + /// + /// # + /// Weight: O(1) + /// - Reads: RegistrarAccount, Reserve + /// - Writes: Reserve #[pallet::weight(WeightInfoOf::::set_reserve_accounts())] pub fn set_reserve_accounts( origin: OriginFor, @@ -253,6 +261,14 @@ pub mod pallet { Ok(()) } + /// Change the configuration of this pallet. + /// + /// Only the registrar can change the configuration. + /// + /// # + /// Weight: O(1) + /// - Reads: RegistrarAccount + /// - Writes: Configuration #[pallet::weight(WeightInfoOf::::set_config())] pub fn set_config(origin: OriginFor, new_config: GratitudeConfig>) -> DispatchResult { let who = ensure_signed(origin)?; @@ -322,6 +338,12 @@ pub mod pallet { /// /// Moves tokens to the given account according to the vote that was /// giving in favour of our parachain. + /// + /// # + /// Weight: O(1) + /// - Reads: Contributions, Reserve, Configuration, [receiver account], + /// [free reserve account], [vested reserve account] + /// - Writes: Contributions #[pallet::weight((WeightInfoOf::::receive_gratitude(), DispatchClass::Normal, Pays::No))] pub fn receive_gratitude(origin: OriginFor, receiver: AccountIdOf) -> DispatchResult { ensure_none(origin)?; diff --git a/pallets/crowdloan/src/storage.rs b/pallets/crowdloan/src/storage.rs index 0cda58823..d3849bb09 100644 --- a/pallets/crowdloan/src/storage.rs +++ b/pallets/crowdloan/src/storage.rs @@ -19,15 +19,22 @@ use codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::Perquintill; +/// A set of reserve accounts #[derive(Clone, Debug, Default, Decode, PartialEq, Encode, TypeInfo)] pub struct ReserveAccounts { + /// The account that is used to do vested transfers. pub vested: A, + /// The account that is used to do free and unlocked transfers. pub free: A, } +/// The configuration of the gratitude. #[derive(Clone, Debug, Default, Decode, Encode, PartialEq, TypeInfo)] pub struct GratitudeConfig { + /// The perquintill of vested tokens that are given. pub vested_share: Perquintill, + /// The start block of the vesting. pub start_block: BlockNumber, + /// The length of the vesting. pub vesting_length: BlockNumber, } From 06a17117773246a10955c90d74958294892c0358 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 08:27:27 +0200 Subject: [PATCH 11/47] use the same test style --- pallets/crowdloan/src/tests.rs | 40 +++++++++++++++++----------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/pallets/crowdloan/src/tests.rs b/pallets/crowdloan/src/tests.rs index 9ca9a9ee3..172d61d73 100644 --- a/pallets/crowdloan/src/tests.rs +++ b/pallets/crowdloan/src/tests.rs @@ -455,16 +455,16 @@ fn test_send_gratitude_contribution_not_found() { fn validate_unsigned_works() { use sp_runtime::traits::ValidateUnsigned; let source = sp_runtime::transaction_validity::TransactionSource::External; - let contributor = || ACCOUNT_00.clone(); + let contributor = ACCOUNT_00; ExtBuilder::default() - .with_contributions(vec![(contributor(), BALANCE_02)]) + .with_contributions(vec![(contributor.clone(), BALANCE_02)]) .build() .execute_with(|| { assert_eq!( crate::Pallet::::validate_unsigned( source, &crate::Call::receive_gratitude { - receiver: contributor() + receiver: contributor.clone() } ), Ok(ValidTransaction { @@ -533,39 +533,39 @@ fn test_set_configuration() { #[test] fn test_set_reserve() { - let registrar = || ACCOUNT_00.clone(); - let contributor = || ACCOUNT_01.clone(); - let free_reserve_old = || ACCOUNT_01.clone(); - let vested_reserve_old = || ACCOUNT_02.clone(); - let free_reserve_new = || ACCOUNT_03.clone(); - let vested_reserve_new = || ACCOUNT_04.clone(); + let registrar = ACCOUNT_00; + let contributor = ACCOUNT_01; + let free_reserve_old = ACCOUNT_01; + let vested_reserve_old = ACCOUNT_02; + let free_reserve_new = ACCOUNT_03; + let vested_reserve_new = ACCOUNT_04; ExtBuilder::default() .with_reserve(ReserveAccounts { - vested: vested_reserve_old(), - free: free_reserve_old(), + vested: vested_reserve_old.clone(), + free: free_reserve_old.clone(), }) - .with_registrar_account(registrar()) + .with_registrar_account(registrar.clone()) .build() .execute_with(|| { assert_ok!(Crowdloan::set_reserve_accounts( - Origin::signed(registrar()), - vested_reserve_new(), - free_reserve_new() + Origin::signed(registrar.clone()), + vested_reserve_new.clone(), + free_reserve_new.clone() )); assert_eq!( crate::Reserve::::get(), ReserveAccounts { - vested: vested_reserve_new(), - free: free_reserve_new(), + vested: vested_reserve_new, + free: free_reserve_new, } ); assert_noop!( Crowdloan::set_reserve_accounts( - Origin::signed(contributor()), - vested_reserve_old(), - free_reserve_old() + Origin::signed(contributor), + vested_reserve_old, + free_reserve_old ), BadOrigin ); From c3e5b8bf3b19972fc4b43f2aa4fbd3fc0e9f0378 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 08:30:02 +0200 Subject: [PATCH 12/47] minor fixes --- pallets/crowdloan/src/lib.rs | 2 +- pallets/crowdloan/src/tests.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index 2104f3fb8..8ff0d652c 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -343,7 +343,7 @@ pub mod pallet { /// Weight: O(1) /// - Reads: Contributions, Reserve, Configuration, [receiver account], /// [free reserve account], [vested reserve account] - /// - Writes: Contributions + /// - Writes: Contributions, [free reserve account], [vested reserve account], [receiver account] #[pallet::weight((WeightInfoOf::::receive_gratitude(), DispatchClass::Normal, Pays::No))] pub fn receive_gratitude(origin: OriginFor, receiver: AccountIdOf) -> DispatchResult { ensure_none(origin)?; diff --git a/pallets/crowdloan/src/tests.rs b/pallets/crowdloan/src/tests.rs index 172d61d73..5ea237068 100644 --- a/pallets/crowdloan/src/tests.rs +++ b/pallets/crowdloan/src/tests.rs @@ -470,7 +470,7 @@ fn validate_unsigned_works() { Ok(ValidTransaction { priority: 100, requires: vec![], - provides: vec![("gratitude", contributor()).encode()], + provides: vec![("gratitude", contributor.clone()).encode()], longevity: TransactionLongevity::max_value(), propagate: true, }) From 3941b2a65829b31a4e4712c16d40a6b30d984d7e Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 08:39:37 +0200 Subject: [PATCH 13/47] clippy --- pallets/crowdloan/src/benchmarking.rs | 2 +- pallets/crowdloan/src/tests.rs | 34 +++++++++++++-------------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/pallets/crowdloan/src/benchmarking.rs b/pallets/crowdloan/src/benchmarking.rs index 09f2b57a5..fdd60d945 100644 --- a/pallets/crowdloan/src/benchmarking.rs +++ b/pallets/crowdloan/src/benchmarking.rs @@ -109,7 +109,7 @@ benchmarks! { + CurrencyOf::::minimum_balance() + CurrencyOf::::minimum_balance(); - RegistrarAccount::::set(registrar.clone()); + RegistrarAccount::::set(registrar); Reserve::::set(ReserveAccounts { vested: reserve_vested.clone(), free: reserve_free.clone(), diff --git a/pallets/crowdloan/src/tests.rs b/pallets/crowdloan/src/tests.rs index 5ea237068..382b8ebbe 100644 --- a/pallets/crowdloan/src/tests.rs +++ b/pallets/crowdloan/src/tests.rs @@ -267,7 +267,7 @@ fn test_send_gratitude_success() { vested: vested_reserve.clone(), free: free_reserve.clone(), }) - .with_registrar_account(registrar.clone()) + .with_registrar_account(registrar) .with_balances(vec![ (free_reserve.clone(), BALANCE_01), (vested_reserve.clone(), BALANCE_01), @@ -306,10 +306,10 @@ fn test_send_gratitude_empty_free_reserve() { ExtBuilder::default() .with_reserve(ReserveAccounts { vested: vested_reserve.clone(), - free: free_reserve.clone(), + free: free_reserve, }) - .with_registrar_account(registrar.clone()) - .with_balances(vec![(vested_reserve.clone(), BALANCE_02)]) + .with_registrar_account(registrar) + .with_balances(vec![(vested_reserve, BALANCE_02)]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) .with_configuration(GratitudeConfig { vested_share: Perquintill::from_percent(50), @@ -334,11 +334,11 @@ fn test_send_gratitude_empty_vest_reserve() { ExtBuilder::default() .with_reserve(ReserveAccounts { - vested: vested_reserve.clone(), + vested: vested_reserve, free: free_reserve.clone(), }) - .with_registrar_account(registrar.clone()) - .with_balances(vec![(free_reserve.clone(), BALANCE_02)]) + .with_registrar_account(registrar) + .with_balances(vec![(free_reserve, BALANCE_02)]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) .with_configuration(GratitudeConfig { vested_share: Perquintill::from_percent(50), @@ -363,10 +363,10 @@ fn test_send_gratitude_same_account_success() { ExtBuilder::default() .with_reserve(ReserveAccounts { - vested: vested_reserve.clone(), + vested: vested_reserve, free: free_reserve.clone(), }) - .with_registrar_account(registrar.clone()) + .with_registrar_account(registrar) .with_balances(vec![(free_reserve.clone(), BALANCE_02)]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) .with_configuration(GratitudeConfig { @@ -400,11 +400,11 @@ fn test_send_gratitude_same_account_out_of_funds() { ExtBuilder::default() .with_reserve(ReserveAccounts { - vested: vested_reserve.clone(), + vested: vested_reserve, free: free_reserve.clone(), }) - .with_registrar_account(registrar.clone()) - .with_balances(vec![(free_reserve.clone(), BALANCE_01)]) + .with_registrar_account(registrar) + .with_balances(vec![(free_reserve, BALANCE_01)]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) .with_configuration(GratitudeConfig { vested_share: Perquintill::from_percent(50), @@ -429,11 +429,11 @@ fn test_send_gratitude_contribution_not_found() { ExtBuilder::default() .with_reserve(ReserveAccounts { - vested: vested_reserve.clone(), + vested: vested_reserve, free: free_reserve.clone(), }) - .with_registrar_account(registrar.clone()) - .with_balances(vec![(free_reserve.clone(), BALANCE_01)]) + .with_registrar_account(registrar) + .with_balances(vec![(free_reserve, BALANCE_01)]) .with_configuration(GratitudeConfig { vested_share: Perquintill::from_percent(50), start_block: 1, @@ -515,8 +515,8 @@ fn test_set_configuration() { ExtBuilder::default() .with_reserve(ReserveAccounts { - vested: vested_reserve.clone(), - free: free_reserve.clone(), + vested: vested_reserve, + free: free_reserve, }) .with_registrar_account(registrar.clone()) .build() From a90a2cfa717f1a57342fc0558f2d6643d2115f33 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 08:43:21 +0200 Subject: [PATCH 14/47] clean dependencies --- pallets/crowdloan/Cargo.toml | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/pallets/crowdloan/Cargo.toml b/pallets/crowdloan/Cargo.toml index 8508e8d64..ab1ae66e3 100644 --- a/pallets/crowdloan/Cargo.toml +++ b/pallets/crowdloan/Cargo.toml @@ -33,20 +33,11 @@ frame-system = {branch = "polkadot-v0.9.11", default-features = false, git = "ht sp-runtime = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} sp-std = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate"} -pallet-balances = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate", optional = true} -pallet-vesting = {branch = "polkadot-v0.9.11", default-features = false, git = "https://github.com/paritytech/substrate", optional = true} -kilt-primitives = {default-features = false, path = "../../primitives", optional = true} - [features] default = ["std"] runtime-benchmarks = [ "frame-benchmarking", - "pallet-balances", - "pallet-balances/frame-benchmarking", - "pallet-vesting", - "pallet-vesting/frame-benchmarking", - "kilt-primitives", ] std = [ @@ -57,9 +48,6 @@ std = [ "scale-info/std", "sp-runtime/std", "sp-std/std", - "kilt-primitives/std", - "pallet-balances/std", - "pallet-vesting/std", ] try-runtime = [ From 10d57dbf5f68bcf077c644a873bf3a7c72e52ec5 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 08:56:22 +0200 Subject: [PATCH 15/47] =?UTF-8?q?=F0=9F=A7=B9=F0=9F=90=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pallets/crowdloan/src/lib.rs | 3 ++- pallets/crowdloan/src/tests.rs | 6 +----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index 8ff0d652c..7ba11e814 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -343,7 +343,8 @@ pub mod pallet { /// Weight: O(1) /// - Reads: Contributions, Reserve, Configuration, [receiver account], /// [free reserve account], [vested reserve account] - /// - Writes: Contributions, [free reserve account], [vested reserve account], [receiver account] + /// - Writes: Contributions, [free reserve account], [vested reserve + /// account], [receiver account] #[pallet::weight((WeightInfoOf::::receive_gratitude(), DispatchClass::Normal, Pays::No))] pub fn receive_gratitude(origin: OriginFor, receiver: AccountIdOf) -> DispatchResult { ensure_none(origin)?; diff --git a/pallets/crowdloan/src/tests.rs b/pallets/crowdloan/src/tests.rs index 382b8ebbe..0cb4d4ae7 100644 --- a/pallets/crowdloan/src/tests.rs +++ b/pallets/crowdloan/src/tests.rs @@ -562,11 +562,7 @@ fn test_set_reserve() { ); assert_noop!( - Crowdloan::set_reserve_accounts( - Origin::signed(contributor), - vested_reserve_old, - free_reserve_old - ), + Crowdloan::set_reserve_accounts(Origin::signed(contributor), vested_reserve_old, free_reserve_old), BadOrigin ); }); From 883e59dad6a57f58a34e891dbe1e3da136147e2e Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 09:06:00 +0200 Subject: [PATCH 16/47] replace perquintill with permill and add test --- pallets/crowdloan/src/benchmarking.rs | 6 +++--- pallets/crowdloan/src/storage.rs | 4 ++-- pallets/crowdloan/src/tests.rs | 17 +++++++++-------- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/pallets/crowdloan/src/benchmarking.rs b/pallets/crowdloan/src/benchmarking.rs index fdd60d945..376143dfd 100644 --- a/pallets/crowdloan/src/benchmarking.rs +++ b/pallets/crowdloan/src/benchmarking.rs @@ -24,7 +24,7 @@ use frame_support::{dispatch::UnfilteredDispatchable, traits::Currency, unsigned use frame_system::RawOrigin; use sp_runtime::{ traits::{One, StaticLookup}, - Perquintill, + Permill, }; const SEED_1: u32 = 1; @@ -65,7 +65,7 @@ benchmarks! { RegistrarAccount::::set(registrar.clone()); let config = GratitudeConfig:: { - vested_share: Perquintill::from_percent(42), + vested_share: Permill::from_percent(42), start_block: 1.into(), vesting_length: 10.into(), }; @@ -116,7 +116,7 @@ benchmarks! { }); Contributions::::insert(&contributor, contribution); Configuration::::set(GratitudeConfig { - vested_share: Perquintill::from_percent(50), + vested_share: Permill::from_percent(50), start_block: 1.into(), vesting_length: 10.into(), }); diff --git a/pallets/crowdloan/src/storage.rs b/pallets/crowdloan/src/storage.rs index d3849bb09..25c94c1f6 100644 --- a/pallets/crowdloan/src/storage.rs +++ b/pallets/crowdloan/src/storage.rs @@ -17,7 +17,7 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org use codec::{Decode, Encode}; use scale_info::TypeInfo; -use sp_runtime::Perquintill; +use sp_runtime::Permill; /// A set of reserve accounts #[derive(Clone, Debug, Default, Decode, PartialEq, Encode, TypeInfo)] @@ -32,7 +32,7 @@ pub struct ReserveAccounts { #[derive(Clone, Debug, Default, Decode, Encode, PartialEq, TypeInfo)] pub struct GratitudeConfig { /// The perquintill of vested tokens that are given. - pub vested_share: Perquintill, + pub vested_share: Permill, /// The start block of the vesting. pub start_block: BlockNumber, /// The length of the vesting. diff --git a/pallets/crowdloan/src/tests.rs b/pallets/crowdloan/src/tests.rs index 0cb4d4ae7..55add9c54 100644 --- a/pallets/crowdloan/src/tests.rs +++ b/pallets/crowdloan/src/tests.rs @@ -23,7 +23,7 @@ use frame_support::{ }; use sp_runtime::{ traits::{BadOrigin, Zero}, - Perquintill, + Permill, }; use crate::{mock::*, GratitudeConfig, ReserveAccounts}; @@ -274,7 +274,7 @@ fn test_send_gratitude_success() { ]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) .with_configuration(GratitudeConfig { - vested_share: Perquintill::from_percent(50), + vested_share: Permill::from_percent(50), start_block: 1, vesting_length: 10, }) @@ -287,6 +287,7 @@ fn test_send_gratitude_success() { ); assert!(pallet_balances::Pallet::::free_balance(free_reserve.clone()).is_zero()); assert!(pallet_balances::Pallet::::free_balance(vested_reserve.clone()).is_zero()); + assert_eq!(pallet_balances::Pallet::::free_balance(contributor.clone()), BALANCE_02); assert!(crate::Contributions::::get(&contributor).is_none()); assert_noop!( @@ -312,7 +313,7 @@ fn test_send_gratitude_empty_free_reserve() { .with_balances(vec![(vested_reserve, BALANCE_02)]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) .with_configuration(GratitudeConfig { - vested_share: Perquintill::from_percent(50), + vested_share: Permill::from_percent(50), start_block: 1, vesting_length: 10, }) @@ -341,7 +342,7 @@ fn test_send_gratitude_empty_vest_reserve() { .with_balances(vec![(free_reserve, BALANCE_02)]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) .with_configuration(GratitudeConfig { - vested_share: Perquintill::from_percent(50), + vested_share: Permill::from_percent(50), start_block: 1, vesting_length: 10, }) @@ -370,7 +371,7 @@ fn test_send_gratitude_same_account_success() { .with_balances(vec![(free_reserve.clone(), BALANCE_02)]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) .with_configuration(GratitudeConfig { - vested_share: Perquintill::from_percent(50), + vested_share: Permill::from_percent(50), start_block: 1, vesting_length: 10, }) @@ -407,7 +408,7 @@ fn test_send_gratitude_same_account_out_of_funds() { .with_balances(vec![(free_reserve, BALANCE_01)]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) .with_configuration(GratitudeConfig { - vested_share: Perquintill::from_percent(50), + vested_share: Permill::from_percent(50), start_block: 1, vesting_length: 10, }) @@ -435,7 +436,7 @@ fn test_send_gratitude_contribution_not_found() { .with_registrar_account(registrar) .with_balances(vec![(free_reserve, BALANCE_01)]) .with_configuration(GratitudeConfig { - vested_share: Perquintill::from_percent(50), + vested_share: Permill::from_percent(50), start_block: 1, vesting_length: 10, }) @@ -508,7 +509,7 @@ fn test_set_configuration() { let free_reserve = ACCOUNT_02; let vested_reserve = ACCOUNT_02; let config = GratitudeConfig { - vested_share: Perquintill::from_percent(50), + vested_share: Permill::from_percent(50), start_block: 1, vesting_length: 10, }; From 4cf15096e0bb77535859b9ffbcb3d96f17eb4058 Mon Sep 17 00:00:00 2001 From: kiltbot <> Date: Wed, 27 Oct 2021 09:11:20 +0200 Subject: [PATCH 17/47] cargo run --quiet --release -p kilt-parachain --features=runtime-benchmarks -- benchmark --chain=spiritnet-dev --steps=50 --repeat=20 --pallet=crowdloan --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./runtimes/spiritnet/src/weights/crowdloan.rs --template=.maintain/runtime-weight-template.hbs --- runtimes/spiritnet/src/weights/crowdloan.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/runtimes/spiritnet/src/weights/crowdloan.rs b/runtimes/spiritnet/src/weights/crowdloan.rs index ddf142620..1f3ffa4fb 100644 --- a/runtimes/spiritnet/src/weights/crowdloan.rs +++ b/runtimes/spiritnet/src/weights/crowdloan.rs @@ -48,32 +48,32 @@ use sp_std::marker::PhantomData; pub struct WeightInfo(PhantomData); impl crowdloan::WeightInfo for WeightInfo { fn set_registrar_account() -> Weight { - (20_486_000_u64) + (19_796_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_contribution() -> Weight { - (23_339_000_u64) + (22_134_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_config() -> Weight { - (20_299_000_u64) + (19_503_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_reserve_accounts() -> Weight { - (24_210_000_u64) + (22_988_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn receive_gratitude() -> Weight { - (164_039_000_u64) + (162_343_000_u64) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } fn remove_contribution() -> Weight { - (24_835_000_u64) + (24_258_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } From 979b8b1e0edd23dc3f86b1c0ef3004940945e5a3 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 10:01:23 +0200 Subject: [PATCH 18/47] =?UTF-8?q?=F0=9F=A7=B9=F0=9F=90=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pallets/crowdloan/src/tests.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pallets/crowdloan/src/tests.rs b/pallets/crowdloan/src/tests.rs index 55add9c54..99d4d177a 100644 --- a/pallets/crowdloan/src/tests.rs +++ b/pallets/crowdloan/src/tests.rs @@ -287,7 +287,10 @@ fn test_send_gratitude_success() { ); assert!(pallet_balances::Pallet::::free_balance(free_reserve.clone()).is_zero()); assert!(pallet_balances::Pallet::::free_balance(vested_reserve.clone()).is_zero()); - assert_eq!(pallet_balances::Pallet::::free_balance(contributor.clone()), BALANCE_02); + assert_eq!( + pallet_balances::Pallet::::free_balance(contributor.clone()), + BALANCE_02 + ); assert!(crate::Contributions::::get(&contributor).is_none()); assert_noop!( From 5e544df32b57f1a700aca6ff8a8edf0f76fcd419 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 09:40:06 +0200 Subject: [PATCH 19/47] fix dependencies --- Cargo.lock | 1 - primitives/Cargo.toml | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6dd6d8a47..c288ec678 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3594,7 +3594,6 @@ dependencies = [ "frame-system", "pallet-transaction-payment", "parity-scale-codec", - "polkadot-runtime-common", "scale-info", "serde", "sp-consensus-aura", diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index 3d9f6f7fb..3c8de29e2 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -7,16 +7,15 @@ version = "0.1.0" [dependencies] codec = {package = "parity-scale-codec", version = "2.3.1", default-features = false, features = ["derive"]} serde = {version = "1.0.124", optional = true, features = ["derive"]} +scale-info = { version = "1.0", default-features = false, features = ["derive"] } frame-support = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.11"} frame-system = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.11"} pallet-transaction-payment = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.11"} -scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-consensus-aura = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.11"} sp-core = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.11"} sp-runtime = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.11"} sp-std = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.11"} -polkadot-runtime-common = {git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.11"} [features] default = ["std"] From ad96003e2324d490038fef05c8c28a094739692c Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 11:10:28 +0200 Subject: [PATCH 20/47] check in validate_unsigned for successful TX --- pallets/crowdloan/src/lib.rs | 82 ++++++++++++++++++++++++------------ 1 file changed, 55 insertions(+), 27 deletions(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index 7ba11e814..41ebf356e 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -349,14 +349,55 @@ pub mod pallet { pub fn receive_gratitude(origin: OriginFor, receiver: AccountIdOf) -> DispatchResult { ensure_none(origin)?; - let amount = Contributions::::get(&receiver).ok_or(Error::::ContributorNotPresent)?; + let gratitude = Self::split_gratitude_for(&receiver)?; + Self::ensure_can_send_gratitude(&gratitude)?; + + // *** No failure beyond this call! The contributor was removed. *** + Contributions::::remove(&receiver); + + let SplitGratitude { vested, free } = gratitude; let config = Configuration::::get(); let reserve = Reserve::::get(); + // Transfer the free amount. Should not fail since checked we + // ensure_can_withdraw. + CurrencyOf::::transfer(&reserve.free, &receiver, free, ExistenceRequirement::AllowDeath)?; + + // Transfer the vested amount and set the vesting schedule. Should not fail + // since checked we ensure_can_withdraw. + CurrencyOf::::transfer(&reserve.vested, &receiver, vested, ExistenceRequirement::AllowDeath)?; + let per_block = vested + .checked_div(&BalanceOf::::from(config.vesting_length)) + .unwrap_or(vested); + // vesting should not fail since we have transferred enough free balance. + VestingOf::::add_vesting_schedule(&receiver, vested, per_block, config.start_block)?; + + Self::deposit_event(Event::GratitudeReceived(receiver)); + + Ok(()) + } + } + + struct SplitGratitude { + vested: Balance, + free: Balance, + } + + impl Pallet { + fn split_gratitude_for(receiver: &AccountIdOf) -> Result>, DispatchError> { + let amount = Contributions::::get(receiver).ok_or(Error::::ContributorNotPresent)?; + let config = Configuration::::get(); + // A two without any trait bounds (no From). let vested = config.vested_share.mul_floor(amount); let free = amount.saturating_sub(vested); + Ok(SplitGratitude { vested, free }) + } + + fn ensure_can_send_gratitude(SplitGratitude { vested, free }: &SplitGratitude>) -> DispatchResult { + let reserve = Reserve::::get(); + let new_free_acc_balance = CurrencyOf::::free_balance(&reserve.free) .checked_sub(&free) .ok_or(Error::::InsufficientBalance)?; @@ -370,32 +411,19 @@ pub mod pallet { .checked_sub(&free) .ok_or(Error::::InsufficientBalance)?; } - CurrencyOf::::ensure_can_withdraw(&reserve.free, free, WithdrawReasons::TRANSFER, new_free_acc_balance)?; + CurrencyOf::::ensure_can_withdraw( + &reserve.free, + *free, + WithdrawReasons::TRANSFER, + new_free_acc_balance, + )?; CurrencyOf::::ensure_can_withdraw( &reserve.vested, - vested, + *vested, WithdrawReasons::TRANSFER, new_vested_acc_balance, )?; - Contributions::::remove(&receiver); - // *** No failure beyond this point! The contributor was removed. *** - - // Transfer the free amount. Should not fail since checked we - // ensure_can_withdraw. - CurrencyOf::::transfer(&reserve.free, &receiver, free, ExistenceRequirement::AllowDeath)?; - - // Transfer the vested amount and set the vesting schedule. Should not fail - // since checked we ensure_can_withdraw. - CurrencyOf::::transfer(&reserve.vested, &receiver, vested, ExistenceRequirement::AllowDeath)?; - let per_block = vested - .checked_div(&BalanceOf::::from(config.vesting_length)) - .unwrap_or(vested); - // vesting should not fail since we have transferred enough free balance. - VestingOf::::add_vesting_schedule(&receiver, vested, per_block, config.start_block)?; - - Self::deposit_event(Event::GratitudeReceived(receiver)); - Ok(()) } } @@ -407,7 +435,7 @@ pub mod pallet { fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { const PRIORITY: u64 = 100; - let claiming_account = match call { + let receiver = match call { // // The weight of this logic must be included in the `receive_gratitude` call. // @@ -415,15 +443,15 @@ pub mod pallet { _ => return Err(InvalidTransaction::Call.into()), }; - ensure!( - Contributions::::contains_key(claiming_account), - InvalidTransaction::BadProof - ); + ensure!(Contributions::::contains_key(receiver), InvalidTransaction::BadProof); + + let gratitude = Self::split_gratitude_for(receiver).map_err(|_| InvalidTransaction::Call)?; + Self::ensure_can_send_gratitude(&gratitude).map_err(|_| InvalidTransaction::Call)?; Ok(ValidTransaction { priority: PRIORITY, requires: vec![], - provides: vec![("gratitude", claiming_account).encode()], + provides: vec![("gratitude", receiver).encode()], longevity: TransactionLongevity::max_value(), propagate: true, }) From ea0dec36de71ccfe1c539fa42ea1074a68d00485 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 11:10:36 +0200 Subject: [PATCH 21/47] add validate_unsigned to runtimes --- runtimes/peregrine/src/lib.rs | 2 +- runtimes/spiritnet/src/lib.rs | 2 +- runtimes/standalone/src/lib.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index 3bceea112..35e194808 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -732,7 +732,7 @@ construct_runtime! { Attestation: attestation::{Pallet, Call, Storage, Event} = 62, Delegation: delegation::{Pallet, Call, Storage, Event} = 63, Did: did::{Pallet, Call, Storage, Event, Origin} = 64, - CrowdloanContributors: crowdloan::{Pallet, Call, Storage, Event, Config} = 65, + CrowdloanContributors: crowdloan::{Pallet, Call, Storage, Event, Config, ValidateUnsigned} = 65, // Parachains pallets. Start indices at 80 to leave room. ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event, Config} = 80, diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index 8246637bb..61411c641 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -749,7 +749,7 @@ construct_runtime! { Delegation: delegation::{Pallet, Call, Storage, Event} = 63, Did: did::{Pallet, Call, Storage, Event, Origin} = 64, - CrowdloanContributors: crowdloan::{Pallet, Call, Storage, Event, Config} = 65, + CrowdloanContributors: crowdloan::{Pallet, Call, Storage, Event, Config, ValidateUnsigned} = 65, // Parachains pallets. Start indices at 80 to leave room. ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event, Config} = 80, diff --git a/runtimes/standalone/src/lib.rs b/runtimes/standalone/src/lib.rs index 91f349e61..a17f3b17a 100644 --- a/runtimes/standalone/src/lib.rs +++ b/runtimes/standalone/src/lib.rs @@ -539,7 +539,7 @@ construct_runtime!( Vesting: pallet_vesting::{Pallet, Call, Storage, Event, Config} = 33, KiltLaunch: kilt_launch::{Pallet, Call, Storage, Event, Config} = 34, Utility: pallet_utility::{Pallet, Call, Storage, Event} = 35, - CrowdloanContributors: crowdloan::{Pallet, Call, Storage, Event, Config} = 36, + CrowdloanContributors: crowdloan::{Pallet, Call, Storage, Event, Config, ValidateUnsigned} = 36, } ); From 572b9e6e034ff497253c476f17733291c61b9324 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 11:12:01 +0200 Subject: [PATCH 22/47] reduce diff between runtimes --- runtimes/peregrine/src/lib.rs | 2 ++ runtimes/spiritnet/src/lib.rs | 30 +++++++++++++++--------------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index 35e194808..6176d50e3 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -728,10 +728,12 @@ construct_runtime! { // KILT Pallets. Start indices 60 to leave room KiltLaunch: kilt_launch::{Pallet, Call, Storage, Event, Config} = 60, + Ctype: ctype::{Pallet, Call, Storage, Event} = 61, Attestation: attestation::{Pallet, Call, Storage, Event} = 62, Delegation: delegation::{Pallet, Call, Storage, Event} = 63, Did: did::{Pallet, Call, Storage, Event, Origin} = 64, + CrowdloanContributors: crowdloan::{Pallet, Call, Storage, Event, Config, ValidateUnsigned} = 65, // Parachains pallets. Start indices at 80 to leave room. diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index 61411c641..a738e2800 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -629,6 +629,15 @@ impl did::Config for Runtime { type WeightInfo = weights::did::WeightInfo; } +impl crowdloan::Config for Runtime { + type Currency = Balances; + type Vesting = Vesting; + type Balance = Balance; + type EnsureRegistrarOrigin = MoreThanHalfCouncil; + type Event = Event; + type WeightInfo = weights::crowdloan::WeightInfo; +} + parameter_types! { /// Minimum round length is 1 hour pub const MinBlocksPerRound: BlockNumber = MIN_BLOCKS_PER_ROUND; @@ -691,15 +700,6 @@ impl pallet_utility::Config for Runtime { impl pallet_randomness_collective_flip::Config for Runtime {} -impl crowdloan::Config for Runtime { - type Currency = Balances; - type Vesting = Vesting; - type Balance = Balance; - type EnsureRegistrarOrigin = MoreThanHalfCouncil; - type Event = Event; - type WeightInfo = weights::crowdloan::WeightInfo; -} - construct_runtime! { pub enum Runtime where Block = Block, @@ -760,12 +760,12 @@ construct_runtime! { impl did::DeriveDidCallAuthorizationVerificationKeyRelationship for Call { fn derive_verification_key_relationship(&self) -> Option { match self { - Call::Attestation(_) => Some(did::DidVerificationKeyRelationship::AssertionMethod), - Call::Ctype(_) => Some(did::DidVerificationKeyRelationship::AssertionMethod), - Call::Delegation(_) => Some(did::DidVerificationKeyRelationship::CapabilityDelegation), + Call::Attestation { .. } => Some(did::DidVerificationKeyRelationship::AssertionMethod), + Call::Ctype { .. } => Some(did::DidVerificationKeyRelationship::AssertionMethod), + Call::Delegation { .. } => Some(did::DidVerificationKeyRelationship::CapabilityDelegation), // DID creation is not allowed through the DID proxy. Call::Did(did::Call::create { .. }) => None, - Call::Did(_) => Some(did::DidVerificationKeyRelationship::Authentication), + Call::Did { .. } => Some(did::DidVerificationKeyRelationship::Authentication), //TODO: add a batch call case that returns the right key type if all calls in the batch require the same // key type as well, otherwise it returns None and fails. #[cfg(not(feature = "runtime-benchmarks"))] @@ -935,6 +935,7 @@ impl_runtime_apis! { // Substrate list_benchmark!(list, extra, frame_system, SystemBench::); + list_benchmark!(list, extra, pallet_session, SessionBench::); list_benchmark!(list, extra, pallet_balances, Balances); list_benchmark!(list, extra, pallet_collective, Council); list_benchmark!(list, extra, pallet_democracy, Democracy); @@ -945,12 +946,11 @@ impl_runtime_apis! { list_benchmark!(list, extra, pallet_treasury, Treasury); list_benchmark!(list, extra, pallet_utility, Utility); list_benchmark!(list, extra, pallet_vesting, Vesting); - list_benchmark!(list, extra, pallet_session, SessionBench::); // KILT list_benchmark!(list, extra, attestation, Attestation); - list_benchmark!(list, extra, ctype, Ctype); list_benchmark!(list, extra, crowdloan, CrowdloanContributors); + list_benchmark!(list, extra, ctype, Ctype); list_benchmark!(list, extra, delegation, Delegation); list_benchmark!(list, extra, did, Did); list_benchmark!(list, extra, kilt_launch, KiltLaunch); From ab7f9ed341edd0bcc4a818259b4e65cbb1e367e9 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 13:13:50 +0200 Subject: [PATCH 23/47] custom errors --- pallets/crowdloan/src/lib.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index 41ebf356e..aad66cdd6 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -428,6 +428,15 @@ pub mod pallet { } } + /// Custom validity errors while validating transactions. + #[repr(u8)] + pub enum ValidityError { + /// The Ethereum signature is invalid. + NoContributor = 0, + /// The signer has no claim. + CannotSendGratitude = 1, + } + #[pallet::validate_unsigned] impl ValidateUnsigned for Pallet { type Call = Call; @@ -443,10 +452,10 @@ pub mod pallet { _ => return Err(InvalidTransaction::Call.into()), }; - ensure!(Contributions::::contains_key(receiver), InvalidTransaction::BadProof); - - let gratitude = Self::split_gratitude_for(receiver).map_err(|_| InvalidTransaction::Call)?; - Self::ensure_can_send_gratitude(&gratitude).map_err(|_| InvalidTransaction::Call)?; + let gratitude = Self::split_gratitude_for(receiver) + .map_err(|_| InvalidTransaction::Custom(ValidityError::NoContributor as u8))?; + Self::ensure_can_send_gratitude(&gratitude) + .map_err(|_| InvalidTransaction::Custom(ValidityError::CannotSendGratitude as u8))?; Ok(ValidTransaction { priority: PRIORITY, From ebcba63c49e2919142352ec3f42f01302343f462 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 13:14:06 +0200 Subject: [PATCH 24/47] remove redundant test --- pallets/crowdloan/src/mock.rs | 2 +- pallets/crowdloan/src/tests.rs | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/pallets/crowdloan/src/mock.rs b/pallets/crowdloan/src/mock.rs index 4b1eba834..d9c5359b9 100644 --- a/pallets/crowdloan/src/mock.rs +++ b/pallets/crowdloan/src/mock.rs @@ -40,7 +40,7 @@ frame_support::construct_runtime!( System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Event}, Vesting: pallet_vesting::{Pallet, Call, Storage, Event}, - Crowdloan: pallet_crowdloan::{Pallet, Call, Config, Storage, Event} + Crowdloan: pallet_crowdloan::{Pallet, Call, Config, Storage, Event, ValidateUnsigned} } ); diff --git a/pallets/crowdloan/src/tests.rs b/pallets/crowdloan/src/tests.rs index 99d4d177a..48d406756 100644 --- a/pallets/crowdloan/src/tests.rs +++ b/pallets/crowdloan/src/tests.rs @@ -287,10 +287,6 @@ fn test_send_gratitude_success() { ); assert!(pallet_balances::Pallet::::free_balance(free_reserve.clone()).is_zero()); assert!(pallet_balances::Pallet::::free_balance(vested_reserve.clone()).is_zero()); - assert_eq!( - pallet_balances::Pallet::::free_balance(contributor.clone()), - BALANCE_02 - ); assert!(crate::Contributions::::get(&contributor).is_none()); assert_noop!( From 1fc4b3cc18dcb13d3d5a18198cba7e79eb4a0b5f Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 13:14:53 +0200 Subject: [PATCH 25/47] clipy --- pallets/crowdloan/src/lib.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index aad66cdd6..cc8f892e9 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -399,16 +399,16 @@ pub mod pallet { let reserve = Reserve::::get(); let new_free_acc_balance = CurrencyOf::::free_balance(&reserve.free) - .checked_sub(&free) + .checked_sub(free) .ok_or(Error::::InsufficientBalance)?; let mut new_vested_acc_balance = CurrencyOf::::free_balance(&reserve.vested) - .checked_sub(&vested) + .checked_sub(vested) .ok_or(Error::::InsufficientBalance)?; if reserve.free == reserve.vested { // if free and vested are the same we need to make sure that we can withdraw // both from the same account new_vested_acc_balance = new_vested_acc_balance - .checked_sub(&free) + .checked_sub(free) .ok_or(Error::::InsufficientBalance)?; } CurrencyOf::::ensure_can_withdraw( From d246ab60c8b1829186684870be0684c61d8caca2 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 13:23:49 +0200 Subject: [PATCH 26/47] document error --- pallets/crowdloan/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index cc8f892e9..3d89d39bb 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -431,9 +431,9 @@ pub mod pallet { /// Custom validity errors while validating transactions. #[repr(u8)] pub enum ValidityError { - /// The Ethereum signature is invalid. + /// The account is not registered and therefore not allowed to make this call. NoContributor = 0, - /// The signer has no claim. + /// An internal error prevents the call from being submitted. CannotSendGratitude = 1, } From 0c07692ba3a86b2f47454e1543245066ff444f00 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 13:49:52 +0200 Subject: [PATCH 27/47] fixes --- pallets/crowdloan/src/benchmarking.rs | 8 +++---- pallets/crowdloan/src/storage.rs | 2 +- pallets/crowdloan/src/tests.rs | 34 +++++++++++++++++++++++++-- 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/pallets/crowdloan/src/benchmarking.rs b/pallets/crowdloan/src/benchmarking.rs index 376143dfd..5d875571f 100644 --- a/pallets/crowdloan/src/benchmarking.rs +++ b/pallets/crowdloan/src/benchmarking.rs @@ -82,7 +82,6 @@ benchmarks! { let reserve_free: AccountIdOf = account("reserve_free", 0, SEED_1); let reserve_vested: AccountIdOf = account("reserve_vested", 0, SEED_1); RegistrarAccount::::set(registrar.clone()); - }: _( RawOrigin::Signed(registrar), T::Lookup::unlookup(reserve_vested.clone()), @@ -90,7 +89,7 @@ benchmarks! { ) verify { assert_eq!( - crate::Reserve::::get(), + Reserve::::get(), ReserveAccounts { vested: reserve_vested, free: reserve_free, @@ -130,11 +129,12 @@ benchmarks! { }: { let call = as Decode>::decode(&mut &*call_enc) .expect("call is encoded above, encoding must be correct"); - crate::Pallet::::validate_unsigned(source, &call).map_err(|e| -> &'static str { e.into() })?; + Pallet::::validate_unsigned(source, &call).map_err(|e| -> &'static str { e.into() })?; call.dispatch_bypass_filter(RawOrigin::None.into())?; } verify { - assert!(crate::Contributions::::get(contributor).is_none()); + assert!(Contributions::::get(contributor.clone()).is_none()); + assert_eq!(CurrencyOf::::free_balance(&contributor), contribution); } remove_contribution { diff --git a/pallets/crowdloan/src/storage.rs b/pallets/crowdloan/src/storage.rs index 25c94c1f6..da75d6edf 100644 --- a/pallets/crowdloan/src/storage.rs +++ b/pallets/crowdloan/src/storage.rs @@ -31,7 +31,7 @@ pub struct ReserveAccounts { /// The configuration of the gratitude. #[derive(Clone, Debug, Default, Decode, Encode, PartialEq, TypeInfo)] pub struct GratitudeConfig { - /// The perquintill of vested tokens that are given. + /// The permill of vested tokens that are given. pub vested_share: Permill, /// The start block of the vesting. pub start_block: BlockNumber, diff --git a/pallets/crowdloan/src/tests.rs b/pallets/crowdloan/src/tests.rs index 48d406756..a2bca39c2 100644 --- a/pallets/crowdloan/src/tests.rs +++ b/pallets/crowdloan/src/tests.rs @@ -456,8 +456,28 @@ fn validate_unsigned_works() { use sp_runtime::traits::ValidateUnsigned; let source = sp_runtime::transaction_validity::TransactionSource::External; let contributor = ACCOUNT_00; + let free_reserve = ACCOUNT_01; + let vested_reserve = ACCOUNT_02; + let contributor2 = ACCOUNT_03; + ExtBuilder::default() - .with_contributions(vec![(contributor.clone(), BALANCE_02)]) + .with_contributions(vec![ + (contributor.clone(), BALANCE_02), + (contributor2.clone(), BALANCE_02 + BALANCE_02), + ]) + .with_balances(vec![ + (free_reserve.clone(), BALANCE_01), + (vested_reserve.clone(), BALANCE_01), + ]) + .with_reserve(ReserveAccounts { + vested: vested_reserve, + free: free_reserve, + }) + .with_configuration(GratitudeConfig { + vested_share: Permill::from_percent(50), + start_block: 1, + vesting_length: 10, + }) .build() .execute_with(|| { assert_eq!( @@ -483,7 +503,17 @@ fn validate_unsigned_works() { receiver: ACCOUNT_02.clone() } ), - Err(InvalidTransaction::BadProof.into()) + Err(InvalidTransaction::Custom(crate::ValidityError::NoContributor as u8).into()) + ); + + assert_eq!( + crate::Pallet::::validate_unsigned( + source, + &crate::Call::receive_gratitude { + receiver: contributor2 + } + ), + Err(InvalidTransaction::Custom(crate::ValidityError::CannotSendGratitude as u8).into()) ); assert_eq!( From 2133775a8c71bfafbf43682851957cf3fb2d0e0a Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 13:52:22 +0200 Subject: [PATCH 28/47] =?UTF-8?q?=F0=9F=A7=B9=F0=9F=90=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pallets/crowdloan/src/lib.rs | 3 ++- pallets/crowdloan/src/tests.rs | 4 +--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index 3d89d39bb..e19a62fd7 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -431,7 +431,8 @@ pub mod pallet { /// Custom validity errors while validating transactions. #[repr(u8)] pub enum ValidityError { - /// The account is not registered and therefore not allowed to make this call. + /// The account is not registered and therefore not allowed to make this + /// call. NoContributor = 0, /// An internal error prevents the call from being submitted. CannotSendGratitude = 1, diff --git a/pallets/crowdloan/src/tests.rs b/pallets/crowdloan/src/tests.rs index a2bca39c2..4a8e7e83e 100644 --- a/pallets/crowdloan/src/tests.rs +++ b/pallets/crowdloan/src/tests.rs @@ -509,9 +509,7 @@ fn validate_unsigned_works() { assert_eq!( crate::Pallet::::validate_unsigned( source, - &crate::Call::receive_gratitude { - receiver: contributor2 - } + &crate::Call::receive_gratitude { receiver: contributor2 } ), Err(InvalidTransaction::Custom(crate::ValidityError::CannotSendGratitude as u8).into()) ); From 1962bf6bb09b94e0902d75bb4da6e60bd2feebd5 Mon Sep 17 00:00:00 2001 From: kiltbot <> Date: Wed, 27 Oct 2021 14:03:14 +0200 Subject: [PATCH 29/47] cargo run --quiet --release -p kilt-parachain --features=runtime-benchmarks -- benchmark --chain=spiritnet-dev --steps=50 --repeat=20 --pallet=crowdloan --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./runtimes/spiritnet/src/weights/crowdloan.rs --template=.maintain/runtime-weight-template.hbs --- runtimes/spiritnet/src/weights/crowdloan.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/runtimes/spiritnet/src/weights/crowdloan.rs b/runtimes/spiritnet/src/weights/crowdloan.rs index 1f3ffa4fb..e3a043494 100644 --- a/runtimes/spiritnet/src/weights/crowdloan.rs +++ b/runtimes/spiritnet/src/weights/crowdloan.rs @@ -48,32 +48,32 @@ use sp_std::marker::PhantomData; pub struct WeightInfo(PhantomData); impl crowdloan::WeightInfo for WeightInfo { fn set_registrar_account() -> Weight { - (19_796_000_u64) + (20_990_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_contribution() -> Weight { - (22_134_000_u64) + (23_380_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_config() -> Weight { - (19_503_000_u64) + (20_196_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_reserve_accounts() -> Weight { - (22_988_000_u64) + (24_140_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn receive_gratitude() -> Weight { - (162_343_000_u64) + (180_866_000_u64) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } fn remove_contribution() -> Weight { - (24_258_000_u64) + (23_617_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } From feef54251b049f3060598a6e386232114c220714 Mon Sep 17 00:00:00 2001 From: kiltbot <> Date: Wed, 27 Oct 2021 14:07:05 +0200 Subject: [PATCH 30/47] cargo run --quiet --release -p kilt-parachain --features=runtime-benchmarks -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=crowdloan --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./runtimes/peregrine/src/weights/crowdloan.rs --template=.maintain/runtime-weight-template.hbs --- runtimes/peregrine/src/weights/crowdloan.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/runtimes/peregrine/src/weights/crowdloan.rs b/runtimes/peregrine/src/weights/crowdloan.rs index aedc2492f..af633e234 100644 --- a/runtimes/peregrine/src/weights/crowdloan.rs +++ b/runtimes/peregrine/src/weights/crowdloan.rs @@ -48,32 +48,32 @@ use sp_std::marker::PhantomData; pub struct WeightInfo(PhantomData); impl crowdloan::WeightInfo for WeightInfo { fn set_registrar_account() -> Weight { - (20_725_000_u64) + (20_525_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_contribution() -> Weight { - (23_337_000_u64) + (23_570_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_config() -> Weight { - (20_508_000_u64) + (20_659_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_reserve_accounts() -> Weight { - (24_087_000_u64) + (23_874_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn receive_gratitude() -> Weight { - (170_326_000_u64) + (184_278_000_u64) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } fn remove_contribution() -> Weight { - (25_155_000_u64) + (24_909_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } From e72f5f73838f1a182c3ccf2959c82f6cd9dcc8c1 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 14:07:14 +0200 Subject: [PATCH 31/47] default config --- pallets/crowdloan/src/mock.rs | 14 ++++++------ pallets/crowdloan/src/tests.rs | 41 +++------------------------------- 2 files changed, 10 insertions(+), 45 deletions(-) diff --git a/pallets/crowdloan/src/mock.rs b/pallets/crowdloan/src/mock.rs index d9c5359b9..39a677797 100644 --- a/pallets/crowdloan/src/mock.rs +++ b/pallets/crowdloan/src/mock.rs @@ -23,6 +23,7 @@ use kilt_primitives::{constants::KILT, AccountId, Balance, BlockNumber, Hash, In use sp_runtime::{ testing::Header, traits::{BlakeTwo256, ConvertInto, IdentityLookup}, + Permill, }; type TestUncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -124,6 +125,11 @@ pub(crate) const ACCOUNT_04: TestAccountId = AccountId::new([4u8; 32]); #[allow(clippy::identity_op)] pub(crate) const BALANCE_01: TestBalance = 1 * KILT; pub(crate) const BALANCE_02: TestBalance = 2 * KILT; +pub(crate) const GRATITUDE_CONFIG: GratitudeConfig = GratitudeConfig { + vested_share: Permill::from_percent(50), + start_block: 1, + vesting_length: 10, +}; pub(crate) fn get_generated_events() -> Vec> { let events = System::events(); @@ -137,7 +143,6 @@ pub(crate) fn get_generated_events() -> Vec, - config: GratitudeConfig, reserve: ReserveAccounts, balances: Vec<(TestAccountId, TestBalance)>, } @@ -153,11 +158,6 @@ impl ExtBuilder { self } - pub(crate) fn with_configuration(mut self, config: GratitudeConfig) -> Self { - self.config = config; - self - } - pub(crate) fn with_reserve(mut self, reserve: ReserveAccounts) -> Self { self.reserve = reserve; self @@ -182,7 +182,7 @@ impl ExtBuilder { System::set_block_number(1); pallet_crowdloan::RegistrarAccount::::set(self.registrar_account); pallet_crowdloan::Reserve::::set(self.reserve); - pallet_crowdloan::Configuration::::set(self.config); + pallet_crowdloan::Configuration::::set(GRATITUDE_CONFIG.clone()); for (contributor_account, contribution_amount) in self.contributions.iter() { pallet_crowdloan::Contributions::::insert(contributor_account, contribution_amount); diff --git a/pallets/crowdloan/src/tests.rs b/pallets/crowdloan/src/tests.rs index 4a8e7e83e..dcf2fb599 100644 --- a/pallets/crowdloan/src/tests.rs +++ b/pallets/crowdloan/src/tests.rs @@ -273,11 +273,6 @@ fn test_send_gratitude_success() { (vested_reserve.clone(), BALANCE_01), ]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) - .with_configuration(GratitudeConfig { - vested_share: Permill::from_percent(50), - start_block: 1, - vesting_length: 10, - }) .build() .execute_with(|| { assert_ok!(Crowdloan::receive_gratitude(Origin::none(), contributor.clone())); @@ -311,11 +306,6 @@ fn test_send_gratitude_empty_free_reserve() { .with_registrar_account(registrar) .with_balances(vec![(vested_reserve, BALANCE_02)]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) - .with_configuration(GratitudeConfig { - vested_share: Permill::from_percent(50), - start_block: 1, - vesting_length: 10, - }) .build() .execute_with(|| { assert_noop!( @@ -340,11 +330,6 @@ fn test_send_gratitude_empty_vest_reserve() { .with_registrar_account(registrar) .with_balances(vec![(free_reserve, BALANCE_02)]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) - .with_configuration(GratitudeConfig { - vested_share: Permill::from_percent(50), - start_block: 1, - vesting_length: 10, - }) .build() .execute_with(|| { assert_noop!( @@ -369,11 +354,6 @@ fn test_send_gratitude_same_account_success() { .with_registrar_account(registrar) .with_balances(vec![(free_reserve.clone(), BALANCE_02)]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) - .with_configuration(GratitudeConfig { - vested_share: Permill::from_percent(50), - start_block: 1, - vesting_length: 10, - }) .build() .execute_with(|| { assert_ok!(Crowdloan::receive_gratitude(Origin::none(), contributor.clone())); @@ -406,11 +386,6 @@ fn test_send_gratitude_same_account_out_of_funds() { .with_registrar_account(registrar) .with_balances(vec![(free_reserve, BALANCE_01)]) .with_contributions(vec![(contributor.clone(), BALANCE_02)]) - .with_configuration(GratitudeConfig { - vested_share: Permill::from_percent(50), - start_block: 1, - vesting_length: 10, - }) .build() .execute_with(|| { assert_noop!( @@ -434,11 +409,6 @@ fn test_send_gratitude_contribution_not_found() { }) .with_registrar_account(registrar) .with_balances(vec![(free_reserve, BALANCE_01)]) - .with_configuration(GratitudeConfig { - vested_share: Permill::from_percent(50), - start_block: 1, - vesting_length: 10, - }) .build() .execute_with(|| { assert_noop!( @@ -473,11 +443,6 @@ fn validate_unsigned_works() { vested: vested_reserve, free: free_reserve, }) - .with_configuration(GratitudeConfig { - vested_share: Permill::from_percent(50), - start_block: 1, - vesting_length: 10, - }) .build() .execute_with(|| { assert_eq!( @@ -536,9 +501,9 @@ fn test_set_configuration() { let free_reserve = ACCOUNT_02; let vested_reserve = ACCOUNT_02; let config = GratitudeConfig { - vested_share: Permill::from_percent(50), - start_block: 1, - vesting_length: 10, + vested_share: Permill::from_percent(5), + start_block: 2, + vesting_length: 20, }; ExtBuilder::default() From 28ec2591d3d6b1098201b6091e8f584c573221a9 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Wed, 27 Oct 2021 14:42:12 +0200 Subject: [PATCH 32/47] filter gratitude --- runtimes/spiritnet/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index a738e2800..ec052be79 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -135,6 +135,7 @@ impl Contains for BaseFilter { | Call::Balances { .. } | Call::Delegation { .. } | Call::ParachainStaking(parachain_staking::Call::join_candidates { .. }) + | Call::CrowdloanContributors(crowdloan::Call::receive_gratitude { .. }) ) } } From a83a69754263cdfd3cdc8608fa466a068d0ee433 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Thu, 28 Oct 2021 09:02:24 +0200 Subject: [PATCH 33/47] handle error cases --- pallets/crowdloan/src/lib.rs | 40 +++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index e19a62fd7..61e26a354 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -170,6 +170,10 @@ pub mod pallet { /// \[contributor account\] GratitudeReceived(AccountIdOf), + /// There was an error while sending the gratitude. + /// \[contributor account\] + GratitudeError(AccountIdOf), + /// A new configuration was set. /// \[new configuration\] UpdatedConfig(GratitudeConfig>), @@ -339,20 +343,22 @@ pub mod pallet { /// Moves tokens to the given account according to the vote that was /// giving in favour of our parachain. /// + /// This is an unsigned extrinsic. The validity needs to be checked with + /// `ValidateUnsigned`. + /// /// # /// Weight: O(1) /// - Reads: Contributions, Reserve, Configuration, [receiver account], /// [free reserve account], [vested reserve account] /// - Writes: Contributions, [free reserve account], [vested reserve /// account], [receiver account] - #[pallet::weight((WeightInfoOf::::receive_gratitude(), DispatchClass::Normal, Pays::No))] + #[pallet::weight(WeightInfoOf::::receive_gratitude())] pub fn receive_gratitude(origin: OriginFor, receiver: AccountIdOf) -> DispatchResult { ensure_none(origin)?; let gratitude = Self::split_gratitude_for(&receiver)?; Self::ensure_can_send_gratitude(&gratitude)?; - // *** No failure beyond this call! The contributor was removed. *** Contributions::::remove(&receiver); let SplitGratitude { vested, free } = gratitude; @@ -361,18 +367,38 @@ pub mod pallet { // Transfer the free amount. Should not fail since checked we // ensure_can_withdraw. - CurrencyOf::::transfer(&reserve.free, &receiver, free, ExistenceRequirement::AllowDeath)?; + let result_free_transfer = + CurrencyOf::::transfer(&reserve.free, &receiver, free, ExistenceRequirement::AllowDeath); + debug_assert!( + result_free_transfer.is_ok(), + "free transfer failed after we checked in ensure_can_withdraw" + ); // Transfer the vested amount and set the vesting schedule. Should not fail // since checked we ensure_can_withdraw. - CurrencyOf::::transfer(&reserve.vested, &receiver, vested, ExistenceRequirement::AllowDeath)?; + let result_vest_transfer = + CurrencyOf::::transfer(&reserve.vested, &receiver, vested, ExistenceRequirement::AllowDeath); + debug_assert!( + result_vest_transfer.is_ok(), + "vested transfer failed after we checked in ensure_can_withdraw" + ); + let per_block = vested .checked_div(&BalanceOf::::from(config.vesting_length)) .unwrap_or(vested); // vesting should not fail since we have transferred enough free balance. - VestingOf::::add_vesting_schedule(&receiver, vested, per_block, config.start_block)?; - - Self::deposit_event(Event::GratitudeReceived(receiver)); + let result_versting = + VestingOf::::add_vesting_schedule(&receiver, vested, per_block, config.start_block); + debug_assert!( + result_versting.is_ok(), + "vesting failed for vested coins after we transferred enough coins that ought to be vestable." + ); + + if result_versting.is_ok() && result_vest_transfer.is_ok() && result_free_transfer.is_ok() { + Self::deposit_event(Event::GratitudeReceived(receiver)); + } else { + Self::deposit_event(Event::GratitudeError(receiver)); + } Ok(()) } From e9c782e3a251a6c79f4c2c102a6424278f066176 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Thu, 28 Oct 2021 09:11:40 +0200 Subject: [PATCH 34/47] ensure can vest & optimisations --- pallets/crowdloan/src/lib.rs | 69 +++++++++++++++++++++++------------- 1 file changed, 44 insertions(+), 25 deletions(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index 61e26a354..b981a131a 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -357,7 +357,7 @@ pub mod pallet { ensure_none(origin)?; let gratitude = Self::split_gratitude_for(&receiver)?; - Self::ensure_can_send_gratitude(&gratitude)?; + Self::ensure_can_send_gratitude(&receiver, gratitude)?; Contributions::::remove(&receiver); @@ -404,6 +404,7 @@ pub mod pallet { } } + #[derive(Clone, Copy, Debug)] struct SplitGratitude { vested: Balance, free: Balance, @@ -421,34 +422,52 @@ pub mod pallet { Ok(SplitGratitude { vested, free }) } - fn ensure_can_send_gratitude(SplitGratitude { vested, free }: &SplitGratitude>) -> DispatchResult { + fn ensure_can_send_gratitude( + receiver: &AccountIdOf, + SplitGratitude { vested, free }: SplitGratitude>, + ) -> DispatchResult { let reserve = Reserve::::get(); + let config = Configuration::::get(); - let new_free_acc_balance = CurrencyOf::::free_balance(&reserve.free) - .checked_sub(free) - .ok_or(Error::::InsufficientBalance)?; - let mut new_vested_acc_balance = CurrencyOf::::free_balance(&reserve.vested) - .checked_sub(vested) - .ok_or(Error::::InsufficientBalance)?; if reserve.free == reserve.vested { - // if free and vested are the same we need to make sure that we can withdraw - // both from the same account - new_vested_acc_balance = new_vested_acc_balance - .checked_sub(free) + let amount = free.saturating_add(vested); + let new_acc_balance = CurrencyOf::::free_balance(&reserve.free) + .checked_sub(&amount) + .ok_or(Error::::InsufficientBalance)?; + + CurrencyOf::::ensure_can_withdraw( + &reserve.free, + amount, + WithdrawReasons::TRANSFER, + new_acc_balance, + )?; + } else { + let new_free_acc_balance = CurrencyOf::::free_balance(&reserve.free) + .checked_sub(&free) .ok_or(Error::::InsufficientBalance)?; + let new_vested_acc_balance = CurrencyOf::::free_balance(&reserve.vested) + .checked_sub(&vested) + .ok_or(Error::::InsufficientBalance)?; + + CurrencyOf::::ensure_can_withdraw( + &reserve.free, + free, + WithdrawReasons::TRANSFER, + new_free_acc_balance, + )?; + CurrencyOf::::ensure_can_withdraw( + &reserve.vested, + vested, + WithdrawReasons::TRANSFER, + new_vested_acc_balance, + )?; } - CurrencyOf::::ensure_can_withdraw( - &reserve.free, - *free, - WithdrawReasons::TRANSFER, - new_free_acc_balance, - )?; - CurrencyOf::::ensure_can_withdraw( - &reserve.vested, - *vested, - WithdrawReasons::TRANSFER, - new_vested_acc_balance, - )?; + + let per_block = vested + .checked_div(&BalanceOf::::from(config.vesting_length)) + .unwrap_or(vested); + // vesting should not fail since we have transferred enough free balance. + VestingOf::::can_add_vesting_schedule(receiver, vested, per_block, config.start_block)?; Ok(()) } @@ -481,7 +500,7 @@ pub mod pallet { let gratitude = Self::split_gratitude_for(receiver) .map_err(|_| InvalidTransaction::Custom(ValidityError::NoContributor as u8))?; - Self::ensure_can_send_gratitude(&gratitude) + Self::ensure_can_send_gratitude(&receiver, gratitude) .map_err(|_| InvalidTransaction::Custom(ValidityError::CannotSendGratitude as u8))?; Ok(ValidTransaction { From 865af56d6f95348cb05235f2b0ca904fd2584b48 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Thu, 28 Oct 2021 09:16:40 +0200 Subject: [PATCH 35/47] remove trait bound from benchmark --- pallets/crowdloan/src/benchmarking.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/pallets/crowdloan/src/benchmarking.rs b/pallets/crowdloan/src/benchmarking.rs index 5d875571f..b58438131 100644 --- a/pallets/crowdloan/src/benchmarking.rs +++ b/pallets/crowdloan/src/benchmarking.rs @@ -31,8 +31,6 @@ const SEED_1: u32 = 1; const SEED_2: u32 = 2; benchmarks! { - where_clause { where ::BlockNumber: From } - set_registrar_account { let registrar: AccountIdOf = account("registrar", 0, SEED_1); let new_registrar: AccountIdOf = account("new_registrar", 0, SEED_2); @@ -66,8 +64,8 @@ benchmarks! { let config = GratitudeConfig:: { vested_share: Permill::from_percent(42), - start_block: 1.into(), - vesting_length: 10.into(), + start_block: 1_u32.into(), + vesting_length: 10_u32.into(), }; }: _(RawOrigin::Signed(registrar), config.clone()) verify { @@ -82,10 +80,14 @@ benchmarks! { let reserve_free: AccountIdOf = account("reserve_free", 0, SEED_1); let reserve_vested: AccountIdOf = account("reserve_vested", 0, SEED_1); RegistrarAccount::::set(registrar.clone()); + + let unlookup_reserve_vested = T::Lookup::unlookup(reserve_vested.clone()); + let unlookup_reserve_free = T::Lookup::unlookup(reserve_free.clone()); + }: _( RawOrigin::Signed(registrar), - T::Lookup::unlookup(reserve_vested.clone()), - T::Lookup::unlookup(reserve_free.clone()) + unlookup_reserve_vested, + unlookup_reserve_free ) verify { assert_eq!( @@ -104,9 +106,7 @@ benchmarks! { let reserve_vested: AccountIdOf = account("reserve_vested", 0, SEED_1); let contributor: AccountIdOf = account("contributor", 0, SEED_1); - let contribution: BalanceOf = CurrencyOf::::minimum_balance() - + CurrencyOf::::minimum_balance() - + CurrencyOf::::minimum_balance(); + let contribution: BalanceOf = CurrencyOf::::minimum_balance() * 3_u32.into(); RegistrarAccount::::set(registrar); Reserve::::set(ReserveAccounts { @@ -116,8 +116,8 @@ benchmarks! { Contributions::::insert(&contributor, contribution); Configuration::::set(GratitudeConfig { vested_share: Permill::from_percent(50), - start_block: 1.into(), - vesting_length: 10.into(), + start_block: 1_u32.into(), + vesting_length: 10_u32.into(), }); CurrencyOf::::make_free_balance_be(&reserve_vested, contribution); CurrencyOf::::make_free_balance_be(&reserve_free, contribution); From e4ecf0de0f48433e87f01b813d94bfc5c0c73580 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Thu, 28 Oct 2021 09:19:29 +0200 Subject: [PATCH 36/47] update weight template --- .maintain/runtime-weight-template.hbs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/.maintain/runtime-weight-template.hbs b/.maintain/runtime-weight-template.hbs index 09ee9b3c5..01d1f40f5 100644 --- a/.maintain/runtime-weight-template.hbs +++ b/.maintain/runtime-weight-template.hbs @@ -34,32 +34,35 @@ use frame_support::{traits::Get, weights::Weight}; use sp_std::marker::PhantomData; -/// Weights for {{pallet}} using the recommended hardware. +/// Weight functions for `{{pallet}}`. pub struct WeightInfo(PhantomData); impl {{pallet}}::WeightInfo for WeightInfo { {{~#each benchmarks as |benchmark|}} + {{~#each benchmark.comments as |comment|}} + // {{comment}} + {{~/each}} fn {{benchmark.name~}} ( {{~#each benchmark.components as |c| ~}} {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} ) -> Weight { - ({{underscore benchmark.base_weight}}_u64) + ({{underscore benchmark.base_weight}} as Weight) {{~#each benchmark.component_weight as |cw|}} // Standard Error: {{underscore cw.error}} - .saturating_add(({{underscore cw.slope}}_u64).saturating_mul({{cw.name}} as Weight)) + .saturating_add(({{underscore cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight)) {{~/each}} {{~#if (ne benchmark.base_reads "0")}} - .saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}}_u64)) + .saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}} as Weight)) {{~/if}} {{~#each benchmark.component_reads as |cr|}} - .saturating_add(T::DbWeight::get().reads(({{cr.slope}}_u64).saturating_mul({{cr.name}} as Weight))) + .saturating_add(T::DbWeight::get().reads(({{cr.slope}} as Weight).saturating_mul({{cr.name}} as Weight))) {{~/each}} {{~#if (ne benchmark.base_writes "0")}} - .saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}}_u64)) + .saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}} as Weight)) {{~/if}} {{~#each benchmark.component_writes as |cw|}} - .saturating_add(T::DbWeight::get().writes(({{cw.slope}}_u64).saturating_mul({{cw.name}} as Weight))) + .saturating_add(T::DbWeight::get().writes(({{cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight))) {{~/each}} } {{~/each}} -} \ No newline at end of file +} From cc60d3b19ddd4d0a15433716335ef683006d0edd Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Thu, 28 Oct 2021 09:24:42 +0200 Subject: [PATCH 37/47] clippy --- pallets/crowdloan/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index b981a131a..8cb8067f7 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -500,7 +500,7 @@ pub mod pallet { let gratitude = Self::split_gratitude_for(receiver) .map_err(|_| InvalidTransaction::Custom(ValidityError::NoContributor as u8))?; - Self::ensure_can_send_gratitude(&receiver, gratitude) + Self::ensure_can_send_gratitude(receiver, gratitude) .map_err(|_| InvalidTransaction::Custom(ValidityError::CannotSendGratitude as u8))?; Ok(ValidTransaction { From 67ac756f950141a1428e7222b72b1183ca8e385e Mon Sep 17 00:00:00 2001 From: kiltbot <> Date: Thu, 28 Oct 2021 09:39:32 +0200 Subject: [PATCH 38/47] cargo run --quiet --release -p kilt-parachain --features=runtime-benchmarks -- benchmark --chain=spiritnet-dev --steps=50 --repeat=20 --pallet=crowdloan --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./runtimes/spiritnet/src/weights/crowdloan.rs --template=.maintain/runtime-weight-template.hbs --- runtimes/spiritnet/src/weights/crowdloan.rs | 57 +++++++++++++-------- 1 file changed, 36 insertions(+), 21 deletions(-) diff --git a/runtimes/spiritnet/src/weights/crowdloan.rs b/runtimes/spiritnet/src/weights/crowdloan.rs index e3a043494..15640d403 100644 --- a/runtimes/spiritnet/src/weights/crowdloan.rs +++ b/runtimes/spiritnet/src/weights/crowdloan.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for crowdloan //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-10-27, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2021-10-28, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("spiritnet-dev"), DB CACHE: 128 // Executed Command: @@ -44,37 +44,52 @@ use frame_support::{traits::Get, weights::Weight}; use sp_std::marker::PhantomData; -/// Weights for crowdloan using the recommended hardware. +/// Weight functions for `crowdloan`. pub struct WeightInfo(PhantomData); impl crowdloan::WeightInfo for WeightInfo { + // Storage: CrowdloanContributors RegistrarAccount (r:1 w:1) fn set_registrar_account() -> Weight { - (20_990_000_u64) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + (20_815_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + // Storage: CrowdloanContributors RegistrarAccount (r:1 w:0) + // Storage: CrowdloanContributors Contributions (r:1 w:1) fn set_contribution() -> Weight { - (23_380_000_u64) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + (23_331_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + // Storage: CrowdloanContributors RegistrarAccount (r:1 w:0) + // Storage: CrowdloanContributors Configuration (r:0 w:1) fn set_config() -> Weight { - (20_196_000_u64) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + (20_834_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + // Storage: CrowdloanContributors RegistrarAccount (r:1 w:0) + // Storage: CrowdloanContributors Reserve (r:1 w:1) fn set_reserve_accounts() -> Weight { - (24_140_000_u64) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + (24_089_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + // Storage: CrowdloanContributors Contributions (r:1 w:1) + // Storage: CrowdloanContributors Configuration (r:1 w:0) + // Storage: CrowdloanContributors Reserve (r:1 w:0) + // Storage: System Account (r:3 w:3) + // Storage: Vesting Vesting (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) fn receive_gratitude() -> Weight { - (180_866_000_u64) - .saturating_add(T::DbWeight::get().reads(8_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) + (193_792_000 as Weight) + .saturating_add(T::DbWeight::get().reads(8 as Weight)) + .saturating_add(T::DbWeight::get().writes(6 as Weight)) } + // Storage: CrowdloanContributors RegistrarAccount (r:1 w:0) + // Storage: CrowdloanContributors Contributions (r:1 w:1) fn remove_contribution() -> Weight { - (23_617_000_u64) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + (24_971_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) } -} \ No newline at end of file +} From 9cb4c238ac3f8d77e7438ef6e6d138062507cf79 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Thu, 28 Oct 2021 10:06:40 +0200 Subject: [PATCH 39/47] allow unnecessary_cast --- .maintain/weight-template.hbs | 1 + runtimes/spiritnet/src/weights/crowdloan.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/.maintain/weight-template.hbs b/.maintain/weight-template.hbs index 610a9c64c..4276b82e6 100644 --- a/.maintain/weight-template.hbs +++ b/.maintain/weight-template.hbs @@ -30,6 +30,7 @@ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] +#![allow(unnecessary_cast)] use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; diff --git a/runtimes/spiritnet/src/weights/crowdloan.rs b/runtimes/spiritnet/src/weights/crowdloan.rs index 15640d403..01c23b491 100644 --- a/runtimes/spiritnet/src/weights/crowdloan.rs +++ b/runtimes/spiritnet/src/weights/crowdloan.rs @@ -40,6 +40,7 @@ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] +#![allow(unnecessary_cast)] use frame_support::{traits::Get, weights::Weight}; use sp_std::marker::PhantomData; From f9266bceed14a6091bbf4c7b0080520d17a127e8 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Thu, 28 Oct 2021 10:21:10 +0200 Subject: [PATCH 40/47] clippy again --- runtimes/spiritnet/src/weights/crowdloan.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtimes/spiritnet/src/weights/crowdloan.rs b/runtimes/spiritnet/src/weights/crowdloan.rs index 01c23b491..d559a4504 100644 --- a/runtimes/spiritnet/src/weights/crowdloan.rs +++ b/runtimes/spiritnet/src/weights/crowdloan.rs @@ -40,7 +40,7 @@ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(unnecessary_cast)] +#![allow(clippy::unnecessary_cast)] use frame_support::{traits::Get, weights::Weight}; use sp_std::marker::PhantomData; From 0acd1081320bb2e802a6262b54ed06a4af0871d1 Mon Sep 17 00:00:00 2001 From: kiltbot <> Date: Thu, 28 Oct 2021 10:41:43 +0200 Subject: [PATCH 41/47] cargo run --quiet --release -p kilt-parachain --features=runtime-benchmarks -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=crowdloan --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./runtimes/peregrine/src/weights/crowdloan.rs --template=.maintain/runtime-weight-template.hbs --- runtimes/peregrine/src/weights/crowdloan.rs | 57 +++++++++++++-------- 1 file changed, 36 insertions(+), 21 deletions(-) diff --git a/runtimes/peregrine/src/weights/crowdloan.rs b/runtimes/peregrine/src/weights/crowdloan.rs index af633e234..a919b5412 100644 --- a/runtimes/peregrine/src/weights/crowdloan.rs +++ b/runtimes/peregrine/src/weights/crowdloan.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for crowdloan //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-10-27, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2021-10-28, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 // Executed Command: @@ -44,37 +44,52 @@ use frame_support::{traits::Get, weights::Weight}; use sp_std::marker::PhantomData; -/// Weights for crowdloan using the recommended hardware. +/// Weight functions for `crowdloan`. pub struct WeightInfo(PhantomData); impl crowdloan::WeightInfo for WeightInfo { + // Storage: CrowdloanContributors RegistrarAccount (r:1 w:1) fn set_registrar_account() -> Weight { - (20_525_000_u64) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + (21_029_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + // Storage: CrowdloanContributors RegistrarAccount (r:1 w:0) + // Storage: CrowdloanContributors Contributions (r:1 w:1) fn set_contribution() -> Weight { - (23_570_000_u64) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + (23_368_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + // Storage: CrowdloanContributors RegistrarAccount (r:1 w:0) + // Storage: CrowdloanContributors Configuration (r:0 w:1) fn set_config() -> Weight { - (20_659_000_u64) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + (20_771_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + // Storage: CrowdloanContributors RegistrarAccount (r:1 w:0) + // Storage: CrowdloanContributors Reserve (r:1 w:1) fn set_reserve_accounts() -> Weight { - (23_874_000_u64) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + (24_498_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + // Storage: CrowdloanContributors Contributions (r:1 w:1) + // Storage: CrowdloanContributors Configuration (r:1 w:0) + // Storage: CrowdloanContributors Reserve (r:1 w:0) + // Storage: System Account (r:3 w:3) + // Storage: Vesting Vesting (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) fn receive_gratitude() -> Weight { - (184_278_000_u64) - .saturating_add(T::DbWeight::get().reads(8_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) + (198_621_000 as Weight) + .saturating_add(T::DbWeight::get().reads(8 as Weight)) + .saturating_add(T::DbWeight::get().writes(6 as Weight)) } + // Storage: CrowdloanContributors RegistrarAccount (r:1 w:0) + // Storage: CrowdloanContributors Contributions (r:1 w:1) fn remove_contribution() -> Weight { - (24_909_000_u64) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + (25_012_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) } -} \ No newline at end of file +} From d45ad85242ecabcfb88b97d59a64a9f0ade7af94 Mon Sep 17 00:00:00 2001 From: kiltbot <> Date: Thu, 28 Oct 2021 10:45:31 +0200 Subject: [PATCH 42/47] cargo run --quiet --release -p kilt-parachain --features=runtime-benchmarks -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=crowdloan --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=pallets/crowdloan/src/default_weights.rs --template=.maintain/weight-template.hbs --- pallets/crowdloan/src/default_weights.rs | 27 ++++++++++++------------ 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/pallets/crowdloan/src/default_weights.rs b/pallets/crowdloan/src/default_weights.rs index d49aa15d4..7326757b7 100644 --- a/pallets/crowdloan/src/default_weights.rs +++ b/pallets/crowdloan/src/default_weights.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for crowdloan //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-10-27, STEPS: {{cmd.steps}}\, REPEAT: {{cmd.repeat}}\, LOW RANGE: {{cmd.lowest_range_values}}\, HIGH RANGE: {{cmd.highest_range_values}}\ +//! DATE: 2021-10-28, STEPS: {{cmd.steps}}\, REPEAT: {{cmd.repeat}}\, LOW RANGE: {{cmd.lowest_range_values}}\, HIGH RANGE: {{cmd.highest_range_values}}\ //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 // Executed Command: @@ -40,6 +40,7 @@ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] +#![allow(unnecessary_cast)] use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; @@ -58,32 +59,32 @@ pub trait WeightInfo { pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { fn set_registrar_account() -> Weight { - (21_644_000_u64) + (20_165_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_contribution() -> Weight { - (23_815_000_u64) + (22_721_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_config() -> Weight { - (21_247_000_u64) + (20_508_000_u64) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn set_reserve_accounts() -> Weight { - (24_336_000_u64) + (23_930_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn receive_gratitude() -> Weight { - (178_299_000_u64) + (194_132_000_u64) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } fn remove_contribution() -> Weight { - (25_459_000_u64) + (24_979_000_u64) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -92,32 +93,32 @@ impl WeightInfo for SubstrateWeight { // For backwards compatibility and tests impl WeightInfo for () { fn set_registrar_account() -> Weight { - (21_644_000_u64) + (20_165_000_u64) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } fn set_contribution() -> Weight { - (23_815_000_u64) + (22_721_000_u64) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } fn set_config() -> Weight { - (21_247_000_u64) + (20_508_000_u64) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } fn set_reserve_accounts() -> Weight { - (24_336_000_u64) + (23_930_000_u64) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } fn receive_gratitude() -> Weight { - (178_299_000_u64) + (194_132_000_u64) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } fn remove_contribution() -> Weight { - (25_459_000_u64) + (24_979_000_u64) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } From e32f92d828c59238767d8ef703ea60b3d202549f Mon Sep 17 00:00:00 2001 From: Albrecht <14820950+weichweich@users.noreply.github.com> Date: Thu, 28 Oct 2021 10:54:12 +0200 Subject: [PATCH 43/47] Update pallets/crowdloan/src/lib.rs Co-authored-by: Shawn Tabrizi --- pallets/crowdloan/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index a84c1cfb0..f128013e7 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -394,7 +394,7 @@ pub mod pallet { .checked_div(&BalanceOf::::from(config.vesting_length)) .unwrap_or(vested); // vesting should not fail since we have transferred enough free balance. - let result_versting = + let result_vesting = VestingOf::::add_vesting_schedule(&receiver, vested, per_block, config.start_block); debug_assert!( result_versting.is_ok(), From 99162bf3b288d0b0b80ddc6e1de6f85c3df088ef Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Thu, 28 Oct 2021 10:55:02 +0200 Subject: [PATCH 44/47] fix spelling --- pallets/crowdloan/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index f128013e7..1b41e69c5 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -397,11 +397,11 @@ pub mod pallet { let result_vesting = VestingOf::::add_vesting_schedule(&receiver, vested, per_block, config.start_block); debug_assert!( - result_versting.is_ok(), + result_vesting.is_ok(), "vesting failed for vested coins after we transferred enough coins that ought to be vestable." ); - if result_versting.is_ok() && result_vest_transfer.is_ok() && result_free_transfer.is_ok() { + if result_vesting.is_ok() && result_vest_transfer.is_ok() && result_free_transfer.is_ok() { Self::deposit_event(Event::GratitudeReceived(receiver)); } else { Self::deposit_event(Event::GratitudeError(receiver)); From 1c4d440f44bb84a73d451ef91fd12ed6c2e18a9c Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Thu, 28 Oct 2021 11:00:50 +0200 Subject: [PATCH 45/47] =?UTF-8?q?=F0=9F=A7=B9=F0=9F=90=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pallets/crowdloan/src/lib.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index 1b41e69c5..868dd53ac 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -394,8 +394,7 @@ pub mod pallet { .checked_div(&BalanceOf::::from(config.vesting_length)) .unwrap_or(vested); // vesting should not fail since we have transferred enough free balance. - let result_vesting = - VestingOf::::add_vesting_schedule(&receiver, vested, per_block, config.start_block); + let result_vesting = VestingOf::::add_vesting_schedule(&receiver, vested, per_block, config.start_block); debug_assert!( result_vesting.is_ok(), "vesting failed for vested coins after we transferred enough coins that ought to be vestable." From 1dba99bb2a3b473f7d01b031b04e8185bd4df2e4 Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Thu, 28 Oct 2021 11:28:04 +0200 Subject: [PATCH 46/47] fix renamed clippy --- .maintain/weight-template.hbs | 5 ++++- pallets/crowdloan/src/default_weights.rs | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.maintain/weight-template.hbs b/.maintain/weight-template.hbs index 4276b82e6..69cb84e08 100644 --- a/.maintain/weight-template.hbs +++ b/.maintain/weight-template.hbs @@ -30,7 +30,7 @@ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(unnecessary_cast)] +#![allow(clippy::unnecessary_cast)] use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; @@ -50,6 +50,9 @@ pub trait WeightInfo { pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { {{~#each benchmarks as |benchmark|}} + {{~#each benchmark.comments as |comment|}} + // {{comment}} + {{~/each}} fn {{benchmark.name~}} ( {{~#each benchmark.components as |c| ~}} diff --git a/pallets/crowdloan/src/default_weights.rs b/pallets/crowdloan/src/default_weights.rs index 7326757b7..5db749bf5 100644 --- a/pallets/crowdloan/src/default_weights.rs +++ b/pallets/crowdloan/src/default_weights.rs @@ -40,7 +40,7 @@ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(unnecessary_cast)] +#![allow(clippy::unnecessary_cast)] use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; From 86bf869699e9ed52f34175e2a7621d18fe95d43c Mon Sep 17 00:00:00 2001 From: weichweich <14820950+weichweich@users.noreply.github.com> Date: Thu, 28 Oct 2021 12:18:57 +0200 Subject: [PATCH 47/47] fix clippy once and for all! --- .maintain/runtime-weight-template.hbs | 1 + runtimes/peregrine/src/weights/crowdloan.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/.maintain/runtime-weight-template.hbs b/.maintain/runtime-weight-template.hbs index 01d1f40f5..9ebfa5a8c 100644 --- a/.maintain/runtime-weight-template.hbs +++ b/.maintain/runtime-weight-template.hbs @@ -30,6 +30,7 @@ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] +#![allow(clippy::unnecessary_cast)] use frame_support::{traits::Get, weights::Weight}; use sp_std::marker::PhantomData; diff --git a/runtimes/peregrine/src/weights/crowdloan.rs b/runtimes/peregrine/src/weights/crowdloan.rs index a919b5412..625851d35 100644 --- a/runtimes/peregrine/src/weights/crowdloan.rs +++ b/runtimes/peregrine/src/weights/crowdloan.rs @@ -40,6 +40,7 @@ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] +#![allow(clippy::unnecessary_cast)] use frame_support::{traits::Get, weights::Weight}; use sp_std::marker::PhantomData;