Browse Source

runtime: Change staking for proposals.

Shamil Gadelshin 4 years ago
parent
commit
12543b34fe

+ 0 - 1
Cargo.lock

@@ -3579,7 +3579,6 @@ version = "3.0.0"
 dependencies = [
  "frame-support",
  "frame-system",
- "mockall",
  "pallet-balances",
  "pallet-common",
  "pallet-membership",

+ 15 - 14
runtime-modules/proposals/codex/src/lib.rs

@@ -73,6 +73,7 @@ use system::ensure_root;
 use common::origin::ActorOriginValidator;
 use common::working_group::WorkingGroup;
 use governance::election_params::ElectionParameters;
+use proposals_engine::BalanceOfCurrency;
 use proposals_engine::{ProposalCreationParameters, ProposalObserver, ProposalParameters};
 
 pub use crate::proposal_types::{
@@ -94,9 +95,9 @@ struct CreateProposalParameters<T: Trait> {
     pub member_id: MemberId<T>,
     pub title: Vec<u8>,
     pub description: Vec<u8>,
-    pub stake_balance: Option<BalanceOf<T>>,
+    pub stake_balance: Option<BalanceOfCurrency<T>>,
     pub proposal_code: Vec<u8>,
-    pub proposal_parameters: ProposalParameters<T::BlockNumber, BalanceOf<T>>,
+    pub proposal_parameters: ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>>,
     pub proposal_details: ProposalDetailsOf<T>,
     pub exact_execution_block: Option<T::BlockNumber>,
 }
@@ -334,7 +335,7 @@ decl_module! {
             member_id: MemberId<T>,
             title: Vec<u8>,
             description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
+            stake_balance: Option<BalanceOfCurrency<T>>,
             text: Vec<u8>,
             exact_execution_block: Option<T::BlockNumber>,
         ) {
@@ -366,7 +367,7 @@ decl_module! {
             member_id: MemberId<T>,
             title: Vec<u8>,
             description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
+            stake_balance: Option<BalanceOfCurrency<T>>,
             wasm: Vec<u8>,
             exact_execution_block: Option<T::BlockNumber>,
         ) {
@@ -398,7 +399,7 @@ decl_module! {
             member_id: MemberId<T>,
             title: Vec<u8>,
             description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
+            stake_balance: Option<BalanceOfCurrency<T>>,
             balance: BalanceOfMint<T>,
             destination: T::AccountId,
             exact_execution_block: Option<T::BlockNumber>,
@@ -433,7 +434,7 @@ decl_module! {
             member_id: MemberId<T>,
             title: Vec<u8>,
             description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
+            stake_balance: Option<BalanceOfCurrency<T>>,
             new_validator_count: u32,
             exact_execution_block: Option<T::BlockNumber>,
         ) {
@@ -471,7 +472,7 @@ decl_module! {
             member_id: MemberId<T>,
             title: Vec<u8>,
             description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
+            stake_balance: Option<BalanceOfCurrency<T>>,
             add_opening_parameters: AddOpeningParameters<T::BlockNumber, BalanceOfGovernanceCurrency<T>>,
             exact_execution_block: Option<T::BlockNumber>,
         ) {
@@ -499,7 +500,7 @@ decl_module! {
             member_id: MemberId<T>,
             title: Vec<u8>,
             description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
+            stake_balance: Option<BalanceOfCurrency<T>>,
             opening_id: working_group::OpeningId<T>,
             working_group: WorkingGroup,
             exact_execution_block: Option<T::BlockNumber>,
@@ -528,7 +529,7 @@ decl_module! {
             member_id: MemberId<T>,
             title: Vec<u8>,
             description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
+            stake_balance: Option<BalanceOfCurrency<T>>,
             fill_opening_parameters: FillOpeningParameters<
                 T::BlockNumber,
                 BalanceOfMint<T>,
@@ -561,7 +562,7 @@ decl_module! {
             member_id: MemberId<T>,
             title: Vec<u8>,
             description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
+            stake_balance: Option<BalanceOfCurrency<T>>,
             mint_balance: BalanceOfMint<T>,
             working_group: WorkingGroup,
             exact_execution_block: Option<T::BlockNumber>,
@@ -595,7 +596,7 @@ decl_module! {
             member_id: MemberId<T>,
             title: Vec<u8>,
             description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
+            stake_balance: Option<BalanceOfCurrency<T>>,
             worker_id: working_group::WorkerId<T>,
             decreasing_stake: BalanceOf<T>,
             working_group: WorkingGroup,
@@ -632,7 +633,7 @@ decl_module! {
             member_id: MemberId<T>,
             title: Vec<u8>,
             description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
+            stake_balance: Option<BalanceOfCurrency<T>>,
             worker_id: working_group::WorkerId<T>,
             slashing_stake: BalanceOf<T>,
             working_group: WorkingGroup,
@@ -669,7 +670,7 @@ decl_module! {
             member_id: MemberId<T>,
             title: Vec<u8>,
             description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
+            stake_balance: Option<BalanceOfCurrency<T>>,
             worker_id: working_group::WorkerId<T>,
             reward_amount: BalanceOfMint<T>,
             working_group: WorkingGroup,
@@ -704,7 +705,7 @@ decl_module! {
             member_id: MemberId<T>,
             title: Vec<u8>,
             description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
+            stake_balance: Option<BalanceOfCurrency<T>>,
             terminate_role_parameters: TerminateRoleParameters<working_group::WorkerId<T>>,
             exact_execution_block: Option<T::BlockNumber>,
         ) {

+ 26 - 25
runtime-modules/proposals/codex/src/proposal_types/parameters.rs

@@ -1,8 +1,8 @@
-use crate::{BalanceOf, Module, ProposalParameters};
+use crate::{BalanceOfCurrency, Module, ProposalParameters};
 
 // Proposal parameters for the 'Set validator count' proposal
 pub(crate) fn set_validator_count_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
+) -> ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>> {
     ProposalParameters {
         voting_period: <Module<T>>::set_validator_count_proposal_voting_period(),
         grace_period: <Module<T>>::set_validator_count_proposal_grace_period(),
@@ -10,13 +10,13 @@ pub(crate) fn set_validator_count_proposal<T: crate::Trait>(
         approval_threshold_percentage: 80,
         slashing_quorum_percentage: 60,
         slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(100_000_u32)),
+        required_stake: Some(<BalanceOfCurrency<T>>::from(100_000_u32)),
     }
 }
 
 // Proposal parameters for the upgrade runtime proposal
 pub(crate) fn runtime_upgrade_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
+) -> ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>> {
     ProposalParameters {
         voting_period: <Module<T>>::runtime_upgrade_proposal_voting_period(),
         grace_period: <Module<T>>::runtime_upgrade_proposal_grace_period(),
@@ -24,12 +24,13 @@ pub(crate) fn runtime_upgrade_proposal<T: crate::Trait>(
         approval_threshold_percentage: 100,
         slashing_quorum_percentage: 60,
         slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(1_000_000_u32)),
+        required_stake: Some(<BalanceOfCurrency<T>>::from(1_000_000_u32)),
     }
 }
 
 // Proposal parameters for the text proposal
-pub(crate) fn text_proposal<T: crate::Trait>() -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
+pub(crate) fn text_proposal<T: crate::Trait>(
+) -> ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>> {
     ProposalParameters {
         voting_period: <Module<T>>::text_proposal_voting_period(),
         grace_period: <Module<T>>::text_proposal_grace_period(),
@@ -37,13 +38,13 @@ pub(crate) fn text_proposal<T: crate::Trait>() -> ProposalParameters<T::BlockNum
         approval_threshold_percentage: 80,
         slashing_quorum_percentage: 60,
         slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(25000u32)),
+        required_stake: Some(<BalanceOfCurrency<T>>::from(25000u32)),
     }
 }
 
 // Proposal parameters for the 'Spending' proposal
 pub(crate) fn spending_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
+) -> ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>> {
     ProposalParameters {
         voting_period: <Module<T>>::spending_proposal_voting_period(),
         grace_period: <Module<T>>::spending_proposal_grace_period(),
@@ -51,13 +52,13 @@ pub(crate) fn spending_proposal<T: crate::Trait>(
         approval_threshold_percentage: 80,
         slashing_quorum_percentage: 60,
         slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(25000u32)),
+        required_stake: Some(<BalanceOfCurrency<T>>::from(25000u32)),
     }
 }
 
 // Proposal parameters for the 'Add working group leader' proposal
 pub(crate) fn add_working_group_leader_opening_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
+) -> ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>> {
     ProposalParameters {
         voting_period: <Module<T>>::add_working_group_opening_proposal_voting_period(),
         grace_period: <Module<T>>::add_working_group_opening_proposal_grace_period(),
@@ -65,13 +66,13 @@ pub(crate) fn add_working_group_leader_opening_proposal<T: crate::Trait>(
         approval_threshold_percentage: 80,
         slashing_quorum_percentage: 60,
         slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(100_000_u32)),
+        required_stake: Some(<BalanceOfCurrency<T>>::from(100_000_u32)),
     }
 }
 
 // Proposal parameters for the 'Begin review working group leader applications' proposal
 pub(crate) fn begin_review_working_group_leader_applications_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
+) -> ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>> {
     ProposalParameters {
         voting_period:
             <Module<T>>::begin_review_working_group_leader_applications_proposal_voting_period(),
@@ -81,13 +82,13 @@ pub(crate) fn begin_review_working_group_leader_applications_proposal<T: crate::
         approval_threshold_percentage: 75,
         slashing_quorum_percentage: 60,
         slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(25000u32)),
+        required_stake: Some(<BalanceOfCurrency<T>>::from(25000u32)),
     }
 }
 
 // Proposal parameters for the 'Fill working group leader opening' proposal
 pub(crate) fn fill_working_group_leader_opening_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
+) -> ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>> {
     ProposalParameters {
         voting_period: <Module<T>>::fill_working_group_leader_opening_proposal_voting_period(),
         grace_period: <Module<T>>::fill_working_group_leader_opening_proposal_grace_period(),
@@ -95,13 +96,13 @@ pub(crate) fn fill_working_group_leader_opening_proposal<T: crate::Trait>(
         approval_threshold_percentage: 75,
         slashing_quorum_percentage: 60,
         slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(50000u32)),
+        required_stake: Some(<BalanceOfCurrency<T>>::from(50000u32)),
     }
 }
 
 // Proposal parameters for the 'Set working group mint capacity' proposal
 pub(crate) fn set_working_group_mint_capacity_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
+) -> ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>> {
     ProposalParameters {
         voting_period: <Module<T>>::set_working_group_mint_capacity_proposal_voting_period(),
         grace_period: <Module<T>>::set_working_group_mint_capacity_proposal_grace_period(),
@@ -109,13 +110,13 @@ pub(crate) fn set_working_group_mint_capacity_proposal<T: crate::Trait>(
         approval_threshold_percentage: 75,
         slashing_quorum_percentage: 60,
         slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(50000u32)),
+        required_stake: Some(<BalanceOfCurrency<T>>::from(50000u32)),
     }
 }
 
 // Proposal parameters for the 'Decrease working group leader stake' proposal
 pub(crate) fn decrease_working_group_leader_stake_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
+) -> ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>> {
     ProposalParameters {
         voting_period: <Module<T>>::decrease_working_group_leader_stake_proposal_voting_period(),
         grace_period: <Module<T>>::decrease_working_group_leader_stake_proposal_grace_period(),
@@ -123,13 +124,13 @@ pub(crate) fn decrease_working_group_leader_stake_proposal<T: crate::Trait>(
         approval_threshold_percentage: 75,
         slashing_quorum_percentage: 60,
         slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(50000u32)),
+        required_stake: Some(<BalanceOfCurrency<T>>::from(50000u32)),
     }
 }
 
 // Proposal parameters for the 'Slash working group leader stake' proposal
 pub(crate) fn slash_working_group_leader_stake_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
+) -> ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>> {
     ProposalParameters {
         voting_period: <Module<T>>::slash_working_group_leader_stake_proposal_voting_period(),
         grace_period: <Module<T>>::slash_working_group_leader_stake_proposal_grace_period(),
@@ -137,13 +138,13 @@ pub(crate) fn slash_working_group_leader_stake_proposal<T: crate::Trait>(
         approval_threshold_percentage: 75,
         slashing_quorum_percentage: 60,
         slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(50000u32)),
+        required_stake: Some(<BalanceOfCurrency<T>>::from(50000u32)),
     }
 }
 
 // Proposal parameters for the 'Set working group leader reward' proposal
 pub(crate) fn set_working_group_leader_reward_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
+) -> ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>> {
     ProposalParameters {
         voting_period: <Module<T>>::set_working_group_leader_reward_proposal_voting_period(),
         grace_period: <Module<T>>::set_working_group_leader_reward_proposal_grace_period(),
@@ -151,13 +152,13 @@ pub(crate) fn set_working_group_leader_reward_proposal<T: crate::Trait>(
         approval_threshold_percentage: 75,
         slashing_quorum_percentage: 60,
         slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(50000u32)),
+        required_stake: Some(<BalanceOfCurrency<T>>::from(50000u32)),
     }
 }
 
 // Proposal parameters for the 'Terminate working group leader role' proposal
 pub(crate) fn terminate_working_group_leader_role_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
+) -> ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>> {
     ProposalParameters {
         voting_period: <Module<T>>::terminate_working_group_leader_role_proposal_voting_period(),
         grace_period: <Module<T>>::terminate_working_group_leader_role_proposal_grace_period(),
@@ -165,6 +166,6 @@ pub(crate) fn terminate_working_group_leader_role_proposal<T: crate::Trait>(
         approval_threshold_percentage: 80,
         slashing_quorum_percentage: 60,
         slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(100_000_u32)),
+        required_stake: Some(<BalanceOfCurrency<T>>::from(100_000_u32)),
     }
 }

+ 0 - 1
runtime-modules/proposals/engine/Cargo.toml

@@ -18,7 +18,6 @@ stake = { package = 'pallet-stake', default-features = false, path = '../../stak
 common = { package = 'pallet-common', default-features = false, path = '../../common'}
 
 [dev-dependencies]
-mockall = "0.7.1"
 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'}
 balances = { package = 'pallet-balances', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}

+ 43 - 107
runtime-modules/proposals/engine/src/lib.rs

@@ -115,13 +115,13 @@
 // Do not delete! Cannot be uncommented by default, because of Parity decl_module! issue.
 //#![warn(missing_docs)]
 
-use types::{ApprovedProposalData, FinalizedProposalData, ProposalStakeManager};
+use types::{ApprovedProposalData, FinalizedProposalData, MemberId};
 
 pub use types::{
-    ActiveStake, ApprovedProposalStatus, BalanceOf, CurrencyOf, DefaultStakeHandlerProvider,
+    ActiveStake, ApprovedProposalStatus, BalanceOf, BalanceOfCurrency, CurrencyOf,
     FinalizationData, NegativeImbalance, Proposal, ProposalCodeDecoder, ProposalCreationParameters,
-    ProposalDecisionStatus, ProposalExecutable, ProposalParameters, ProposalStatus, StakeHandler,
-    StakeHandlerProvider, VoteKind, VotersParameters, VotingResults,
+    ProposalDecisionStatus, ProposalExecutable, ProposalParameters, ProposalStatus, StakingHandler,
+    VoteKind, VotersParameters, VotingResults,
 };
 
 pub(crate) mod types;
@@ -132,7 +132,7 @@ mod tests;
 use codec::Decode;
 use frame_support::dispatch::{DispatchError, DispatchResult, UnfilteredDispatchable};
 use frame_support::storage::IterableStorageMap;
-use frame_support::traits::{Currency, Get};
+use frame_support::traits::Get;
 use frame_support::{
     decl_error, decl_event, decl_module, decl_storage, ensure, print, Parameter, StorageDoubleMap,
 };
@@ -142,8 +142,6 @@ use system::{ensure_root, RawOrigin};
 
 use common::origin::ActorOriginValidator;
 
-type MemberId<T> = <T as membership::Trait>::MemberId;
-
 /// Proposals engine trait.
 pub trait Trait:
     system::Trait + pallet_timestamp::Trait + stake::Trait + membership::Trait
@@ -167,14 +165,14 @@ pub trait Trait:
     /// Proposal Id type
     type ProposalId: From<u32> + Parameter + Default + Copy;
 
-    /// Provides stake logic implementation. Can be used to mock stake logic.
-    type StakeHandlerProvider: StakeHandlerProvider<Self>;
+    /// Provides stake logic implementation.
+    type StakingHandler: StakingHandler<Self>;
 
     /// The fee is applied when cancel the proposal. A fee would be slashed (burned).
-    type CancellationFee: Get<BalanceOf<Self>>;
+    type CancellationFee: Get<BalanceOfCurrency<Self>>;
 
     /// The fee is applied when the proposal gets rejected. A fee would be slashed (burned).
-    type RejectionFee: Get<BalanceOf<Self>>;
+    type RejectionFee: Get<BalanceOfCurrency<Self>>;
 
     /// Defines max allowed proposal title length.
     type TitleMaxLength: Get<u32>;
@@ -214,7 +212,6 @@ decl_event!(
         MemberId = MemberId<T>,
         <T as system::Trait>::BlockNumber,
         <T as system::Trait>::AccountId,
-        <T as stake::Trait>::StakeId,
     {
         /// Emits on proposal creation.
         /// Params:
@@ -226,7 +223,7 @@ decl_event!(
         /// Params:
         /// - Id of a updated proposal.
         /// - New proposal status
-        ProposalStatusUpdated(ProposalId, ProposalStatus<BlockNumber, StakeId, AccountId>),
+        ProposalStatusUpdated(ProposalId, ProposalStatus<BlockNumber, AccountId>),
 
         /// Emits on voting for the proposal
         /// Params:
@@ -324,10 +321,6 @@ decl_storage! {
         /// Double map for preventing duplicate votes. Should be cleaned after usage.
         pub VoteExistsByProposalByVoter get(fn vote_by_proposal_by_voter):
             double_map hasher(blake2_128_concat)  T::ProposalId, hasher(blake2_128_concat) MemberId<T> => VoteKind;
-
-        /// Map proposal id by stake id. Required by StakingEventsHandler callback call
-        pub StakesProposals get(fn stakes_proposals): map hasher(blake2_128_concat)
-            T::StakeId =>  T::ProposalId;
     }
 }
 
@@ -341,10 +334,10 @@ decl_module! {
         fn deposit_event() = default;
 
         /// Exports const - the fee is applied when cancel the proposal. A fee would be slashed (burned).
-        const CancellationFee: BalanceOf<T> = T::CancellationFee::get();
+        const CancellationFee: BalanceOfCurrency<T> = T::CancellationFee::get();
 
         /// Exports const -  the fee is applied when the proposal gets rejected. A fee would be slashed (burned).
-        const RejectionFee: BalanceOf<T> = T::RejectionFee::get();
+        const RejectionFee: BalanceOfCurrency<T> = T::RejectionFee::get();
 
         /// Exports const -  max allowed proposal title length.
         const TitleMaxLength: u32 = T::TitleMaxLength::get();
@@ -452,7 +445,7 @@ impl<T: Trait> Module<T> {
     pub fn create_proposal(
         creation_params: ProposalCreationParameters<
             T::BlockNumber,
-            types::BalanceOf<T>,
+            BalanceOfCurrency<T>,
             MemberId<T>,
             T::AccountId,
         >,
@@ -472,27 +465,15 @@ impl<T: Trait> Module<T> {
         let new_proposal_id = next_proposal_count_value;
         let proposal_id = T::ProposalId::from(new_proposal_id);
 
-        // Check stake_balance for value and create stake if value exists, else take None
-        // If create_stake() returns error - return error from extrinsic
-        let stake_id_result = creation_params
-            .stake_balance
-            .map(|stake_amount| {
-                ProposalStakeManager::<T>::create_stake(
-                    stake_amount,
-                    creation_params.account_id.clone(),
-                )
-            })
-            .transpose()?;
+        let stake_data = if let Some(stake_balance) = creation_params.stake_balance {
+            T::StakingHandler::lock(&creation_params.account_id, stake_balance);
 
-        let mut stake_data = None;
-        if let Some(stake_id) = stake_id_result {
-            stake_data = Some(ActiveStake {
-                stake_id,
+            Some(ActiveStake {
                 source_account_id: creation_params.account_id,
-            });
-
-            <StakesProposals<T>>::insert(stake_id, proposal_id);
-        }
+            })
+        } else {
+            None
+        };
 
         let new_proposal = Proposal {
             created_at: Self::current_block(),
@@ -528,10 +509,10 @@ impl<T: Trait> Module<T> {
     /// - provided parameters: approval_threshold_percentage and slashing_threshold_percentage > 0
     /// - provided stake balance and parameters.required_stake are valid
     pub fn ensure_create_proposal_parameters_are_valid(
-        parameters: &ProposalParameters<T::BlockNumber, types::BalanceOf<T>>,
+        parameters: &ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>>,
         title: &[u8],
         description: &[u8],
-        stake_balance: Option<types::BalanceOf<T>>,
+        stake_balance: Option<BalanceOfCurrency<T>>,
         exact_execution_block: Option<T::BlockNumber>,
     ) -> DispatchResult {
         ensure!(!title.is_empty(), Error::<T>::EmptyTitleProvided);
@@ -594,38 +575,6 @@ impl<T: Trait> Module<T> {
         Ok(())
     }
 
-    /// Callback from StakingEventsHandler. Refunds unstaked imbalance back to the source account.
-    /// There can be a lot of invariant breaks in the scope of this proposal.
-    /// Such situations are handled by adding error messages to the log.
-    pub fn refund_proposal_stake(stake_id: T::StakeId, imbalance: NegativeImbalance<T>) {
-        if <StakesProposals<T>>::contains_key(stake_id) {
-            let proposal_id = Self::stakes_proposals(stake_id);
-
-            if <Proposals<T>>::contains_key(proposal_id) {
-                let proposal = Self::proposals(proposal_id);
-
-                if let ProposalStatus::Active(active_stake_result) = proposal.status {
-                    if let Some(active_stake) = active_stake_result {
-                        let refunding_result = CurrencyOf::<T>::resolve_into_existing(
-                            &active_stake.source_account_id,
-                            imbalance,
-                        );
-
-                        if refunding_result.is_err() {
-                            print("Broken invariant: cannot refund");
-                        }
-                    }
-                } else {
-                    print("Broken invariant: proposal status is not Active");
-                }
-            } else {
-                print("Broken invariant: proposal doesn't exist");
-            }
-        } else {
-            print("Broken invariant: stake doesn't exist");
-        }
-    }
-
     /// Resets voting results for active proposals.
     /// Possible application includes new council elections.
     pub fn reset_active_proposals() {
@@ -677,12 +626,8 @@ impl<T: Trait> Module<T> {
     fn veto_pending_execution_proposal(proposal_id: T::ProposalId, proposal: ProposalOf<T>) {
         <PendingExecutionProposalIds<T>>::remove(proposal_id);
 
-        let vetoed_proposal_status = ProposalStatus::finalized(
-            ProposalDecisionStatus::Vetoed,
-            None,
-            None,
-            Self::current_block(),
-        );
+        let vetoed_proposal_status =
+            ProposalStatus::finalized(ProposalDecisionStatus::Vetoed, Self::current_block());
 
         <Proposals<T>>::insert(
             proposal_id,
@@ -714,9 +659,10 @@ impl<T: Trait> Module<T> {
             Err(error) => ApprovedProposalStatus::failed_execution(error.what()),
         };
 
-        let proposal_execution_status = approved_proposal
-            .finalisation_status_data
-            .create_approved_proposal_status(approved_proposal_status);
+        let proposal_execution_status = ProposalStatus::Finalized(FinalizationData {
+            proposal_status: ProposalDecisionStatus::Approved(approved_proposal_status),
+            finalized_at: approved_proposal.finalisation_status_data.finalized_at,
+        });
 
         Self::deposit_event(RawEvent::ProposalStatusUpdated(
             approved_proposal.proposal_id,
@@ -751,16 +697,11 @@ impl<T: Trait> Module<T> {
             // deal with stakes if necessary
             let slash_balance =
                 Self::calculate_slash_balance(&decision_status, &proposal.parameters);
-            let slash_and_unstake_result =
-                Self::slash_and_unstake(active_stake.clone(), slash_balance);
+            Self::slash_and_unstake(active_stake, slash_balance);
 
             // create finalized proposal status with error if any
-            let new_proposal_status = ProposalStatus::finalized(
-                decision_status,
-                slash_and_unstake_result.err(),
-                active_stake,
-                Self::current_block(),
-            );
+            let new_proposal_status =
+                ProposalStatus::finalized(decision_status, Self::current_block());
 
             if clean_finilized_proposal {
                 Self::remove_proposal_data(&proposal_id);
@@ -780,39 +721,37 @@ impl<T: Trait> Module<T> {
 
     // Slashes the stake and perform unstake only in case of existing stake
     fn slash_and_unstake(
-        current_stake_data: Option<ActiveStake<T::StakeId, T::AccountId>>,
-        slash_balance: BalanceOf<T>,
-    ) -> Result<(), &'static str> {
+        current_stake_data: Option<ActiveStake<T::AccountId>>,
+        slash_balance: BalanceOfCurrency<T>,
+    ) {
         // only if stake exists
         if let Some(stake_data) = current_stake_data {
             if !slash_balance.is_zero() {
-                ProposalStakeManager::<T>::slash(stake_data.stake_id, slash_balance)?;
+                T::StakingHandler::slash(&stake_data.source_account_id, Some(slash_balance));
             }
 
-            ProposalStakeManager::<T>::remove_stake(stake_data.stake_id)?;
+            T::StakingHandler::unlock(&stake_data.source_account_id);
         }
-
-        Ok(())
     }
 
     // Calculates required slash based on finalization ProposalDecisionStatus and proposal parameters.
     // Method visibility allows testing.
     pub(crate) fn calculate_slash_balance(
         decision_status: &ProposalDecisionStatus,
-        proposal_parameters: &ProposalParameters<T::BlockNumber, types::BalanceOf<T>>,
-    ) -> types::BalanceOf<T> {
+        proposal_parameters: &ProposalParameters<T::BlockNumber, BalanceOfCurrency<T>>,
+    ) -> BalanceOfCurrency<T> {
         match decision_status {
             ProposalDecisionStatus::Rejected | ProposalDecisionStatus::Expired => {
                 T::RejectionFee::get()
             }
             ProposalDecisionStatus::Approved { .. } | ProposalDecisionStatus::Vetoed => {
-                BalanceOf::<T>::zero()
+                BalanceOfCurrency::<T>::zero()
             }
             ProposalDecisionStatus::Canceled => T::CancellationFee::get(),
             ProposalDecisionStatus::Slashed => proposal_parameters
                 .required_stake
                 .clone()
-                .unwrap_or_else(BalanceOf::<T>::zero), // stake if set or zero
+                .unwrap_or_else(BalanceOfCurrency::<T>::zero), // stake if set or zero
         }
     }
 
@@ -888,8 +827,7 @@ type FinalizedProposal<T> = FinalizedProposalData<
     <T as Trait>::ProposalId,
     <T as system::Trait>::BlockNumber,
     MemberId<T>,
-    types::BalanceOf<T>,
-    <T as stake::Trait>::StakeId,
+    BalanceOfCurrency<T>,
     <T as system::Trait>::AccountId,
 >;
 
@@ -898,8 +836,7 @@ type ApprovedProposal<T> = ApprovedProposalData<
     <T as Trait>::ProposalId,
     <T as system::Trait>::BlockNumber,
     MemberId<T>,
-    types::BalanceOf<T>,
-    <T as stake::Trait>::StakeId,
+    BalanceOfCurrency<T>,
     <T as system::Trait>::AccountId,
 >;
 
@@ -907,7 +844,6 @@ type ApprovedProposal<T> = ApprovedProposalData<
 type ProposalOf<T> = Proposal<
     <T as system::Trait>::BlockNumber,
     MemberId<T>,
-    types::BalanceOf<T>,
-    <T as stake::Trait>::StakeId,
+    BalanceOfCurrency<T>,
     <T as system::Trait>::AccountId,
 >;

+ 66 - 42
runtime-modules/proposals/engine/src/types/mod.rs

@@ -15,19 +15,11 @@ use sp_std::ops::Add;
 use sp_std::vec::Vec;
 
 mod proposal_statuses;
-mod stakes;
 
+use common::currency::GovernanceCurrency;
 pub use proposal_statuses::{
     ApprovedProposalStatus, FinalizationData, ProposalDecisionStatus, ProposalStatus,
 };
-pub(crate) use stakes::ProposalStakeManager;
-pub use stakes::{DefaultStakeHandlerProvider, StakeHandler, StakeHandlerProvider};
-
-#[cfg(test)]
-pub(crate) use stakes::DefaultStakeHandler;
-
-#[cfg(test)]
-pub(crate) use stakes::MockStakeHandler;
 
 /// Vote kind for the proposal. Sum of all votes defines proposal status.
 #[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
@@ -122,10 +114,7 @@ impl VotingResults {
 /// Contains created stake id and source account for the stake balance
 #[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
 #[derive(Encode, Decode, Default, Clone, Copy, PartialEq, Eq, Debug)]
-pub struct ActiveStake<StakeId, AccountId> {
-    /// Created stake id for the proposal
-    pub stake_id: StakeId,
-
+pub struct ActiveStake<AccountId> {
     /// Source account of the stake balance. Refund if any will be provided using this account
     pub source_account_id: AccountId,
 }
@@ -133,7 +122,7 @@ pub struct ActiveStake<StakeId, AccountId> {
 /// 'Proposal' contains information necessary for the proposal system functioning.
 #[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
 #[derive(Encode, Decode, Default, Clone, PartialEq, Eq, Debug)]
-pub struct Proposal<BlockNumber, ProposerId, Balance, StakeId, AccountId> {
+pub struct Proposal<BlockNumber, ProposerId, Balance, AccountId> {
     /// Proposals parameter, characterize different proposal types.
     pub parameters: ProposalParameters<BlockNumber, Balance>,
 
@@ -150,7 +139,7 @@ pub struct Proposal<BlockNumber, ProposerId, Balance, StakeId, AccountId> {
     pub created_at: BlockNumber,
 
     /// Current proposal status
-    pub status: ProposalStatus<BlockNumber, StakeId, AccountId>,
+    pub status: ProposalStatus<BlockNumber, AccountId>,
 
     /// Curring voting result for the proposal
     pub voting_results: VotingResults,
@@ -159,11 +148,10 @@ pub struct Proposal<BlockNumber, ProposerId, Balance, StakeId, AccountId> {
     pub exact_execution_block: Option<BlockNumber>,
 }
 
-impl<BlockNumber, ProposerId, Balance, StakeId, AccountId>
-    Proposal<BlockNumber, ProposerId, Balance, StakeId, AccountId>
+impl<BlockNumber, ProposerId, Balance, AccountId>
+    Proposal<BlockNumber, ProposerId, Balance, AccountId>
 where
     BlockNumber: Add<Output = BlockNumber> + PartialOrd + Copy,
-    StakeId: Clone,
     AccountId: Clone,
 {
     /// Returns whether voting period expired by now
@@ -253,8 +241,8 @@ pub trait VotersParameters {
 }
 
 // Calculates quorum, votes threshold, expiration status
-struct ProposalStatusResolution<'a, BlockNumber, ProposerId, Balance, StakeId, AccountId> {
-    proposal: &'a Proposal<BlockNumber, ProposerId, Balance, StakeId, AccountId>,
+struct ProposalStatusResolution<'a, BlockNumber, ProposerId, Balance, AccountId> {
+    proposal: &'a Proposal<BlockNumber, ProposerId, Balance, AccountId>,
     now: BlockNumber,
     votes_count: u32,
     total_voters_count: u32,
@@ -262,11 +250,10 @@ struct ProposalStatusResolution<'a, BlockNumber, ProposerId, Balance, StakeId, A
     slashes: u32,
 }
 
-impl<'a, BlockNumber, ProposerId, Balance, StakeId, AccountId>
-    ProposalStatusResolution<'a, BlockNumber, ProposerId, Balance, StakeId, AccountId>
+impl<'a, BlockNumber, ProposerId, Balance, AccountId>
+    ProposalStatusResolution<'a, BlockNumber, ProposerId, Balance, AccountId>
 where
     BlockNumber: Add<Output = BlockNumber> + PartialOrd + Copy,
-    StakeId: Clone,
     AccountId: Clone,
 {
     // Proposal has been expired and quorum not reached.
@@ -351,19 +338,12 @@ pub type NegativeImbalance<T> =
 pub type CurrencyOf<T> = <T as stake::Trait>::Currency;
 
 /// Data container for the finalized proposal results
-pub(crate) struct FinalizedProposalData<
-    ProposalId,
-    BlockNumber,
-    ProposerId,
-    Balance,
-    StakeId,
-    AccountId,
-> {
+pub(crate) struct FinalizedProposalData<ProposalId, BlockNumber, ProposerId, Balance, AccountId> {
     /// Proposal id
     pub proposal_id: ProposalId,
 
     /// Proposal to be finalized
-    pub proposal: Proposal<BlockNumber, ProposerId, Balance, StakeId, AccountId>,
+    pub proposal: Proposal<BlockNumber, ProposerId, Balance, AccountId>,
 
     /// Proposal finalization status
     pub status: ProposalDecisionStatus,
@@ -373,22 +353,15 @@ pub(crate) struct FinalizedProposalData<
 }
 
 /// Data container for the approved proposal results
-pub(crate) struct ApprovedProposalData<
-    ProposalId,
-    BlockNumber,
-    ProposerId,
-    Balance,
-    StakeId,
-    AccountId,
-> {
+pub(crate) struct ApprovedProposalData<ProposalId, BlockNumber, ProposerId, Balance, AccountId> {
     /// Proposal id.
     pub proposal_id: ProposalId,
 
     /// Proposal to be finalized.
-    pub proposal: Proposal<BlockNumber, ProposerId, Balance, StakeId, AccountId>,
+    pub proposal: Proposal<BlockNumber, ProposerId, Balance, AccountId>,
 
     /// Proposal finalisation status data.
-    pub finalisation_status_data: FinalizationData<BlockNumber, StakeId, AccountId>,
+    pub finalisation_status_data: FinalizationData<BlockNumber>,
 }
 
 /// Containter-type for a proposal creation method.
@@ -419,6 +392,57 @@ pub struct ProposalCreationParameters<BlockNumber, Balance, MemberId, AccountId>
     pub exact_execution_block: Option<BlockNumber>,
 }
 
+// Type alias for member id.
+pub(crate) type MemberId<T> = <T as membership::Trait>::MemberId;
+
+/// Balance alias for GovernanceCurrency from `common` module. TODO: replace with BalanceOf
+pub type BalanceOfCurrency<T> =
+    <<T as common::currency::GovernanceCurrency>::Currency as Currency<
+        <T as system::Trait>::AccountId,
+    >>::Balance;
+
+/// Defines abstract staking handler to manage user stakes for different activities
+/// like adding a proposal. Implementation should use built-in LockableCurrency
+/// and LockIdentifier to lock balance consistently with pallet_staking.
+pub trait StakingHandler<T: system::Trait + membership::Trait + GovernanceCurrency> {
+    /// Locks the specified balance on the account using specific lock identifier.
+    fn lock(account_id: &T::AccountId, amount: BalanceOfCurrency<T>);
+
+    /// Removes the specified lock on the account.
+    fn unlock(account_id: &T::AccountId);
+
+    /// Slash the specified balance on the account using specific lock identifier.
+    /// No limits, no actions on zero stake.
+    /// If slashing balance greater than the existing stake - stake is slashed to zero.
+    /// Returns actually slashed balance.
+    fn slash(
+        account_id: &T::AccountId,
+        amount: Option<BalanceOfCurrency<T>>,
+    ) -> BalanceOfCurrency<T>;
+
+    /// Decreases the stake for to a given amount.
+    fn decrease_stake(account_id: &T::AccountId, new_stake: BalanceOfCurrency<T>);
+
+    /// Increases the stake for to a given amount.
+    fn increase_stake(account_id: &T::AccountId, new_stake: BalanceOfCurrency<T>)
+        -> DispatchResult;
+
+    /// Verifies that staking account bound to the member.
+    fn is_member_staking_account(member_id: &MemberId<T>, account_id: &T::AccountId) -> bool;
+
+    /// Verifies that there no conflicting stakes on the staking account.
+    fn is_account_free_of_conflicting_stakes(account_id: &T::AccountId) -> bool;
+
+    /// Verifies that staking account balance is sufficient for staking.
+    /// During the balance check we should consider already locked stake. Effective balance to check
+    /// is 'already locked funds' + 'usable funds'.
+    fn is_enough_balance_for_stake(account_id: &T::AccountId, amount: BalanceOfCurrency<T>)
+        -> bool;
+
+    /// Returns the current stake on the account.
+    fn current_stake(account_id: &T::AccountId) -> BalanceOfCurrency<T>;
+}
+
 #[cfg(test)]
 mod tests {
     use crate::types::ProposalStatusResolution;

+ 9 - 50
runtime-modules/proposals/engine/src/types/proposal_statuses.rs

@@ -10,48 +10,29 @@ use crate::ActiveStake;
 /// Current status of the proposal
 #[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
 #[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
-pub enum ProposalStatus<BlockNumber, StakeId, AccountId> {
+pub enum ProposalStatus<BlockNumber, AccountId> {
     /// A new proposal status that is available for voting (with optional stake data).
-    Active(Option<ActiveStake<StakeId, AccountId>>),
+    Active(Option<ActiveStake<AccountId>>),
 
     /// The proposal decision was made.
-    Finalized(FinalizationData<BlockNumber, StakeId, AccountId>),
+    Finalized(FinalizationData<BlockNumber>),
 }
 
-impl<BlockNumber, StakeId, AccountId> Default for ProposalStatus<BlockNumber, StakeId, AccountId> {
+impl<BlockNumber, AccountId> Default for ProposalStatus<BlockNumber, AccountId> {
     fn default() -> Self {
         ProposalStatus::Active(None)
     }
 }
 
-impl<BlockNumber, StakeId, AccountId> ProposalStatus<BlockNumber, StakeId, AccountId> {
-    /// Creates finalized proposal status with provided ProposalDecisionStatus
-    pub fn finalized_successfully(
-        decision_status: ProposalDecisionStatus,
-        now: BlockNumber,
-    ) -> ProposalStatus<BlockNumber, StakeId, AccountId> {
-        Self::finalized(decision_status, None, None, now)
-    }
-
-    /// Creates finalized proposal status with provided ProposalDecisionStatus and error
+impl<BlockNumber, AccountId> ProposalStatus<BlockNumber, AccountId> {
+    /// Creates finalized proposal status with provided ProposalDecisionStatus.
     pub fn finalized(
         decision_status: ProposalDecisionStatus,
-        encoded_unstaking_error_due_to_broken_runtime: Option<&str>,
-        active_stake: Option<ActiveStake<StakeId, AccountId>>,
         now: BlockNumber,
-    ) -> ProposalStatus<BlockNumber, StakeId, AccountId> {
-        // drop the stake information if there were no errors on unstaking
-        let actual_stake = if encoded_unstaking_error_due_to_broken_runtime.is_some() {
-            active_stake
-        } else {
-            None
-        };
+    ) -> ProposalStatus<BlockNumber, AccountId> {
         ProposalStatus::Finalized(FinalizationData {
             proposal_status: decision_status,
-            encoded_unstaking_error_due_to_broken_runtime:
-                encoded_unstaking_error_due_to_broken_runtime.map(|err| err.as_bytes().to_vec()),
             finalized_at: now,
-            stake_data_after_unstaking_error: actual_stake,
         })
     }
 
@@ -59,12 +40,10 @@ impl<BlockNumber, StakeId, AccountId> ProposalStatus<BlockNumber, StakeId, Accou
     pub fn approved(
         approved_status: ApprovedProposalStatus,
         now: BlockNumber,
-    ) -> ProposalStatus<BlockNumber, StakeId, AccountId> {
+    ) -> ProposalStatus<BlockNumber, AccountId> {
         ProposalStatus::Finalized(FinalizationData {
             proposal_status: ProposalDecisionStatus::Approved(approved_status),
-            encoded_unstaking_error_due_to_broken_runtime: None,
             finalized_at: now,
-            stake_data_after_unstaking_error: None,
         })
     }
 }
@@ -72,31 +51,12 @@ impl<BlockNumber, StakeId, AccountId> ProposalStatus<BlockNumber, StakeId, Accou
 /// Final proposal status and potential error.
 #[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
 #[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)]
-pub struct FinalizationData<BlockNumber, StakeId, AccountId> {
+pub struct FinalizationData<BlockNumber> {
     /// Final proposal status
     pub proposal_status: ProposalDecisionStatus,
 
     /// Proposal finalization block number
     pub finalized_at: BlockNumber,
-
-    /// Error occured during the proposal finalization - unstaking failed in the stake module
-    pub encoded_unstaking_error_due_to_broken_runtime: Option<Vec<u8>>,
-
-    /// Stake data for the proposal, filled if the unstaking wasn't successful
-    pub stake_data_after_unstaking_error: Option<ActiveStake<StakeId, AccountId>>,
-}
-
-impl<BlockNumber, StakeId, AccountId> FinalizationData<BlockNumber, StakeId, AccountId> {
-    /// FinalizationData helper, creates ApprovedProposalStatus
-    pub fn create_approved_proposal_status(
-        self,
-        approved_status: ApprovedProposalStatus,
-    ) -> ProposalStatus<BlockNumber, StakeId, AccountId> {
-        ProposalStatus::Finalized(FinalizationData {
-            proposal_status: ProposalDecisionStatus::Approved(approved_status),
-            ..self
-        })
-    }
 }
 
 /// Status of the approved proposal. Defines execution stages.
@@ -173,7 +133,6 @@ mod tests {
         let msg = "error";
         let block_number = 20;
         let stake = ActiveStake {
-            stake_id: 50,
             source_account_id: 2,
         };
 

+ 0 - 248
runtime-modules/proposals/engine/src/types/stakes.rs

@@ -1,248 +0,0 @@
-#![warn(missing_docs)]
-
-use super::{BalanceOf, CurrencyOf, NegativeImbalance};
-use crate::Trait;
-use frame_support::traits::{Currency, ExistenceRequirement, WithdrawReasons};
-use sp_std::convert::From;
-use sp_std::marker::PhantomData;
-use sp_std::rc::Rc;
-
-// Mocking dependencies for testing
-#[cfg(test)]
-use mockall::predicate::*;
-#[cfg(test)]
-use mockall::*;
-
-/// Returns registered stake handler. This is scaffolds for the mocking of the stake module.
-pub trait StakeHandlerProvider<T: Trait> {
-    /// Returns stake logic handler
-    fn stakes() -> Rc<dyn StakeHandler<T>>;
-}
-
-/// Default implementation of the stake module logic provider. Returns actual implementation
-/// dependent on the stake module.
-pub struct DefaultStakeHandlerProvider;
-impl<T: Trait> StakeHandlerProvider<T> for DefaultStakeHandlerProvider {
-    /// Returns stake logic handler
-    fn stakes() -> Rc<dyn StakeHandler<T>> {
-        Rc::new(DefaultStakeHandler {
-            marker: PhantomData::<T>::default(),
-        })
-    }
-}
-
-/// Stake logic handler.
-#[cfg_attr(test, automock)] // attributes creates mocks in testing environment
-pub trait StakeHandler<T: Trait> {
-    /// Creates a stake. Returns created stake id or an error.
-    fn create_stake(&self) -> Result<T::StakeId, &'static str>;
-
-    /// Stake the imbalance
-    fn stake(
-        &self,
-        stake_id: &T::StakeId,
-        stake_imbalance: NegativeImbalance<T>,
-    ) -> Result<(), &'static str>;
-
-    /// Removes stake
-    fn remove_stake(&self, stake_id: T::StakeId) -> Result<(), &'static str>;
-
-    /// Execute unstaking
-    fn unstake(&self, stake_id: T::StakeId) -> Result<(), &'static str>;
-
-    /// Slash balance from the existing stake
-    fn slash(&self, stake_id: T::StakeId, slash_balance: BalanceOf<T>) -> Result<(), &'static str>;
-
-    /// Withdraw some balance from the source account and create stake imbalance
-    fn make_stake_imbalance(
-        &self,
-        balance: BalanceOf<T>,
-        source_account_id: &T::AccountId,
-    ) -> Result<NegativeImbalance<T>, &'static str>;
-}
-
-/// Default implementation of the stake logic. Uses actual stake module.
-/// 'marker' responsible for the 'Trait' binding.
-pub(crate) struct DefaultStakeHandler<T> {
-    pub marker: PhantomData<T>,
-}
-
-impl<T: Trait> StakeHandler<T> for DefaultStakeHandler<T> {
-    /// Creates a stake. Returns created stake id or an error.
-    fn create_stake(&self) -> Result<<T as stake::Trait>::StakeId, &'static str> {
-        Ok(stake::Module::<T>::create_stake())
-    }
-
-    /// Stake the imbalance
-    fn stake(
-        &self,
-        stake_id: &<T as stake::Trait>::StakeId,
-        stake_imbalance: NegativeImbalance<T>,
-    ) -> Result<(), &'static str> {
-        stake::Module::<T>::stake(&stake_id, stake_imbalance).map_err(WrappedError)?;
-
-        Ok(())
-    }
-
-    /// Removes stake
-    fn remove_stake(&self, stake_id: <T as stake::Trait>::StakeId) -> Result<(), &'static str> {
-        stake::Module::<T>::remove_stake(&stake_id).map_err(WrappedError)?;
-
-        Ok(())
-    }
-
-    /// Execute unstaking
-    fn unstake(&self, stake_id: <T as stake::Trait>::StakeId) -> Result<(), &'static str> {
-        stake::Module::<T>::initiate_unstaking(&stake_id, None).map_err(WrappedError)?;
-
-        Ok(())
-    }
-
-    /// Slash balance from the existing stake
-    fn slash(
-        &self,
-        stake_id: <T as stake::Trait>::StakeId,
-        slash_balance: BalanceOf<T>,
-    ) -> Result<(), &'static str> {
-        let _ignored_successful_result =
-            stake::Module::<T>::slash_immediate(&stake_id, slash_balance, false)
-                .map_err(WrappedError)?;
-
-        Ok(())
-    }
-
-    /// Withdraw some balance from the source account and create stake imbalance
-    fn make_stake_imbalance(
-        &self,
-        balance: BalanceOf<T>,
-        source_account_id: &T::AccountId,
-    ) -> Result<NegativeImbalance<T>, &'static str> {
-        CurrencyOf::<T>::withdraw(
-            source_account_id,
-            balance,
-            WithdrawReasons::all(),
-            ExistenceRequirement::AllowDeath,
-        )
-        .map_err(<&str>::from)
-    }
-}
-
-/// Proposal implementation of the stake logic.
-/// 'marker' responsible for the 'Trait' binding.
-pub(crate) struct ProposalStakeManager<T> {
-    pub marker: PhantomData<T>,
-}
-
-impl<T: Trait> ProposalStakeManager<T> {
-    /// Creates a stake using stake balance and source account.
-    /// Returns created stake id or an error.
-    pub fn create_stake(
-        stake_balance: BalanceOf<T>,
-        source_account_id: T::AccountId,
-    ) -> Result<T::StakeId, &'static str> {
-        let stake_id = T::StakeHandlerProvider::stakes().create_stake()?;
-
-        let stake_imbalance = T::StakeHandlerProvider::stakes()
-            .make_stake_imbalance(stake_balance, &source_account_id)?;
-
-        T::StakeHandlerProvider::stakes().stake(&stake_id, stake_imbalance)?;
-
-        Ok(stake_id)
-    }
-
-    /// Execute unstaking and removes the stake
-    pub fn remove_stake(stake_id: T::StakeId) -> Result<(), &'static str> {
-        T::StakeHandlerProvider::stakes().unstake(stake_id)?;
-
-        T::StakeHandlerProvider::stakes().remove_stake(stake_id)?;
-
-        Ok(())
-    }
-
-    /// Slash balance from the existing stake
-    pub fn slash(stake_id: T::StakeId, slash_balance: BalanceOf<T>) -> Result<(), &'static str> {
-        T::StakeHandlerProvider::stakes().slash(stake_id, slash_balance)
-    }
-}
-
-// 'New type' pattern for the error
-// https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#using-the-newtype-pattern-to-implement-external-traits-on-external-types
-struct WrappedError<E>(E);
-
-// error conversion for the Wrapped StakeActionError with the inner InitiateUnstakingError
-impl From<WrappedError<stake::StakeActionError<stake::InitiateUnstakingError>>> for &str {
-    fn from(wrapper: WrappedError<stake::StakeActionError<stake::InitiateUnstakingError>>) -> Self {
-        {
-            match wrapper.0 {
-                stake::StakeActionError::StakeNotFound => "StakeNotFound",
-                stake::StakeActionError::Error(err) => match err {
-                    stake::InitiateUnstakingError::UnstakingPeriodShouldBeGreaterThanZero => {
-                        "UnstakingPeriodShouldBeGreaterThanZero"
-                    }
-                    stake::InitiateUnstakingError::UnstakingError(e) => match e {
-                        stake::UnstakingError::NotStaked => "NotStaked",
-                        stake::UnstakingError::AlreadyUnstaking => "AlreadyUnstaking",
-                        stake::UnstakingError::CannotUnstakeWhileSlashesOngoing => {
-                            "CannotUnstakeWhileSlashesOngoing"
-                        }
-                    },
-                },
-            }
-        }
-    }
-}
-
-// error conversion for the Wrapped StakeActionError with the inner StakingError
-impl From<WrappedError<stake::StakeActionError<stake::StakingError>>> for &str {
-    fn from(wrapper: WrappedError<stake::StakeActionError<stake::StakingError>>) -> Self {
-        {
-            match wrapper.0 {
-                stake::StakeActionError::StakeNotFound => "StakeNotFound",
-                stake::StakeActionError::Error(err) => match err {
-                    stake::StakingError::CannotStakeZero => "CannotStakeZero",
-                    stake::StakingError::CannotStakeLessThanMinimumBalance => {
-                        "CannotStakeLessThanMinimumBalance"
-                    }
-                    stake::StakingError::AlreadyStaked => "AlreadyStaked",
-                },
-            }
-        }
-    }
-}
-
-// error conversion for the Wrapped StakeActionError with the inner InitiateSlashingError
-impl From<WrappedError<stake::StakeActionError<stake::InitiateSlashingError>>> for &str {
-    fn from(wrapper: WrappedError<stake::StakeActionError<stake::InitiateSlashingError>>) -> Self {
-        {
-            match wrapper.0 {
-                stake::StakeActionError::StakeNotFound => "StakeNotFound",
-                stake::StakeActionError::Error(err) => match err {
-                    stake::InitiateSlashingError::NotStaked => "NotStaked",
-                    stake::InitiateSlashingError::SlashPeriodShouldBeGreaterThanZero => {
-                        "SlashPeriodShouldBeGreaterThanZero"
-                    }
-                    stake::InitiateSlashingError::SlashAmountShouldBeGreaterThanZero => {
-                        "SlashAmountShouldBeGreaterThanZero"
-                    }
-                },
-            }
-        }
-    }
-}
-
-// error conversion for the Wrapped StakeActionError with the inner ImmediateSlashingError
-impl From<WrappedError<stake::StakeActionError<stake::ImmediateSlashingError>>> for &str {
-    fn from(wrapper: WrappedError<stake::StakeActionError<stake::ImmediateSlashingError>>) -> Self {
-        {
-            match wrapper.0 {
-                stake::StakeActionError::StakeNotFound => "StakeNotFound",
-                stake::StakeActionError::Error(err) => match err {
-                    stake::ImmediateSlashingError::NotStaked => "NotStaked",
-                    stake::ImmediateSlashingError::SlashAmountShouldBeGreaterThanZero => {
-                        "SlashAmountShouldBeGreaterThanZero"
-                    }
-                },
-            }
-        }
-    }
-}

+ 0 - 2
runtime/src/integration/proposals/mod.rs

@@ -4,10 +4,8 @@ mod council_elected_handler;
 mod council_origin_validator;
 mod membership_origin_validator;
 mod proposal_encoder;
-mod staking_events_handler;
 
 pub use council_elected_handler::CouncilElectedHandler;
 pub use council_origin_validator::CouncilManager;
 pub use membership_origin_validator::{MemberId, MembershipOriginValidator};
 pub use proposal_encoder::ExtrinsicProposalEncoder;
-pub use staking_events_handler::StakingEventsHandler;

+ 0 - 49
runtime/src/integration/proposals/staking_events_handler.rs

@@ -1,49 +0,0 @@
-#![warn(missing_docs)]
-
-use frame_support::traits::{Currency, Imbalance};
-use frame_support::StorageMap;
-use sp_std::marker::PhantomData;
-
-// Balance alias
-type BalanceOf<T> =
-    <<T as stake::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;
-
-// Balance alias for staking
-type NegativeImbalance<T> =
-    <<T as stake::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;
-
-/// Proposal implementation of the staking event handler from the stake module.
-/// 'marker' responsible for the 'Trait' binding.
-pub struct StakingEventsHandler<T> {
-    pub marker: PhantomData<T>,
-}
-
-impl<T: stake::Trait + proposals_engine::Trait> stake::StakingEventsHandler<T>
-    for StakingEventsHandler<T>
-{
-    /// Unstake remaining sum back to the source_account_id
-    fn unstaked(
-        id: &<T as stake::Trait>::StakeId,
-        _unstaked_amount: BalanceOf<T>,
-        remaining_imbalance: NegativeImbalance<T>,
-    ) -> NegativeImbalance<T> {
-        if <proposals_engine::StakesProposals<T>>::contains_key(id) {
-            <proposals_engine::Module<T>>::refund_proposal_stake(*id, remaining_imbalance);
-
-            return <NegativeImbalance<T>>::zero(); // imbalance was consumed
-        }
-
-        remaining_imbalance
-    }
-
-    /// Empty handler for slashing
-    fn slashed(
-        _: &<T as stake::Trait>::StakeId,
-        _: Option<<T as stake::Trait>::SlashId>,
-        _: BalanceOf<T>,
-        _: BalanceOf<T>,
-        remaining_imbalance: NegativeImbalance<T>,
-    ) -> NegativeImbalance<T> {
-        remaining_imbalance
-    }
-}

+ 42 - 6
runtime/src/lib.rs

@@ -69,6 +69,7 @@ pub use content_directory;
 pub use content_directory::{
     HashedTextMaxLength, InputValidationLengthConstraint, MaxNumber, TextMaxLength, VecMaxLength,
 };
+use frame_support::dispatch::DispatchResult;
 
 /// This runtime version.
 pub const VERSION: RuntimeVersion = RuntimeVersion {
@@ -453,11 +454,8 @@ impl stake::Trait for Runtime {
     type Currency = <Self as common::currency::GovernanceCurrency>::Currency;
     type StakePoolId = StakePoolId;
     type StakingEventsHandler = (
-        crate::integration::proposals::StakingEventsHandler<Self>,
-        (
-            crate::integration::working_group::ContentDirectoryWGStakingEventsHandler<Self>,
-            crate::integration::working_group::StorageWgStakingEventsHandler<Self>,
-        ),
+        crate::integration::working_group::ContentDirectoryWGStakingEventsHandler<Self>,
+        crate::integration::working_group::StorageWgStakingEventsHandler<Self>,
     );
     type StakeId = u64;
     type SlashId = u64;
@@ -562,7 +560,7 @@ impl proposals_engine::Trait for Runtime {
     type VoterOriginValidator = CouncilManager<Self>;
     type TotalVotersCounter = CouncilManager<Self>;
     type ProposalId = u32;
-    type StakeHandlerProvider = proposals_engine::DefaultStakeHandlerProvider;
+    type StakingHandler = (); // !!!!!! REMOVE STUB
     type CancellationFee = ProposalCancellationFee;
     type RejectionFee = ProposalRejectionFee;
     type TitleMaxLength = ProposalTitleMaxLength;
@@ -572,6 +570,44 @@ impl proposals_engine::Trait for Runtime {
     type ProposalObserver = ProposalsCodex;
 }
 
+impl proposals_engine::StakingHandler<Runtime> for () {
+    fn lock(_account_id: &AccountId, _amount: Balance) {
+        unimplemented!()
+    }
+
+    fn unlock(_account_id: &AccountId) {
+        unimplemented!()
+    }
+
+    fn slash(_account_id: &AccountId, _amount: Option<Balance>) -> Balance {
+        unimplemented!()
+    }
+
+    fn decrease_stake(_account_id: &AccountId, _new_stake: Balance) {
+        unimplemented!()
+    }
+
+    fn increase_stake(_account_id: &AccountId, _new_stake: Balance) -> DispatchResult {
+        unimplemented!()
+    }
+
+    fn is_member_staking_account(_member_id: &MemberId, _account_id: &AccountId) -> bool {
+        unimplemented!()
+    }
+
+    fn is_account_free_of_conflicting_stakes(_account_id: &AccountId) -> bool {
+        unimplemented!()
+    }
+
+    fn is_enough_balance_for_stake(_account_id: &AccountId, _amount: Balance) -> bool {
+        unimplemented!()
+    }
+
+    fn current_stake(_account_id: &AccountId) -> Balance {
+        unimplemented!()
+    }
+}
+
 impl Default for Call {
     fn default() -> Self {
         panic!("shouldn't call default for Call");