Bladeren bron

runtime: Upgrade governance pallet.

Shamil Gadelshin 4 jaren geleden
bovenliggende
commit
0a3edf3f8d

+ 21 - 0
Cargo.lock

@@ -1019,6 +1019,27 @@ dependencies = [
  "sp-runtime",
 ]
 
+[[package]]
+name = "pallet-governance"
+version = "3.0.0"
+dependencies = [
+ "frame-support",
+ "frame-system",
+ "pallet-balances",
+ "pallet-common",
+ "pallet-membership",
+ "pallet-recurring-reward",
+ "pallet-timestamp",
+ "pallet-token-mint",
+ "parity-scale-codec",
+ "serde",
+ "sp-arithmetic",
+ "sp-core",
+ "sp-io",
+ "sp-runtime",
+ "sp-std",
+]
+
 [[package]]
 name = "pallet-hiring"
 version = "3.0.0"

+ 1 - 1
Cargo.toml

@@ -7,7 +7,7 @@ members = [
 	"runtime-modules/common",
 #	"runtime-modules/content-working-group",
 	"runtime-modules/forum",
-#	"runtime-modules/governance",
+	"runtime-modules/governance",
 	"runtime-modules/hiring",
 	"runtime-modules/membership",
 	"runtime-modules/memo",

+ 29 - 88
runtime-modules/governance/Cargo.toml

@@ -1,100 +1,41 @@
 [package]
-name = 'substrate-governance-module'
-version = '1.0.0'
+name = 'pallet-governance'
+version = '3.0.0'
 authors = ['Joystream contributors']
 edition = '2018'
 
+[dependencies]
+serde = { version = "1.0.101", optional = true, features = ["derive"] }
+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'}
+timestamp = { package = 'pallet-timestamp', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
+membership = { package = 'pallet-membership', default-features = false, path = '../membership'}
+minting = { package = 'pallet-token-mint', default-features = false, path = '../token-minting'}
+recurringrewards = { package = 'pallet-recurring-reward', default-features = false, path = '../recurring-reward'}
+common = { package = 'pallet-common', default-features = false, path = '../common'}
+
+[dev-dependencies]
+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'}
+
 [features]
 default = ['std']
 std = [
-	'sr-primitives/std',
-	'srml-support/std',
-	'system/std',
 	'serde',
 	'codec/std',
-	'timestamp/std',
-	'primitives/std',
 	'rstd/std',
-	'common/std',
+	'frame-support/std',
+	'system/std',
+	'sp-arithmetic/std',
+	'sp-runtime/std',
+	'timestamp/std',
 	'membership/std',
 	'minting/std',
-]
-
-[dependencies.sr-primitives]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'sr-primitives'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dependencies.srml-support]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'srml-support'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dependencies.system]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'srml-system'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dependencies.rstd]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'sr-std'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dependencies.serde]
-features = ['derive']
-optional = true
-version = '1.0.101'
-
-[dependencies.timestamp]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'srml-timestamp'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dependencies.primitives]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'substrate-primitives'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dependencies.codec]
-default-features = false
-features = ['derive']
-package = 'parity-scale-codec'
-version = '1.0.0'
-
-[dependencies.common]
-default_features = false
-package = 'substrate-common-module'
-path = '../common'
-
-[dependencies.membership]
-default_features = false
-package = 'substrate-membership-module'
-path = '../membership'
-
-[dev-dependencies.runtime-io]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'sr-io'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dev-dependencies.balances]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'srml-balances'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dependencies.minting]
-default_features = false
-package = 'substrate-token-mint-module'
-path = '../token-minting'
-
-[dependencies.recurringrewards]
-default_features = false
-package = 'substrate-recurring-reward-module'
-path = '../recurring-reward'
+	'recurringrewards/std',
+	'common/std',
+]

+ 30 - 21
runtime-modules/governance/src/council.rs

@@ -1,6 +1,5 @@
-use rstd::prelude::*;
-use sr_primitives::traits::{One, Zero};
-use srml_support::{debug, decl_event, decl_module, decl_storage, ensure};
+use frame_support::{debug, decl_event, decl_module, decl_storage, ensure};
+use sp_arithmetic::traits::{One, Zero};
 use system::{self, ensure_root};
 
 pub use super::election::{self, CouncilElected, Seat, Seats};
