瀏覽代碼

runtime: Upgrade the ‘stake’ pallet.

Shamil Gadelshin 4 年之前
父節點
當前提交
5daaca2d64

+ 16 - 0
Cargo.lock

@@ -969,6 +969,22 @@ dependencies = [
  "sp-runtime",
 ]
 
+[[package]]
+name = "pallet-stake"
+version = "3.0.0"
+dependencies = [
+ "frame-support",
+ "frame-system",
+ "pallet-balances",
+ "pallet-timestamp",
+ "parity-scale-codec",
+ "sp-arithmetic",
+ "sp-core",
+ "sp-io",
+ "sp-runtime",
+ "sp-std",
+]
+
 [[package]]
 name = "pallet-timestamp"
 version = "2.0.0-rc4"

+ 1 - 1
Cargo.toml

@@ -13,7 +13,7 @@ members = [
 	"runtime-modules/memo",
 	"runtime-modules/recurring-reward",
 #	"runtime-modules/service-discovery",
-#	"runtime-modules/stake",
+	"runtime-modules/stake",
 #	"runtime-modules/storage",
 	"runtime-modules/token-minting",
 	"runtime-modules/versioned-store",

+ 0 - 5
runtime-modules/recurring-reward/src/mock/mod.rs

@@ -59,11 +59,6 @@ impl system::Trait for Test {
 
 parameter_types! {
     pub const ExistentialDeposit: u32 = 0;
-    pub const TransferFee: u32 = 0;
-    pub const CreationFee: u32 = 0;
-    pub const TransactionBaseFee: u32 = 1;
-    pub const TransactionByteFee: u32 = 0;
-    pub const InitialMembersBalance: u64 = 2000;
 }
 
 impl balances::Trait for Test {

+ 16 - 36
runtime-modules/stake/Cargo.toml

@@ -1,50 +1,30 @@
 [package]
-name = 'substrate-stake-module'
-version = '2.0.0'
+name = 'pallet-stake'
+version = '3.0.0'
 authors = ['Joystream contributors']
 edition = '2018'
 
 [dependencies]
-hex-literal = '0.1.0'
-serde = { version = '1.0', optional = true }
-serde_derive = { version = '1.0', optional = true }
-rstd = { package = 'sr-std', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-runtime-primitives = { package = 'sr-primitives', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-srml-support = { package = 'srml-support', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-srml-support-procedural = { package = 'srml-support-procedural', git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-system = { package = 'srml-system', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-balances = { package = 'srml-balances', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-codec = { package = 'parity-scale-codec', version = '1.0.0', default-features = false, features = ['derive'] }
-# https://users.rust-lang.org/t/failure-derive-compilation-error/39062
-quote = '<=1.0.2'
-
-[dependencies.timestamp]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'srml-timestamp'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dependencies.runtime-io]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'sr-io'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
+codec = { package = 'parity-scale-codec', version = '1.3.1', default-features = false, features = ['derive'] }
+rstd = { package = 'sp-std', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
+frame-support = { package = 'frame-support', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
+system = { package = 'frame-system', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
+sp-arithmetic = { package = 'sp-arithmetic', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
+sp-runtime = { package = 'sp-runtime', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
 
 [dev-dependencies]
-runtime-io = { package = 'sr-io', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
-primitives = { package = 'substrate-primitives', git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
+sp-io = { package = 'sp-io', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
+sp-core = { package = 'sp-core', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
+timestamp = { package = 'pallet-timestamp', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
+balances = { package = 'pallet-balances', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
 
 [features]
 default = ['std']
 std = [
-	'serde',
-	'serde_derive',
 	'codec/std',
 	'rstd/std',
-	'runtime-io/std',
-	'runtime-primitives/std',
-	'srml-support/std',
+	'frame-support/std',
 	'system/std',
-  	'balances/std',
-	'timestamp/std',
-]
+	'sp-arithmetic/std',
+	'sp-runtime/std',
+]

+ 24 - 28
runtime-modules/stake/src/lib.rs

@@ -1,17 +1,15 @@
 // Ensure we're `no_std` when compiling for Wasm.
 #![cfg_attr(not(feature = "std"), no_std)]
 
-use rstd::prelude::*;
-
 use codec::{Codec, Decode, Encode};
-use runtime_primitives::traits::{
-    AccountIdConversion, MaybeSerialize, Member, One, SimpleArithmetic, Zero,
-};
-use runtime_primitives::ModuleId;
-use srml_support::traits::{Currency, ExistenceRequirement, Get, Imbalance, WithdrawReasons};
-use srml_support::{decl_module, decl_storage, ensure, Parameter};
-
+use frame_support::storage::IterableStorageMap;
+use frame_support::traits::{Currency, ExistenceRequirement, Get, Imbalance, WithdrawReasons};
+use frame_support::{decl_module, decl_storage, ensure, Parameter};
 use rstd::collections::btree_map::BTreeMap;
+use rstd::prelude::*;
+use sp_arithmetic::traits::{BaseArithmetic, One, Zero};
+use sp_runtime::traits::{AccountIdConversion, MaybeSerialize, Member};
+use sp_runtime::ModuleId;
 
 mod errors;
 pub use errors::*;
@@ -38,7 +36,7 @@ pub trait Trait: system::Trait + Sized {
     /// The type used as a stake identifier.
     type StakeId: Parameter
         + Member
-        + SimpleArithmetic
+        + BaseArithmetic
         + Codec
         + Default
         + Copy
@@ -48,7 +46,7 @@ pub trait Trait: system::Trait + Sized {
     /// The type used as slash identifier.
     type SlashId: Parameter
         + Member
-        + SimpleArithmetic
+        + BaseArithmetic
         + Codec
         + Default
         + Copy
@@ -201,8 +199,8 @@ pub struct StakedState<BlockNumber, Balance, SlashId: Ord> {
 
 impl<BlockNumber, Balance, SlashId> StakedState<BlockNumber, Balance, SlashId>
 where
-    BlockNumber: SimpleArithmetic + Copy,
-    Balance: SimpleArithmetic + Copy,
+    BlockNumber: BaseArithmetic + Copy,
+    Balance: BaseArithmetic + Copy,
     SlashId: Ord + Copy,
 {
     /// Iterates over all ongoing slashes and decrements blocks_remaining_in_active_period_for_slashing of active slashes (advancing the timer).
@@ -268,7 +266,7 @@ where
     /// For all slahes that should be executed, will apply the Slash to the staked amount, and drop it from the ongoing slashes map.
     /// Returns a vector of the executed slashes outcome: (SlashId, Slashed Amount, Remaining Staked Amount)
     fn finalize_slashes(&mut self, minimum_balance: Balance) -> Vec<(SlashId, Balance, Balance)> {
-        let mut finalized_slashes: Vec<(SlashId, Balance, Balance)> = vec![];
+        let mut finalized_slashes: Vec<(SlashId, Balance, Balance)> = Vec::new();
 
         for (slash_id, slash) in self.get_slashes_to_finalize().iter() {
             // apply the slashing and get back actual amount slashed
@@ -305,8 +303,8 @@ pub struct Stake<BlockNumber, Balance, SlashId: Ord> {
 
 impl<BlockNumber, Balance, SlashId> Stake<BlockNumber, Balance, SlashId>
 where
-    BlockNumber: Copy + SimpleArithmetic + Zero,
-    Balance: Copy + SimpleArithmetic,
+    BlockNumber: Copy + BaseArithmetic + Zero,
+    Balance: Copy + BaseArithmetic,
     SlashId: Copy + Ord + Zero + One,
 {
     fn new(created_at: BlockNumber) -> Self {
@@ -638,7 +636,7 @@ where
 
                 (did_update, slashed)
             }
-            _ => (false, vec![]),
+            _ => (false, Vec::new()),
         }
     }
 
@@ -711,11 +709,12 @@ pub struct SlashImmediateOutcome<Balance, NegativeImbalance> {
 decl_storage! {
     trait Store for Module<T: Trait> as StakePool {
         /// Maps identifiers to a stake.
-        pub Stakes get(stakes): linked_map T::StakeId => Stake<T::BlockNumber, BalanceOf<T>, T::SlashId>;
+        pub Stakes get(fn stakes): map hasher(blake2_128_concat)
+            T::StakeId => Stake<T::BlockNumber, BalanceOf<T>, T::SlashId>;
 
         /// Identifier value for next stake, and count of total stakes created (not necessarily the number of current
         /// stakes in the Stakes map as stakes can be removed.)
-        pub StakesCreated get(stakes_created): T::StakeId;
+        pub StakesCreated get(fn stakes_created): T::StakeId;
     }
 }
 
@@ -900,14 +899,11 @@ impl<T: Trait> Module<T> {
         source_account_id: &T::AccountId,
         value: BalanceOf<T>,
     ) -> Result<BalanceOf<T>, StakeActionError<IncreasingStakeFromAccountError>> {
-        // Compiler error when using macro: cannot infer type for `ErrorType`
-        // let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
-        ensure!(
-            <Stakes<T>>::exists(stake_id),
-            StakeActionError::StakeNotFound
-        );
-
-        let mut stake = Self::stakes(stake_id);
+        let mut stake = ensure_stake_exists!(
+            T,
+            stake_id,
+            <StakeActionError<IncreasingStakeFromAccountError>>::StakeNotFound
+        )?;
 
         let total_staked_amount = stake.increase_stake(value)?;
 
@@ -1141,7 +1137,7 @@ impl<T: Trait> Module<T> {
     /// Finalised slashing results in the staked_balance in the given stake being correspondingly reduced, and the imbalance
     /// is provided to the slashed() hook in the StakingEventsHandler.
     fn finalize_slashing_and_unstaking() {
-        for (stake_id, ref mut stake) in <Stakes<T>>::enumerate() {
+        for (stake_id, ref mut stake) in <Stakes<T>>::iter() {
             let (updated, slashed, unstaked) =
                 stake.finalize_slashing_and_unstaking(T::Currency::minimum_balance());
 

+ 1 - 1
runtime-modules/stake/src/macroes.rs

@@ -1,7 +1,7 @@
 #[macro_export]
 macro_rules! ensure_map_has_mapping_with_key {
     ($map_variable_name:ident , $runtime_trait:tt, $key:expr, $error:expr) => {{
-        if <$map_variable_name<$runtime_trait>>::exists($key) {
+        if <$map_variable_name<$runtime_trait>>::contains_key($key) {
             let value = <$map_variable_name<$runtime_trait>>::get($key);
 
             Ok(value)

+ 16 - 35
runtime-modules/stake/src/mock.rs

@@ -1,17 +1,15 @@
 #![cfg(test)]
 
 use crate::*;
-
-use primitives::H256;
-
 use crate::{Module, Trait};
 use balances;
-use runtime_primitives::{
+use frame_support::{impl_outer_origin, parameter_types};
+use sp_core::H256;
+use sp_runtime::{
     testing::Header,
     traits::{BlakeTwo256, IdentityLookup},
     Perbill,
 };
-use srml_support::{impl_outer_origin, parameter_types};
 
 impl_outer_origin! {
     pub enum Origin for Test {}
@@ -29,10 +27,11 @@ parameter_types! {
 }
 
 impl system::Trait for Test {
+    type BaseCallFilter = ();
     type Origin = Origin;
+    type Call = ();
     type Index = u64;
     type BlockNumber = u64;
-    type Call = ();
     type Hash = H256;
     type Hashing = BlakeTwo256;
     type AccountId = u64;
@@ -41,35 +40,30 @@ impl system::Trait for Test {
     type Event = ();
     type BlockHashCount = BlockHashCount;
     type MaximumBlockWeight = MaximumBlockWeight;
+    type DbWeight = ();
+    type BlockExecutionWeight = ();
+    type ExtrinsicBaseWeight = ();
+    type MaximumExtrinsicWeight = ();
     type MaximumBlockLength = MaximumBlockLength;
     type AvailableBlockRatio = AvailableBlockRatio;
     type Version = ();
+    type ModuleToIndex = ();
+    type AccountData = balances::AccountData<u64>;
+    type OnNewAccount = ();
+    type OnKilledAccount = ();
 }
 
 parameter_types! {
     pub const ExistentialDeposit: u32 = 500;
-    pub const TransferFee: u32 = 5;
-    pub const CreationFee: u32 = 5;
-    pub const TransactionBaseFee: u32 = 5;
-    pub const TransactionByteFee: u32 = 0;
     pub const StakePoolId: [u8; 8] = *b"joystake";
 }
 
 impl balances::Trait for Test {
-    /// The type for recording an account's balance.
     type Balance = u64;
-    /// What to do if an account's free balance gets zeroed.
-    type OnFreeBalanceZero = ();
-    /// What to do if a new account is created.
-    type OnNewAccount = ();
-    /// The ubiquitous event type.
-    type Event = ();
-
     type DustRemoval = ();
-    type TransferPayment = ();
+    type Event = ();
     type ExistentialDeposit = ExistentialDeposit;
-    type TransferFee = TransferFee;
-    type CreationFee = CreationFee;
+    type AccountStore = System;
 }
 
 impl Trait for Test {
@@ -80,7 +74,7 @@ impl Trait for Test {
     type SlashId = u64;
 }
 
-pub fn build_test_externalities() -> runtime_io::TestExternalities {
+pub fn build_test_externalities() -> sp_io::TestExternalities {
     let t = system::GenesisConfig::default()
         .build_storage::<Test>()
         .unwrap();
@@ -99,17 +93,4 @@ pub mod fixtures {
         <Test as Trait>::SlashId,
         Slash<<Test as system::Trait>::BlockNumber, BalanceOf<Test>>,
     >;
-    // pub enum StakeInState {
-    //     NotStaked,
-    //     StakedNormal(BalanceOf<Test>, OngoingSlashes),
-    //     StakedUnstaking(BalanceOf<Test>, OngoingSlashes, <Test as system::Trait>::BlockNumber),
-    // }
-    // fn get_next_slash_id() -> SlashId {
-    // }
-    // pub fn make_stake(state: StakeInState) -> StakeId {
-    //     let id = StakePool::create_stake();
-    //     <Stakes<Test>>::mutate(id, |stake| {});
-    //     id
-    // }
-    // fn stake_in_state_to_stake(StakeInState) -> StakedState {}
 }

+ 5 - 5
runtime-modules/stake/src/tests.rs

@@ -2,8 +2,8 @@
 
 use super::*;
 use crate::mock::*;
-use runtime_primitives::traits::OnFinalize;
-use srml_support::{assert_err, assert_ok};
+use frame_support::traits::OnFinalize;
+use frame_support::{assert_err, assert_ok};
 
 #[test]
 fn stake_pool_works() {
@@ -70,7 +70,7 @@ fn create_stake() {
     build_test_externalities().execute_with(|| {
         let stake_id = StakePool::create_stake();
         assert_eq!(stake_id, 0);
-        assert!(<Stakes<Test>>::exists(&stake_id));
+        assert!(<Stakes<Test>>::contains_key(&stake_id));
 
         assert_eq!(StakePool::stakes_created(), stake_id + 1);
 
@@ -91,7 +91,7 @@ fn remove_stake_in_not_staked_state() {
             },
         );
         assert_ok!(StakePool::remove_stake(&100));
-        assert!(!<Stakes<Test>>::exists(&100));
+        assert!(!<Stakes<Test>>::contains_key(&100));
 
         // when status is Staked, removing should fail
         <Stakes<Test>>::insert(
@@ -106,7 +106,7 @@ fn remove_stake_in_not_staked_state() {
             StakePool::remove_stake(&200),
             StakeActionError::Error(StakingError::AlreadyStaked)
         );
-        assert!(<Stakes<Test>>::exists(&200));
+        assert!(<Stakes<Test>>::contains_key(&200));
     });
 }
 

+ 0 - 1
runtime-modules/token-minting/src/mock.rs

@@ -22,7 +22,6 @@ parameter_types! {
     pub const MaximumBlockWeight: u32 = 1024;
     pub const MaximumBlockLength: u32 = 2 * 1024;
     pub const AvailableBlockRatio: Perbill = Perbill::one();
-    pub const MinimumPeriod: u64 = 5;
 }
 
 impl system::Trait for Test {