@@ -29,28 +28,29 @@ pub trait Trait: system::Trait + recurringrewards::Trait + GovernanceCurrency {
 
 decl_storage! {
     trait Store for Module<T: Trait> as Council {
-        pub ActiveCouncil get(active_council) config(): Seats<T::AccountId, BalanceOf<T>>;
+        pub ActiveCouncil get(fn active_council) config(): Seats<T::AccountId, BalanceOf<T>>;
 
-        pub TermEndsAt get(term_ends_at) config() : T::BlockNumber = T::BlockNumber::from(1);
+        pub TermEndsAt get(fn term_ends_at) config() : T::BlockNumber = T::BlockNumber::from(1);
 
         /// The mint that funds council member rewards and spending proposals budget. It is an Option
         /// because it was introduced in a runtime upgrade. It will be automatically created when
         /// a successful call to set_council_mint_capacity() is made.
-        pub CouncilMint get(council_mint) : Option<<T as minting::Trait>::MintId>;
+        pub CouncilMint get(fn council_mint) : Option<<T as minting::Trait>::MintId>;
 
         /// The reward relationships currently in place. There may not necessarily be a 1-1 correspondance with
         /// the active council, since there are multiple ways of setting/adding/removing council members, some of which
         /// do not involve creating a relationship.
-        pub RewardRelationships get(reward_relationships) : map T::AccountId => T::RewardRelationshipId;
+        pub RewardRelationships get(fn reward_relationships) : map hasher(blake2_128_concat)
+            T::AccountId => T::RewardRelationshipId;
 
         /// Reward amount paid out at each PayoutInterval
-        pub AmountPerPayout get(amount_per_payout): minting::BalanceOf<T>;
+        pub AmountPerPayout get(fn amount_per_payout): minting::BalanceOf<T>;
 
         /// Optional interval in blocks on which a reward payout will be made to each council member
-        pub PayoutInterval get(payout_interval): Option<T::BlockNumber>;
+        pub PayoutInterval get(fn payout_interval): Option<T::BlockNumber>;
 
         /// How many blocks after the reward is created, the first payout will be made
-        pub FirstPayoutAfterRewardCreated get(first_payout_after_reward_created): T::BlockNumber;
+        pub FirstPayoutAfterRewardCreated get(fn first_payout_after_reward_created): T::BlockNumber;
     }
 }
 
@@ -128,7 +128,7 @@ impl<T: Trait> Module<T> {
 
     fn remove_reward_relationships() {
         for seat in Self::active_council().into_iter() {
-            if RewardRelationships::<T>::exists(&seat.member) {
+            if RewardRelationships::<T>::contains_key(&seat.member) {
                 let id = Self::reward_relationships(&seat.member);
                 <recurringrewards::Module<T>>::remove_reward_relationship(id);
             }
@@ -165,6 +165,7 @@ decl_module! {
         /// Existing council rewards are removed and new council members do NOT get any rewards.
         /// Avoid using this call if possible, will be deprecated. The term of the new council is
         /// not extended.
+        #[weight = 10_000_000] // TODO: adjust weight
         pub fn set_council(origin, accounts: Vec<T::AccountId>) {
             ensure_root(origin)?;
 
@@ -189,6 +190,7 @@ decl_module! {
         }
 
         /// Adds a zero staked council member. A member added in this way does not get a recurring reward.
+        #[weight = 10_000_000] // TODO: adjust weight
         fn add_council_member(origin, account: T::AccountId) {
             ensure_root(origin)?;
 
@@ -209,12 +211,13 @@ decl_module! {
         }
 
         /// Remove a single council member and their reward.
+        #[weight = 10_000_000] // TODO: adjust weight
         fn remove_council_member(origin, account_to_remove: T::AccountId) {
             ensure_root(origin)?;
 
             ensure!(Self::is_councilor(&account_to_remove), "account is not a councilor");
 
-            if RewardRelationships::<T>::exists(&account_to_remove) {
+            if RewardRelationships::<T>::contains_key(&account_to_remove) {
                 let relationship_id = Self::reward_relationships(&account_to_remove);
                 <recurringrewards::Module<T>>::remove_reward_relationship(relationship_id);
             }
@@ -228,6 +231,7 @@ decl_module! {
         }
 
         /// Set blocknumber when council term will end
+        #[weight = 10_000_000] // TODO: adjust weight
         fn set_term_ends_at(origin, ends_at: T::BlockNumber) {
             ensure_root(origin)?;
             ensure!(ends_at > <system::Module<T>>::block_number(), "must set future block number");
@@ -236,28 +240,32 @@ decl_module! {
 
         /// Sets the capacity of the the council mint, if it doesn't exist, attempts to
         /// create a new one.
+        #[weight = 10_000_000] // TODO: adjust weight
         pub fn set_council_mint_capacity(origin, capacity: minting::BalanceOf<T>) {
             ensure_root(origin)?;
 
             if let Some(mint_id) = Self::council_mint() {
-                minting::Module::<T>::set_mint_capacity(mint_id, capacity)?;
+                minting::Module::<T>::set_mint_capacity(mint_id, capacity).map_err(<&str>::from)?;
             } else {
                 Self::create_new_council_mint(capacity)?;
             }
         }
 
         /// Attempts to mint and transfer amount to destination account
+        #[weight = 10_000_000] // TODO: adjust weight
         fn spend_from_council_mint(origin, amount: minting::BalanceOf<T>, destination: T::AccountId) {
             ensure_root(origin)?;
 
             if let Some(mint_id) = Self::council_mint() {
-                minting::Module::<T>::transfer_tokens(mint_id, amount, &destination)?;
+                minting::Module::<T>::transfer_tokens(mint_id, amount, &destination)
+                    .map_err(<&str>::from)?;
             } else {
-                return Err("CouncilHasNoMint")
+                return Err("CouncilHasNoMint".into());
             }
         }
 
         /// Sets the council rewards which is only applied on new council being elected.
+        #[weight = 10_000_000] // TODO: adjust weight
         fn set_council_rewards(
             origin,
             amount_per_payout: minting::BalanceOf<T>,
@@ -282,10 +290,11 @@ decl_module! {
 mod tests {
     use super::*;
     use crate::mock::*;
-    use srml_support::*;
+    use crate::DispatchResult;
+    use frame_support::*;
 
-    fn add_council_member_as_root(account: <Test as system::Trait>::AccountId) -> dispatch::Result {
-        Council::add_council_member(system::RawOrigin::Root.into(), account)
+    fn add_council_member_as_root(account: <Test as system::Trait>::AccountId) -> DispatchResult {
+        Council::add_council_member(system::RawOrigin::Root.into(), account).map_err(|e| e.into())
     }
 
     #[test]
@@ -367,9 +376,9 @@ mod tests {
             assert!(Council::is_councilor(&6));
             assert!(Council::is_councilor(&7));
 
-            assert!(RewardRelationships::<Test>::exists(&5));
-            assert!(RewardRelationships::<Test>::exists(&6));
-            assert!(RewardRelationships::<Test>::exists(&7));
+            assert!(RewardRelationships::<Test>::contains_key(&5));
+            assert!(RewardRelationships::<Test>::contains_key(&6));
+            assert!(RewardRelationships::<Test>::contains_key(&7));
         });
     }
 }

+ 71 - 45
runtime-modules/governance/src/election.rs

@@ -29,17 +29,17 @@
 // Clippy linter warning
 #![allow(clippy::redundant_closure_call)] // disable it because of the substrate lib design
 
-use rstd::prelude::*;
-use srml_support::traits::{Currency, ReservableCurrency};
-use srml_support::{decl_event, decl_module, decl_storage, dispatch::Result, ensure};
-use system::{self, ensure_root, ensure_signed};
+#[cfg(feature = "std")]
+use serde::{Deserialize, Serialize};
 
 use codec::{Decode, Encode};
+use frame_support::traits::{Currency, ReservableCurrency};
+use frame_support::{decl_event, decl_module, decl_storage, ensure};
 use rstd::collections::btree_map::BTreeMap;
 use rstd::ops::Add;
-#[cfg(feature = "std")]
-use serde::{Deserialize, Serialize};
-use sr_primitives::traits::{Hash, Zero};
+use sp_arithmetic::traits::Zero;
+use sp_runtime::traits::Hash;
+use system::{self, ensure_root, ensure_signed};
 
 use super::sealed_vote::SealedVote;
 use super::stake::Stake;
@@ -48,6 +48,8 @@ use super::council;
 use crate::election_params::ElectionParameters;
 pub use common::currency::{BalanceOf, GovernanceCurrency};
 
+use crate::DispatchResult;
+
 pub trait Trait: system::Trait + council::Trait + GovernanceCurrency + membership::Trait {
     type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
 
@@ -132,37 +134,40 @@ pub type ElectionStake<T> = Stake<BalanceOf<T>>;
 decl_storage! {
     trait Store for Module<T: Trait> as CouncilElection {
         // Flag for wether to automatically start an election after a council term ends
-        AutoStart get(auto_start) config() : bool = true;
+        AutoStart get(fn auto_start) config() : bool = true;
 
         // Current stage if there is an election running
-        Stage get(stage): Option<ElectionStage<T::BlockNumber>>;
+        Stage get(fn stage): Option<ElectionStage<T::BlockNumber>>;
 
         // The election round
-        Round get(round): u32;
+        Round get(fn round): u32;
 
-        ExistingStakeHolders get(existing_stake_holders): Vec<T::AccountId>;
-        TransferableStakes get(transferable_stakes): map T::AccountId => TransferableStake<BalanceOf<T>>;
+        ExistingStakeHolders get(fn existing_stake_holders): Vec<T::AccountId>;
+        TransferableStakes get(fn transferable_stakes): map hasher(blake2_128_concat)
+            T::AccountId => TransferableStake<BalanceOf<T>>;
 
-        Applicants get(applicants): Vec<T::AccountId>;
-        ApplicantStakes get(applicant_stakes): map T::AccountId => ElectionStake<T>;
+        Applicants get(fn applicants): Vec<T::AccountId>;
+        ApplicantStakes get(fn applicant_stakes): map hasher(blake2_128_concat)
+            T::AccountId => ElectionStake<T>;
 
-        Commitments get(commitments): Vec<T::Hash>;
+        Commitments get(fn commitments): Vec<T::Hash>;
 
         // TODO value type of this map looks scary, is there any way to simplify the notation?
-        Votes get(votes): map T::Hash => SealedVote<T::AccountId, ElectionStake<T>, T::Hash, T::AccountId>;
+        Votes get(fn votes): map hasher(blake2_128_concat)
+            T::Hash => SealedVote<T::AccountId, ElectionStake<T>, T::Hash, T::AccountId>;
 
         // Current Election Parameters.
         // Should we replace all the individual values with a single ElectionParameters type?
         // Having them individually makes it more flexible to add and remove new parameters in future
         // without dealing with migration issues.
-        AnnouncingPeriod get(announcing_period): T::BlockNumber;
-        VotingPeriod get(voting_period): T::BlockNumber;
-        RevealingPeriod get(revealing_period): T::BlockNumber;
-        CouncilSize get(council_size): u32;
-        CandidacyLimit get (candidacy_limit): u32;
-        MinCouncilStake get(min_council_stake): BalanceOf<T>;
-        NewTermDuration get(new_term_duration): T::BlockNumber;
-        MinVotingStake get(min_voting_stake): BalanceOf<T>;
+        AnnouncingPeriod get(fn announcing_period): T::BlockNumber;
+        VotingPeriod get(fn voting_period): T::BlockNumber;
+        RevealingPeriod get(fn revealing_period): T::BlockNumber;
+        CouncilSize get(fn council_size): u32;
+        CandidacyLimit get (fn candidacy_limit): u32;
+        MinCouncilStake get(fn min_council_stake): BalanceOf<T>;
+        NewTermDuration get(fn new_term_duration): T::BlockNumber;
+        MinVotingStake get(fn min_voting_stake): BalanceOf<T>;
     }
     add_extra_genesis {
         config(election_parameters): ElectionParameters<BalanceOf<T>, T::BlockNumber>;
@@ -238,7 +243,7 @@ impl<T: Trait> Module<T> {
 
     /// Starts an election. Will fail if an election is already running
     /// Initializes transferable stakes. Assumes election parameters have already been set.
-    fn start_election(current_council: Seats<T::AccountId, BalanceOf<T>>) -> Result {
+    fn start_election(current_council: Seats<T::AccountId, BalanceOf<T>>) -> DispatchResult {
         ensure!(!Self::is_election_running(), "election already in progress");
         ensure!(
             Self::existing_stake_holders().is_empty(),
@@ -618,7 +623,7 @@ impl<T: Trait> Module<T> {
         for seat in current_council.into_iter() {
             let Seat { member, stake, .. } = seat;
 
-            if <TransferableStakes<T>>::exists(&member) {
+            if <TransferableStakes<T>>::contains_key(&member) {
                 <TransferableStakes<T>>::mutate(&member, |transferbale_stake| {
                     *transferbale_stake = TransferableStake {
                         seat: transferbale_stake.seat + stake,
@@ -640,7 +645,7 @@ impl<T: Trait> Module<T> {
             for backer in seat.backers.into_iter() {
                 let Backer { member, stake, .. } = backer;
 
-                if <TransferableStakes<T>>::exists(&member) {
+                if <TransferableStakes<T>>::contains_key(&member) {
                     <TransferableStakes<T>>::mutate(&member, |transferbale_stake| {
                         *transferbale_stake = TransferableStake {
                             seat: transferbale_stake.seat,
@@ -682,7 +687,7 @@ impl<T: Trait> Module<T> {
         }
     }
 
-    fn try_add_applicant(applicant: T::AccountId, stake: BalanceOf<T>) -> Result {
+    fn try_add_applicant(applicant: T::AccountId, stake: BalanceOf<T>) -> DispatchResult {
         let mut transferable_stake = <TransferableStakes<T>>::get(&applicant);
 
         let new_stake = Self::new_stake_reusing_transferable(&mut transferable_stake.seat, stake);
@@ -700,11 +705,11 @@ impl<T: Trait> Module<T> {
         let applicant_stake = <ApplicantStakes<T>>::get(&applicant);
         let total_stake = applicant_stake.add(&new_stake);
 
-        if <TransferableStakes<T>>::exists(&applicant) {
+        if <TransferableStakes<T>>::contains_key(&applicant) {
             <TransferableStakes<T>>::insert(&applicant, transferable_stake);
         }
 
-        if !<ApplicantStakes<T>>::exists(&applicant) {
+        if !<ApplicantStakes<T>>::contains_key(&applicant) {
             // insert element at the begining, this gives priority to early applicants
             // when ordering applicants by stake if stakes are equal
             <Applicants<T>>::mutate(|applicants| applicants.insert(0, applicant.clone()));
@@ -715,8 +720,15 @@ impl<T: Trait> Module<T> {
         Ok(())
     }
 
-    fn try_add_vote(voter: T::AccountId, stake: BalanceOf<T>, commitment: T::Hash) -> Result {
-        ensure!(!<Votes<T>>::exists(commitment), "duplicate commitment");
+    fn try_add_vote(
+        voter: T::AccountId,
+        stake: BalanceOf<T>,
+        commitment: T::Hash,
+    ) -> DispatchResult {
+        ensure!(
+            !<Votes<T>>::contains_key(commitment),
+            "duplicate commitment"
+        );
 
         let mut transferable_stake = <TransferableStakes<T>>::get(&voter);
 
@@ -740,7 +752,7 @@ impl<T: Trait> Module<T> {
             SealedVote::new(voter.clone(), vote_stake, commitment),
         );
 
-        if <TransferableStakes<T>>::exists(&voter) {
+        if <TransferableStakes<T>>::contains_key(&voter) {
             <TransferableStakes<T>>::insert(&voter, transferable_stake);
         }
 
@@ -752,8 +764,11 @@ impl<T: Trait> Module<T> {
         commitment: T::Hash,
         vote_for: T::AccountId,
         salt: Vec<u8>,
-    ) -> Result {
-        ensure!(<Votes<T>>::exists(&commitment), "commitment not found");
+    ) -> DispatchResult {
+        ensure!(
+            <Votes<T>>::contains_key(&commitment),
+            "commitment not found"
+        );
 
         let mut sealed_vote = <Votes<T>>::get(&commitment);
 
@@ -761,7 +776,7 @@ impl<T: Trait> Module<T> {
         // only voter can reveal their own votes
         ensure!(sealed_vote.is_owned_by(voter), "only voter can reveal vote");
         ensure!(
-            <ApplicantStakes<T>>::exists(&vote_for),
+            <ApplicantStakes<T>>::contains_key(&vote_for),
             "vote for non-applicant not allowed"
         );
 
@@ -799,6 +814,7 @@ decl_module! {
 
         // Member can apply during announcing stage only. On first call a minimum stake will need to be provided.
         // Member can make subsequent calls during announcing stage to increase their stake.
+        #[weight = 10_000_000] // TODO: adjust weight
         pub fn apply(origin, stake: BalanceOf<T>) {
             let sender = ensure_signed(origin)?;
             ensure!(Self::can_participate(&sender), "Only members can apply to be on council");
@@ -813,7 +829,7 @@ decl_module! {
             ensure!(is_announcing, "election not in announcing stage");
 
             // minimum stake on first attempt to apply
-            if !<ApplicantStakes<T>>::exists(&sender) {
+            if !<ApplicantStakes<T>>::contains_key(&sender) {
                 ensure!(stake >= Self::min_council_stake(), "minimum stake must be provided");
             }
 
@@ -822,6 +838,7 @@ decl_module! {
             Self::deposit_event(RawEvent::Applied(sender));
         }
 
+        #[weight = 10_000_000] // TODO: adjust weight
         fn vote(origin, commitment: T::Hash, stake: BalanceOf<T>) {
             let sender = ensure_signed(origin)?;
             ensure!(Self::can_participate(&sender), "Only members can vote for an applicant");
@@ -840,6 +857,7 @@ decl_module! {
             Self::deposit_event(RawEvent::Voted(sender, commitment));
         }
 
+        #[weight = 10_000_000] // TODO: adjust weight
         fn reveal(origin, commitment: T::Hash, vote: T::AccountId, salt: Vec<u8>) {
             let sender = ensure_signed(origin)?;
 
@@ -858,18 +876,21 @@ decl_module! {
             Self::deposit_event(RawEvent::Revealed(sender, commitment, vote));
         }
 
+        #[weight = 10_000_000] // TODO: adjust weight
         fn set_stage_announcing(origin, ends_at: T::BlockNumber) {
             ensure_root(origin)?;
             ensure!(ends_at > <system::Module<T>>::block_number(), "must end at future block number");
             <Stage<T>>::put(ElectionStage::Announcing(ends_at));
         }
 
+        #[weight = 10_000_000] // TODO: adjust weight
         fn set_stage_revealing(origin, ends_at: T::BlockNumber) {
             ensure_root(origin)?;
             ensure!(ends_at > <system::Module<T>>::block_number(), "must end at future block number");
             <Stage<T>>::put(ElectionStage::Revealing(ends_at));
         }
 
+        #[weight = 10_000_000] // TODO: adjust weight
         fn set_stage_voting(origin, ends_at: T::BlockNumber) {
             ensure_root(origin)?;
             ensure!(ends_at > <system::Module<T>>::block_number(), "must end at future block number");
@@ -881,6 +902,7 @@ decl_module! {
         /// The call will fail if an election is in progress. If a council is not being elected for some
         /// reaon after multiple rounds, force_stop_election() can be called to stop elections and followed by
         /// set_election_parameters().
+        #[weight = 10_000_000] // TODO: adjust weight
         pub fn set_election_parameters(origin, params: ElectionParameters<BalanceOf<T>, T::BlockNumber>) {
             ensure_root(origin)?;
             ensure!(!Self::is_election_running(), MSG_CANNOT_CHANGE_PARAMS_DURING_ELECTION);
@@ -888,6 +910,7 @@ decl_module! {
             Self::set_verified_election_parameters(params);
         }
 
+        #[weight = 10_000_000] // TODO: adjust weight
         fn force_stop_election(origin) {
             ensure_root(origin)?;
             ensure!(Self::is_election_running(), "only running election can be stopped");
@@ -907,16 +930,17 @@ decl_module! {
             );
         }
 
+        #[weight = 10_000_000] // TODO: adjust weight
         pub fn force_start_election(origin) {
             ensure_root(origin)?;
             Self::start_election(<council::Module<T>>::active_council())?;
         }
 
+        #[weight = 10_000_000] // TODO: adjust weight
         fn set_auto_start (origin, flag: bool) {
             ensure_root(origin)?;
             AutoStart::put(flag);
         }
-
     }
 }
 
@@ -933,7 +957,9 @@ mod tests {
     use super::*;
     use crate::mock::*;
     use codec::Encode;
-    use srml_support::*;
+    use frame_support::traits::OnFinalize;
+    use frame_support::{assert_err, assert_ok};
+    use system::RawOrigin;
 
     #[test]
     fn election_starts_when_council_term_ends() {
@@ -1344,12 +1370,12 @@ mod tests {
             assert_eq!(Balances::free_balance(&1), 1000);
 
             //assert_eq!(Election::applicant_stakes(2), Default::default());
-            assert!(!<ApplicantStakes<Test>>::exists(2));
+            assert!(!<ApplicantStakes<Test>>::contains_key(2));
             assert_eq!(Election::transferable_stakes(2).seat, 400);
             assert_eq!(Balances::free_balance(&2), 2300);
 
             //assert_eq!(Election::applicant_stakes(3), Default::default());
-            assert!(!<ApplicantStakes<Test>>::exists(3));
+            assert!(!<ApplicantStakes<Test>>::contains_key(3));
             assert_eq!(Election::transferable_stakes(3).seat, 600);
             assert_eq!(Balances::free_balance(&3), 3500);
         });
@@ -1432,7 +1458,7 @@ mod tests {
 
             assert!(Election::try_add_vote(20, 1000, commitment).is_err());
             assert_eq!(Election::commitments(), vec![]);
-            assert!(!<Votes<Test>>::exists(commitment));
+            assert!(!<Votes<Test>>::contains_key(commitment));
             assert_eq!(Balances::free_balance(&20), 100);
         });
     }
@@ -1634,7 +1660,7 @@ mod tests {
 
     pub fn mock_votes(
         mock: Vec<(u64, u64, u64, u64)>,
-    ) -> Vec<SealedVote<u64, Stake<u64>, primitives::H256, u64>> {
+    ) -> Vec<SealedVote<u64, Stake<u64>, sp_core::H256, u64>> {
         let commitment = make_commitment_for_applicant(1, &mut vec![0u8]);
 
         mock.into_iter()
@@ -1806,7 +1832,7 @@ mod tests {
 
             // applicant dropped
             assert_eq!(Election::applicants(), vec![200, 300]);
-            assert!(!<ApplicantStakes<Test>>::exists(100));
+            assert!(!<ApplicantStakes<Test>>::contains_key(100));
 
             // and refunded
             assert_eq!(Election::transferable_stakes(100).seat, 150);
@@ -2095,7 +2121,7 @@ mod tests {
             };
 
             assert_ok!(Election::set_election_parameters(
-                Origin::ROOT,
+                RawOrigin::Root.into(),
                 new_parameters
             ));
 

+ 9 - 6
runtime-modules/governance/src/election_params.rs

@@ -1,8 +1,11 @@
-use codec::{Decode, Encode};
 #[cfg(feature = "std")]
 use serde::{Deserialize, Serialize};
-use sr_primitives::traits::Zero;
-use srml_support::{dispatch::Result, ensure};
+
+use codec::{Decode, Encode};
+use frame_support::ensure;
+use sp_arithmetic::traits::Zero;
+
+use crate::DispatchResult;
 
 pub static MSG_PERIOD_CANNOT_BE_ZERO: &str = "PeriodCannotBeZero";
 pub static MSG_COUNCIL_SIZE_CANNOT_BE_ZERO: &str = "CouncilSizeCannotBeZero";
@@ -24,20 +27,20 @@ pub struct ElectionParameters<Balance, BlockNumber> {
 }
 
 impl<Balance, BlockNumber: PartialOrd + Zero> ElectionParameters<Balance, BlockNumber> {
-    pub fn ensure_valid(&self) -> Result {
+    pub fn ensure_valid(&self) -> DispatchResult {
         self.ensure_periods_are_valid()?;
         self.ensure_council_size_and_candidacy_limit_are_valid()?;
         Ok(())
     }
 
-    fn ensure_periods_are_valid(&self) -> Result {
+    fn ensure_periods_are_valid(&self) -> DispatchResult {
         ensure!(!self.announcing_period.is_zero(), MSG_PERIOD_CANNOT_BE_ZERO);
         ensure!(!self.voting_period.is_zero(), MSG_PERIOD_CANNOT_BE_ZERO);
         ensure!(!self.revealing_period.is_zero(), MSG_PERIOD_CANNOT_BE_ZERO);
         Ok(())
     }
 
-    fn ensure_council_size_and_candidacy_limit_are_valid(&self) -> Result {
+    fn ensure_council_size_and_candidacy_limit_are_valid(&self) -> DispatchResult {
         ensure!(self.council_size > 0, MSG_COUNCIL_SIZE_CANNOT_BE_ZERO);
         ensure!(
             self.council_size <= self.candidacy_limit,

+ 4 - 0
runtime-modules/governance/src/lib.rs

@@ -9,3 +9,7 @@ mod sealed_vote;
 mod stake;
 
 mod mock;
+
+//TODO: Convert errors to the Substrate decl_error! macro.
+/// Result with string error message. This exists for backward compatibility purpose.
+pub type DispatchResult = Result<(), &'static str>;

+ 20 - 26
runtime-modules/governance/src/mock.rs

@@ -2,17 +2,15 @@
 
 pub use super::{council, election};
 pub use common::currency::GovernanceCurrency;
-pub use system;
 
-pub use primitives::{Blake2Hasher, H256};
-pub use sr_primitives::{
-    testing::{Digest, DigestItem, Header, UintAuthorityId},
-    traits::{BlakeTwo256, Convert, IdentityLookup, OnFinalize},
-    weights::Weight,
-    BuildStorage, Perbill,
+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};
+pub use system;
 
 impl_outer_origin! {
     pub enum Origin for Test {}
@@ -30,10 +28,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;
@@ -42,9 +41,17 @@ 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 = ();
 }
 
 impl timestamp::Trait for Test {
@@ -80,27 +87,14 @@ impl recurringrewards::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;
 }
 
 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 GovernanceCurrency for Test {
@@ -111,7 +105,7 @@ impl GovernanceCurrency for Test {
 
 // This function basically just builds a genesis storage key/value store according to
 // our desired mockup.
-pub fn initial_test_ext() -> runtime_io::TestExternalities {
+pub fn initial_test_ext() -> sp_io::TestExternalities {
     let mut t = system::GenesisConfig::default()
         .build_storage::<Test>()
         .unwrap();

+ 1 - 1
runtime-modules/governance/src/sealed_vote.rs

@@ -1,6 +1,6 @@
 use codec::{Decode, Encode};
+use frame_support::ensure;
 use rstd::vec::Vec;
-use srml_support::ensure;
 
 #[derive(Clone, Copy, Encode, Decode, Default)]
 pub struct SealedVote<AccountId, Stake, Hash, Vote>

+ 7 - 7
runtime-modules/governance/src/stake.rs

@@ -1,11 +1,11 @@
 use codec::{Decode, Encode};
 use rstd::cmp::Ordering;
-use sr_primitives::traits::SimpleArithmetic;
+use sp_arithmetic::traits::BaseArithmetic;
 
 #[derive(Encode, Decode, Clone, Copy, Default, Debug)]
 pub struct Stake<Balance>
 where
-    Balance: Copy + SimpleArithmetic,
+    Balance: Copy + BaseArithmetic,
 {
     pub new: Balance,
     pub transferred: Balance,
@@ -13,7 +13,7 @@ where
 
 impl<Balance> Stake<Balance>
 where
-    Balance: Copy + SimpleArithmetic,
+    Balance: Copy + BaseArithmetic,
 {
     pub fn total(&self) -> Balance {
         self.new + self.transferred
@@ -27,25 +27,25 @@ where
     }
 }
 
-impl<T: Copy + SimpleArithmetic> PartialOrd for Stake<T> {
+impl<T: Copy + BaseArithmetic> PartialOrd for Stake<T> {
     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
         Some(self.cmp(&other))
     }
 }
 
-impl<T: Copy + SimpleArithmetic> Ord for Stake<T> {
+impl<T: Copy + BaseArithmetic> Ord for Stake<T> {
     fn cmp(&self, other: &Self) -> Ordering {
         self.total().cmp(&other.total())
     }
 }
 
-impl<T: Copy + SimpleArithmetic> PartialEq for Stake<T> {
+impl<T: Copy + BaseArithmetic> PartialEq for Stake<T> {
     fn eq(&self, other: &Self) -> bool {
         self.total() == other.total()
     }
 }
 
-impl<T: Copy + SimpleArithmetic> Eq for Stake<T> {}
+impl<T: Copy + BaseArithmetic> Eq for Stake<T> {}
 
 #[cfg(test)]
 mod tests {