Browse Source

Run rustfmt over everything.

Jens Finkhaeuser 6 years ago
parent
commit
e69a6dae74

+ 6 - 7
src/governance/council.rs

@@ -1,12 +1,12 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
-use srml_support::{StorageValue, decl_module, decl_event, decl_storage, ensure};
-use system::{self};
-use runtime_primitives::traits::{As, Zero};
 use rstd::prelude::*;
+use runtime_primitives::traits::{As, Zero};
+use srml_support::{decl_event, decl_module, decl_storage, ensure, StorageValue};
+use system;
 
-pub use super::election::{self, Seats, Seat, CouncilElected};
-pub use super::{ GovernanceCurrency, BalanceOf };
+pub use super::election::{self, CouncilElected, Seat, Seats};
+pub use super::{BalanceOf, GovernanceCurrency};
 
 // Hook For announcing that council term has ended
 pub trait CouncilTermEnded {
@@ -55,7 +55,6 @@ impl<T: Trait> CouncilElected<Seats<T::AccountId, BalanceOf<T>>, T::BlockNumber>
 }
 
 impl<T: Trait> Module<T> {
-
     pub fn is_term_ended() -> bool {
         <system::Module<T>>::block_number() >= Self::term_ends_at()
     }
@@ -158,7 +157,7 @@ mod tests {
     #[test]
     fn set_council_test() {
         with_externalities(&mut initial_test_ext(), || {
-            assert_ok!(Council::set_council(vec![4,5,6]));
+            assert_ok!(Council::set_council(vec![4, 5, 6]));
             assert!(Council::is_councilor(&4));
             assert!(Council::is_councilor(&5));
             assert!(Council::is_councilor(&6));

File diff suppressed because it is too large
+ 367 - 179
src/governance/election.rs


+ 9 - 6
src/governance/mock.rs

@@ -1,14 +1,14 @@
 #![cfg(test)]
 
-pub use super::{election, council, proposals, GovernanceCurrency};
+pub use super::{council, election, proposals, GovernanceCurrency};
+use crate::traits::Members;
 pub use system;
-use crate::traits::{Members};
 
-pub use primitives::{H256, Blake2Hasher};
+pub use primitives::{Blake2Hasher, H256};
 pub use runtime_primitives::{
+    testing::{Digest, DigestItem, Header, UintAuthorityId},
+    traits::{BlakeTwo256, IdentityLookup, OnFinalise},
     BuildStorage,
-    traits::{BlakeTwo256, OnFinalise, IdentityLookup},
-    testing::{Digest, DigestItem, Header, UintAuthorityId}
 };
 
 use srml_support::impl_outer_origin;
@@ -102,7 +102,10 @@ 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<Blake2Hasher> {
-    let t = system::GenesisConfig::<Test>::default().build_storage().unwrap().0;
+    let t = system::GenesisConfig::<Test>::default()
+        .build_storage()
+        .unwrap()
+        .0;
 
     runtime_io::TestExternalities::new(t)
 }

+ 6 - 5
src/governance/mod.rs

@@ -1,19 +1,20 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
-use srml_support::traits::{Currency, ArithmeticType};
+use srml_support::traits::{ArithmeticType, Currency};
 use system;
 
-pub mod election;
 pub mod council;
+pub mod election;
 pub mod proposals;
 
-mod stake;
 mod sealed_vote;
+mod stake;
 
 pub trait GovernanceCurrency: system::Trait + Sized {
-    type Currency: ArithmeticType + Currency<<Self as system::Trait>::AccountId, Balance=BalanceOf<Self>>;
+    type Currency: ArithmeticType
+        + Currency<<Self as system::Trait>::AccountId, Balance = BalanceOf<Self>>;
 }
 
 pub type BalanceOf<T> = <<T as GovernanceCurrency>::Currency as ArithmeticType>::Type;
 
-mod mock;
+mod mock;

+ 334 - 195
src/governance/proposals.rs

@@ -1,17 +1,18 @@
-use srml_support::{StorageValue, StorageMap, dispatch, decl_module, decl_event, decl_storage, ensure};
-use srml_support::traits::{Currency};
-use runtime_primitives::traits::{As, Hash, Zero};
+use rstd::prelude::*;
 use runtime_io::print;
+use runtime_primitives::traits::{As, Hash, Zero};
+use srml_support::traits::Currency;
+use srml_support::{
+    decl_event, decl_module, decl_storage, dispatch, ensure, StorageMap, StorageValue,
+};
 use system::{self, ensure_signed};
-use rstd::prelude::*;
 
 #[cfg(test)]
-use primitives::{storage::well_known_keys};
-
+use primitives::storage::well_known_keys;
 
 use super::council;
-pub use super::{ GovernanceCurrency, BalanceOf };
-use crate::traits::{Members};
+pub use super::{BalanceOf, GovernanceCurrency};
+use crate::traits::Members;
 
 const DEFAULT_APPROVAL_QUORUM: u32 = 60;
 const DEFAULT_MIN_STAKE: u64 = 100;
@@ -346,7 +347,6 @@ decl_module! {
 }
 
 impl<T: Trait> Module<T> {
-
     fn current_block() -> T::BlockNumber {
         <system::Module<T>>::block_number()
     }
@@ -386,20 +386,18 @@ impl<T: Trait> Module<T> {
     }
 
     fn end_block(_now: T::BlockNumber) -> dispatch::Result {
-
         // TODO refactor this method
 
         // TODO iterate over not expired proposals and tally
 
-          Self::tally()?;
-          // TODO approve or reject a proposal
+        Self::tally()?;
+        // TODO approve or reject a proposal
 
         Ok(())
     }
 
     /// Get the voters for the current proposal.
-    pub fn tally(/* proposal_id: u32 */) -> dispatch::Result {
-
+    pub fn tally() -> dispatch::Result {
         let councilors: u32 = Self::councilors_count();
         let quorum: u32 = Self::approval_quorum_seats();
 
@@ -436,26 +434,25 @@ impl<T: Trait> Module<T> {
             // Instead let other councilors cast their vote
             // up until the proposal's expired.
 
-            let new_status: Option<ProposalStatus> =
-                if all_councilors_slashed {
-                    Some(Slashed)
-                } else if all_councilors_voted {
-                    if quorum_reached {
-                        Some(Approved)
-                    } else {
-                        Some(Rejected)
-                    }
-                } else if is_expired {
-                    if quorum_reached {
-                        Some(Approved)
-                    } else {
-                        // Proposal has been expired and quorum not reached.
-                        Some(Expired)
-                    }
+            let new_status: Option<ProposalStatus> = if all_councilors_slashed {
+                Some(Slashed)
+            } else if all_councilors_voted {
+                if quorum_reached {
+                    Some(Approved)
                 } else {
-                    // Councilors still have time to vote on this proposal.
-                    None
-                };
+                    Some(Rejected)
+                }
+            } else if is_expired {
+                if quorum_reached {
+                    Some(Approved)
+                } else {
+                    // Proposal has been expired and quorum not reached.
+                    Some(Expired)
+                }
+            } else {
+                // Councilors still have time to vote on this proposal.
+                None
+            };
 
             // TODO move next block outside of tally to 'end_block'
             if let Some(status) = new_status {
@@ -496,7 +493,7 @@ impl<T: Trait> Module<T> {
                 Slashed => Self::_slash_proposal(pid)?,
                 Rejected | Expired => Self::_reject_proposal(pid)?,
                 Approved => Self::_approve_proposal(pid)?,
-                Active | Cancelled => { /* nothing */ },
+                Active | Cancelled => { /* nothing */ }
             }
             <ActiveProposalIds<T>>::put(other_active_ids);
             <Proposals<T>>::mutate(proposal_id, |p| p.status = new_status.clone());
@@ -552,14 +549,14 @@ impl<T: Trait> Module<T> {
 mod tests {
 
     use super::*;
+    use primitives::{Blake2Hasher, H256};
     use runtime_io::with_externalities;
-    use primitives::{H256, Blake2Hasher};
     // The testing primitives are very useful for avoiding having to work with signatures
     // or public keys. `u64` is used as the `AccountId` and no `Signature`s are requried.
     use runtime_primitives::{
+        testing::{Digest, DigestItem, Header, UintAuthorityId},
+        traits::{BlakeTwo256, IdentityLookup, OnFinalise},
         BuildStorage,
-        traits::{BlakeTwo256, OnFinalise, IdentityLookup},
-        testing::{Digest, DigestItem, Header, UintAuthorityId}
     };
     use srml_support::*;
 
@@ -652,13 +649,7 @@ mod tests {
 
     const NOT_COUNCILOR: u64 = 22;
 
-    const ALL_COUNCILORS: [u64; 5] = [
-        COUNCILOR1,
-        COUNCILOR2,
-        COUNCILOR3,
-        COUNCILOR4,
-        COUNCILOR5
-    ];
+    const ALL_COUNCILORS: [u64; 5] = [COUNCILOR1, COUNCILOR2, COUNCILOR3, COUNCILOR4, COUNCILOR5];
 
     // TODO Figure out how to test Events in test... (low priority)
     // mod proposals {
@@ -673,21 +664,36 @@ mod tests {
     // This function basically just builds a genesis storage key/value store according to
     // our desired mockup.
     fn new_test_ext() -> runtime_io::TestExternalities<Blake2Hasher> {
-        let mut t = system::GenesisConfig::<Test>::default().build_storage().unwrap().0;
+        let mut t = system::GenesisConfig::<Test>::default()
+            .build_storage()
+            .unwrap()
+            .0;
         // We use default for brevity, but you can configure as desired if needed.
-        t.extend(balances::GenesisConfig::<Test>::default().build_storage().unwrap().0);
-
-        let council_mock: council::Seats<u64, u64> =
-            ALL_COUNCILORS.iter().map(|&c| council::Seat {
+        t.extend(
+            balances::GenesisConfig::<Test>::default()
+                .build_storage()
+                .unwrap()
+                .0,
+        );
+
+        let council_mock: council::Seats<u64, u64> = ALL_COUNCILORS
+            .iter()
+            .map(|&c| council::Seat {
                 member: c,
                 stake: 0u64,
                 backers: vec![],
-            }).collect();
+            })
+            .collect();
 
-        t.extend(council::GenesisConfig::<Test>{
-            active_council: council_mock,
-            term_ends_at: 0,
-        }.build_storage().unwrap().0);
+        t.extend(
+            council::GenesisConfig::<Test> {
+                active_council: council_mock,
+                term_ends_at: 0,
+            }
+            .build_storage()
+            .unwrap()
+            .0,
+        );
 
         // t.extend(GenesisConfig::<Test>{
         //     // Here we can override defaults.
@@ -737,14 +743,14 @@ mod tests {
         stake: Option<u64>,
         name: Option<Vec<u8>>,
         description: Option<Vec<u8>>,
-        wasm_code: Option<Vec<u8>>
+        wasm_code: Option<Vec<u8>>,
     ) -> dispatch::Result {
         Proposals::create_proposal(
             Origin::signed(origin.unwrap_or(PROPOSER1)),
             stake.unwrap_or(min_stake()),
             name.unwrap_or(self::name()),
             description.unwrap_or(self::description()),
-            wasm_code.unwrap_or(self::wasm_code())
+            wasm_code.unwrap_or(self::wasm_code()),
         )
     }
 
@@ -753,11 +759,15 @@ mod tests {
     }
 
     macro_rules! assert_runtime_code_empty {
-        () => { assert_eq!(get_runtime_code(), None) }
+        () => {
+            assert_eq!(get_runtime_code(), None)
+        };
     }
 
     macro_rules! assert_runtime_code {
-        ($code:expr) => { assert_eq!(get_runtime_code(), Some($code)) }
+        ($code:expr) => {
+            assert_eq!(get_runtime_code(), Some($code))
+        };
     }
 
     #[test]
@@ -768,7 +778,10 @@ mod tests {
             assert_eq!(Proposals::cancellation_fee(), DEFAULT_CANCELLATION_FEE);
             assert_eq!(Proposals::rejection_fee(), DEFAULT_REJECTION_FEE);
             assert_eq!(Proposals::name_max_len(), DEFAULT_NAME_MAX_LEN);
-            assert_eq!(Proposals::description_max_len(), DEFAULT_DESCRIPTION_MAX_LEN);
+            assert_eq!(
+                Proposals::description_max_len(),
+                DEFAULT_DESCRIPTION_MAX_LEN
+            );
             assert_eq!(Proposals::wasm_code_max_len(), DEFAULT_WASM_CODE_MAX_LEN);
             assert_eq!(Proposals::proposal_count(), 0);
             assert!(Proposals::active_proposal_ids().is_empty());
@@ -794,12 +807,15 @@ mod tests {
                 description: description(),
                 wasm_hash,
                 proposed_at: 1,
-                status: Active
+                status: Active,
             };
             assert_eq!(Proposals::proposals(1), expected_proposal);
 
             // Check that stake amount has been locked on proposer's balance:
-            assert_eq!(Balances::free_balance(PROPOSER1), initial_balance() - min_stake());
+            assert_eq!(
+                Balances::free_balance(PROPOSER1),
+                initial_balance() - min_stake()
+            );
             assert_eq!(Balances::reserved_balance(PROPOSER1), min_stake());
 
             // TODO expect event ProposalCreated(AccountId, u32)
@@ -811,8 +827,10 @@ mod tests {
         with_externalities(&mut new_test_ext(), || {
             // In this test a proposer has an empty balance
             // thus he is not considered as a member.
-            assert_eq!(_create_default_proposal(),
-                Err(MSG_ONLY_MEMBERS_CAN_PROPOSE));
+            assert_eq!(
+                _create_default_proposal(),
+                Err(MSG_ONLY_MEMBERS_CAN_PROPOSE)
+            );
         });
     }
 
@@ -822,9 +840,10 @@ mod tests {
             Balances::set_free_balance(&PROPOSER1, initial_balance());
             Balances::increase_total_stake_by(initial_balance());
 
-            assert_eq!(_create_proposal(
-                None, Some(min_stake() - 1), None, None, None),
-                Err(MSG_STAKE_IS_TOO_LOW));
+            assert_eq!(
+                _create_proposal(None, Some(min_stake() - 1), None, None, None),
+                Err(MSG_STAKE_IS_TOO_LOW)
+            );
 
             // Check that balances remain unchanged afer a failed attempt to create a proposal:
             assert_eq!(Balances::free_balance(PROPOSER1), initial_balance());
@@ -838,9 +857,10 @@ mod tests {
             Balances::set_free_balance(&PROPOSER1, initial_balance());
             Balances::increase_total_stake_by(initial_balance());
 
-            assert_eq!(_create_proposal(
-                None, Some(initial_balance() + 1), None, None, None),
-                Err(MSG_STAKE_IS_GREATER_THAN_BALANCE));
+            assert_eq!(
+                _create_proposal(None, Some(initial_balance() + 1), None, None, None),
+                Err(MSG_STAKE_IS_GREATER_THAN_BALANCE)
+            );
 
             // Check that balances remain unchanged afer a failed attempt to create a proposal:
             assert_eq!(Balances::free_balance(PROPOSER1), initial_balance());
@@ -855,19 +875,22 @@ mod tests {
             Balances::increase_total_stake_by(initial_balance());
 
             // Empty name:
-            assert_eq!(_create_proposal(
-                None, None, Some(vec![]), None, None),
-                Err(MSG_EMPTY_NAME_PROVIDED));
+            assert_eq!(
+                _create_proposal(None, None, Some(vec![]), None, None),
+                Err(MSG_EMPTY_NAME_PROVIDED)
+            );
 
             // Empty description:
-            assert_eq!(_create_proposal(
-                None, None, None, Some(vec![]), None),
-                Err(MSG_EMPTY_DESCRIPTION_PROVIDED));
+            assert_eq!(
+                _create_proposal(None, None, None, Some(vec![]), None),
+                Err(MSG_EMPTY_DESCRIPTION_PROVIDED)
+            );
 
             // Empty WASM code:
-            assert_eq!(_create_proposal(
-                None, None, None, None, Some(vec![])),
-                Err(MSG_EMPTY_WASM_CODE_PROVIDED));
+            assert_eq!(
+                _create_proposal(None, None, None, None, Some(vec![])),
+                Err(MSG_EMPTY_WASM_CODE_PROVIDED)
+            );
         });
     }
 
@@ -878,19 +901,22 @@ mod tests {
             Balances::increase_total_stake_by(initial_balance());
 
             // Too long name:
-            assert_eq!(_create_proposal(
-                None, None, Some(too_long_name()), None, None),
-                Err(MSG_TOO_LONG_NAME));
+            assert_eq!(
+                _create_proposal(None, None, Some(too_long_name()), None, None),
+                Err(MSG_TOO_LONG_NAME)
+            );
 
             // Too long description:
-            assert_eq!(_create_proposal(
-                None, None, None, Some(too_long_description()), None),
-                Err(MSG_TOO_LONG_DESCRIPTION));
+            assert_eq!(
+                _create_proposal(None, None, None, Some(too_long_description()), None),
+                Err(MSG_TOO_LONG_DESCRIPTION)
+            );
 
             // Too long WASM code:
-            assert_eq!(_create_proposal(
-                None, None, None, None, Some(too_long_wasm_code())),
-                Err(MSG_TOO_LONG_WASM_CODE));
+            assert_eq!(
+                _create_proposal(None, None, None, None, Some(too_long_wasm_code())),
+                Err(MSG_TOO_LONG_WASM_CODE)
+            );
         });
     }
 
@@ -921,7 +947,10 @@ mod tests {
             assert!(Proposals::active_proposal_ids().is_empty());
 
             // Check that proposer's balance reduced by cancellation fee and other part of his stake returned to his balance:
-            assert_eq!(Balances::free_balance(PROPOSER1), initial_balance() - cancellation_fee());
+            assert_eq!(
+                Balances::free_balance(PROPOSER1),
+                initial_balance() - cancellation_fee()
+            );
             assert_eq!(Balances::reserved_balance(PROPOSER1), 0);
 
             // TODO expect event ProposalCancelled(AccountId, u32)
@@ -942,12 +971,17 @@ mod tests {
             let updated_free_balance = Balances::free_balance(PROPOSER1);
             let updated_reserved_balance = Balances::reserved_balance(PROPOSER1);
 
-            assert_eq!(Proposals::cancel_proposal(Origin::signed(PROPOSER1), 1),
-                Err(MSG_PROPOSAL_FINALIZED));
+            assert_eq!(
+                Proposals::cancel_proposal(Origin::signed(PROPOSER1), 1),
+                Err(MSG_PROPOSAL_FINALIZED)
+            );
 
             // Check that proposer's balance and locked stake haven't been changed:
             assert_eq!(Balances::free_balance(PROPOSER1), updated_free_balance);
-            assert_eq!(Balances::reserved_balance(PROPOSER1), updated_reserved_balance);
+            assert_eq!(
+                Balances::reserved_balance(PROPOSER1),
+                updated_reserved_balance
+            );
         });
     }
 
@@ -958,8 +992,10 @@ mod tests {
             Balances::set_free_balance(&PROPOSER2, initial_balance());
             Balances::increase_total_stake_by(initial_balance() * 2);
             assert_ok!(_create_default_proposal());
-            assert_eq!(Proposals::cancel_proposal(Origin::signed(PROPOSER2), 1),
-                Err(MSG_YOU_DONT_OWN_THIS_PROPOSAL));
+            assert_eq!(
+                Proposals::cancel_proposal(Origin::signed(PROPOSER2), 1),
+                Err(MSG_YOU_DONT_OWN_THIS_PROPOSAL)
+            );
         });
     }
 
@@ -974,11 +1010,17 @@ mod tests {
             assert_ok!(_create_default_proposal());
 
             assert_ok!(Proposals::vote_on_proposal(
-                Origin::signed(COUNCILOR1), 1, Approve));
+                Origin::signed(COUNCILOR1),
+                1,
+                Approve
+            ));
 
             // Check that a vote has been saved:
             assert_eq!(Proposals::votes_by_proposal(1), vec![(COUNCILOR1, Approve)]);
-            assert_eq!(Proposals::vote_by_account_and_proposal((COUNCILOR1, 1)), Approve);
+            assert_eq!(
+                Proposals::vote_by_account_and_proposal((COUNCILOR1, 1)),
+                Approve
+            );
 
             // TODO expect event Voted(PROPOSER1, 1, Approve)
         });
@@ -992,10 +1034,14 @@ mod tests {
             assert_ok!(_create_default_proposal());
 
             assert_ok!(Proposals::vote_on_proposal(
-                Origin::signed(COUNCILOR1), 1, Approve));
-            assert_eq!(Proposals::vote_on_proposal(
-                Origin::signed(COUNCILOR1), 1, Approve),
-                Err(MSG_YOU_ALREADY_VOTED));
+                Origin::signed(COUNCILOR1),
+                1,
+                Approve
+            ));
+            assert_eq!(
+                Proposals::vote_on_proposal(Origin::signed(COUNCILOR1), 1, Approve),
+                Err(MSG_YOU_ALREADY_VOTED)
+            );
         });
     }
 
@@ -1004,14 +1050,15 @@ mod tests {
         with_externalities(&mut new_test_ext(), || {
             Balances::set_free_balance(&COUNCILOR1, initial_balance());
             Balances::increase_total_stake_by(initial_balance());
-            assert_ok!(_create_proposal(
-                Some(COUNCILOR1), None, None, None, None
-            ));
+            assert_ok!(_create_proposal(Some(COUNCILOR1), None, None, None, None));
 
             // Check that a vote has been sent automatically,
             // such as the proposer is a councilor:
             assert_eq!(Proposals::votes_by_proposal(1), vec![(COUNCILOR1, Approve)]);
-            assert_eq!(Proposals::vote_by_account_and_proposal((COUNCILOR1, 1)), Approve);
+            assert_eq!(
+                Proposals::vote_by_account_and_proposal((COUNCILOR1, 1)),
+                Approve
+            );
         });
     }
 
@@ -1021,9 +1068,10 @@ mod tests {
             Balances::set_free_balance(&PROPOSER1, initial_balance());
             Balances::increase_total_stake_by(initial_balance());
             assert_ok!(_create_default_proposal());
-            assert_eq!(Proposals::vote_on_proposal(
-                Origin::signed(NOT_COUNCILOR), 1, Approve),
-                Err(MSG_ONLY_COUNCILORS_CAN_VOTE));
+            assert_eq!(
+                Proposals::vote_on_proposal(Origin::signed(NOT_COUNCILOR), 1, Approve),
+                Err(MSG_ONLY_COUNCILORS_CAN_VOTE)
+            );
         });
     }
 
@@ -1034,9 +1082,10 @@ mod tests {
             Balances::increase_total_stake_by(initial_balance());
             assert_ok!(_create_default_proposal());
             assert_ok!(Proposals::cancel_proposal(Origin::signed(PROPOSER1), 1));
-            assert_eq!(Proposals::vote_on_proposal(
-                Origin::signed(COUNCILOR1), 1, Approve),
-                Err(MSG_PROPOSAL_FINALIZED));
+            assert_eq!(
+                Proposals::vote_on_proposal(Origin::signed(COUNCILOR1), 1, Approve),
+                Err(MSG_PROPOSAL_FINALIZED)
+            );
         });
     }
 
@@ -1052,8 +1101,15 @@ mod tests {
             let mut expected_votes: Vec<(u64, VoteKind)> = vec![];
             for &councilor in ALL_COUNCILORS.iter() {
                 expected_votes.push((councilor, Approve));
-                assert_ok!(Proposals::vote_on_proposal(Origin::signed(councilor), 1, Approve));
-                assert_eq!(Proposals::vote_by_account_and_proposal((councilor, 1)), Approve);
+                assert_ok!(Proposals::vote_on_proposal(
+                    Origin::signed(councilor),
+                    1,
+                    Approve
+                ));
+                assert_eq!(
+                    Proposals::vote_by_account_and_proposal((councilor, 1)),
+                    Approve
+                );
             }
             assert_eq!(Proposals::votes_by_proposal(1), expected_votes);
 
@@ -1064,9 +1120,10 @@ mod tests {
             assert_eq!(Proposals::proposals(1).status, Approved);
 
             // Try to vote on finalized proposal:
-            assert_eq!(Proposals::vote_on_proposal(
-                Origin::signed(COUNCILOR1), 1, Reject),
-                Err(MSG_PROPOSAL_FINALIZED));
+            assert_eq!(
+                Proposals::vote_on_proposal(Origin::signed(COUNCILOR1), 1, Reject),
+                Err(MSG_PROPOSAL_FINALIZED)
+            );
         });
     }
 
@@ -1085,8 +1142,15 @@ mod tests {
             let mut expected_votes: Vec<(u64, VoteKind)> = vec![];
             for &councilor in ALL_COUNCILORS.iter() {
                 expected_votes.push((councilor, Approve));
-                assert_ok!(Proposals::vote_on_proposal(Origin::signed(councilor), 1, Approve));
-                assert_eq!(Proposals::vote_by_account_and_proposal((councilor, 1)), Approve);
+                assert_ok!(Proposals::vote_on_proposal(
+                    Origin::signed(councilor),
+                    1,
+                    Approve
+                ));
+                assert_eq!(
+                    Proposals::vote_by_account_and_proposal((councilor, 1)),
+                    Approve
+                );
             }
             assert_eq!(Proposals::votes_by_proposal(1), expected_votes);
 
@@ -1100,15 +1164,18 @@ mod tests {
 
             assert!(Proposals::active_proposal_ids().is_empty());
             assert_eq!(Proposals::proposals(1).status, Approved);
-            assert_eq!(Proposals::tally_results(1), TallyResult {
-                proposal_id: 1,
-                abstentions: 0,
-                approvals: ALL_COUNCILORS.len() as u32,
-                rejections: 0,
-                slashes: 0,
-                status: Approved,
-                finalized_at: 2
-            });
+            assert_eq!(
+                Proposals::tally_results(1),
+                TallyResult {
+                    proposal_id: 1,
+                    abstentions: 0,
+                    approvals: ALL_COUNCILORS.len() as u32,
+                    rejections: 0,
+                    slashes: 0,
+                    status: Approved,
+                    finalized_at: 2
+                }
+            );
 
             // Check that proposer's stake has been added back to his balance:
             assert_eq!(Balances::free_balance(PROPOSER1), initial_balance());
@@ -1131,9 +1198,16 @@ mod tests {
             let approvals = Proposals::approval_quorum_seats();
             let rejections = councilors - approvals;
             for i in 0..councilors as usize {
-                let vote = if (i as u32) < approvals { Approve } else { Reject };
+                let vote = if (i as u32) < approvals {
+                    Approve
+                } else {
+                    Reject
+                };
                 assert_ok!(Proposals::vote_on_proposal(
-                    Origin::signed(ALL_COUNCILORS[i]), 1, vote));
+                    Origin::signed(ALL_COUNCILORS[i]),
+                    1,
+                    vote
+                ));
             }
             assert_eq!(Proposals::votes_by_proposal(1).len() as u32, councilors);
 
@@ -1147,15 +1221,18 @@ mod tests {
 
             assert!(Proposals::active_proposal_ids().is_empty());
             assert_eq!(Proposals::proposals(1).status, Approved);
-            assert_eq!(Proposals::tally_results(1), TallyResult {
-                proposal_id: 1,
-                abstentions: 0,
-                approvals: approvals,
-                rejections: rejections,
-                slashes: 0,
-                status: Approved,
-                finalized_at: 2
-            });
+            assert_eq!(
+                Proposals::tally_results(1),
+                TallyResult {
+                    proposal_id: 1,
+                    abstentions: 0,
+                    approvals: approvals,
+                    rejections: rejections,
+                    slashes: 0,
+                    status: Approved,
+                    finalized_at: 2
+                }
+            );
 
             // Check that proposer's stake has been added back to his balance:
             assert_eq!(Balances::free_balance(PROPOSER1), initial_balance());
@@ -1176,9 +1253,16 @@ mod tests {
             // Only quorum of councilors approved, other councilors didn't vote:
             let approvals = Proposals::approval_quorum_seats();
             for i in 0..approvals as usize {
-                let vote = if (i as u32) < approvals { Approve } else { Slash };
+                let vote = if (i as u32) < approvals {
+                    Approve
+                } else {
+                    Slash
+                };
                 assert_ok!(Proposals::vote_on_proposal(
-                    Origin::signed(ALL_COUNCILORS[i]), 1, vote));
+                    Origin::signed(ALL_COUNCILORS[i]),
+                    1,
+                    vote
+                ));
             }
             assert_eq!(Proposals::votes_by_proposal(1).len() as u32, approvals);
 
@@ -1200,15 +1284,18 @@ mod tests {
 
             assert!(Proposals::active_proposal_ids().is_empty());
             assert_eq!(Proposals::proposals(1).status, Approved);
-            assert_eq!(Proposals::tally_results(1), TallyResult {
-                proposal_id: 1,
-                abstentions: 0,
-                approvals: approvals,
-                rejections: 0,
-                slashes: 0,
-                status: Approved,
-                finalized_at: expiration_block
-            });
+            assert_eq!(
+                Proposals::tally_results(1),
+                TallyResult {
+                    proposal_id: 1,
+                    abstentions: 0,
+                    approvals: approvals,
+                    rejections: 0,
+                    slashes: 0,
+                    status: Approved,
+                    finalized_at: expiration_block
+                }
+            );
 
             // Check that proposer's stake has been added back to his balance:
             assert_eq!(Balances::free_balance(PROPOSER1), initial_balance());
@@ -1231,9 +1318,16 @@ mod tests {
             let approvals = Proposals::approval_quorum_seats() - 1;
             let abstentions = councilors - approvals;
             for i in 0..councilors as usize {
-                let vote = if (i as u32) < approvals { Approve } else { Abstain };
+                let vote = if (i as u32) < approvals {
+                    Approve
+                } else {
+                    Abstain
+                };
                 assert_ok!(Proposals::vote_on_proposal(
-                    Origin::signed(ALL_COUNCILORS[i]), 1, vote));
+                    Origin::signed(ALL_COUNCILORS[i]),
+                    1,
+                    vote
+                ));
             }
             assert_eq!(Proposals::votes_by_proposal(1).len() as u32, councilors);
 
@@ -1247,18 +1341,24 @@ mod tests {
 
             assert!(Proposals::active_proposal_ids().is_empty());
             assert_eq!(Proposals::proposals(1).status, Rejected);
-            assert_eq!(Proposals::tally_results(1), TallyResult {
-                proposal_id: 1,
-                abstentions: abstentions,
-                approvals: approvals,
-                rejections: 0,
-                slashes: 0,
-                status: Rejected,
-                finalized_at: 2
-            });
+            assert_eq!(
+                Proposals::tally_results(1),
+                TallyResult {
+                    proposal_id: 1,
+                    abstentions: abstentions,
+                    approvals: approvals,
+                    rejections: 0,
+                    slashes: 0,
+                    status: Rejected,
+                    finalized_at: 2
+                }
+            );
 
             // Check that proposer's balance reduced by burnt stake:
-            assert_eq!(Balances::free_balance(PROPOSER1), initial_balance() - rejection_fee());
+            assert_eq!(
+                Balances::free_balance(PROPOSER1),
+                initial_balance() - rejection_fee()
+            );
             assert_eq!(Balances::reserved_balance(PROPOSER1), 0);
 
             // TODO expect event ProposalStatusUpdated(1, Rejected)
@@ -1277,8 +1377,15 @@ mod tests {
             let mut expected_votes: Vec<(u64, VoteKind)> = vec![];
             for &councilor in ALL_COUNCILORS.iter() {
                 expected_votes.push((councilor, Reject));
-                assert_ok!(Proposals::vote_on_proposal(Origin::signed(councilor), 1, Reject));
-                assert_eq!(Proposals::vote_by_account_and_proposal((councilor, 1)), Reject);
+                assert_ok!(Proposals::vote_on_proposal(
+                    Origin::signed(councilor),
+                    1,
+                    Reject
+                ));
+                assert_eq!(
+                    Proposals::vote_by_account_and_proposal((councilor, 1)),
+                    Reject
+                );
             }
             assert_eq!(Proposals::votes_by_proposal(1), expected_votes);
 
@@ -1292,18 +1399,24 @@ mod tests {
 
             assert!(Proposals::active_proposal_ids().is_empty());
             assert_eq!(Proposals::proposals(1).status, Rejected);
-            assert_eq!(Proposals::tally_results(1), TallyResult {
-                proposal_id: 1,
-                abstentions: 0,
-                approvals: 0,
-                rejections: ALL_COUNCILORS.len() as u32,
-                slashes: 0,
-                status: Rejected,
-                finalized_at: 2
-            });
+            assert_eq!(
+                Proposals::tally_results(1),
+                TallyResult {
+                    proposal_id: 1,
+                    abstentions: 0,
+                    approvals: 0,
+                    rejections: ALL_COUNCILORS.len() as u32,
+                    slashes: 0,
+                    status: Rejected,
+                    finalized_at: 2
+                }
+            );
 
             // Check that proposer's balance reduced by burnt stake:
-            assert_eq!(Balances::free_balance(PROPOSER1), initial_balance() - rejection_fee());
+            assert_eq!(
+                Balances::free_balance(PROPOSER1),
+                initial_balance() - rejection_fee()
+            );
             assert_eq!(Balances::reserved_balance(PROPOSER1), 0);
 
             // TODO expect event ProposalStatusUpdated(1, Rejected)
@@ -1322,8 +1435,15 @@ mod tests {
             let mut expected_votes: Vec<(u64, VoteKind)> = vec![];
             for &councilor in ALL_COUNCILORS.iter() {
                 expected_votes.push((councilor, Slash));
-                assert_ok!(Proposals::vote_on_proposal(Origin::signed(councilor), 1, Slash));
-                assert_eq!(Proposals::vote_by_account_and_proposal((councilor, 1)), Slash);
+                assert_ok!(Proposals::vote_on_proposal(
+                    Origin::signed(councilor),
+                    1,
+                    Slash
+                ));
+                assert_eq!(
+                    Proposals::vote_by_account_and_proposal((councilor, 1)),
+                    Slash
+                );
             }
             assert_eq!(Proposals::votes_by_proposal(1), expected_votes);
 
@@ -1337,18 +1457,24 @@ mod tests {
 
             assert!(Proposals::active_proposal_ids().is_empty());
             assert_eq!(Proposals::proposals(1).status, Slashed);
-            assert_eq!(Proposals::tally_results(1), TallyResult {
-                proposal_id: 1,
-                abstentions: 0,
-                approvals: 0,
-                rejections: 0,
-                slashes: ALL_COUNCILORS.len() as u32,
-                status: Slashed,
-                finalized_at: 2
-            });
+            assert_eq!(
+                Proposals::tally_results(1),
+                TallyResult {
+                    proposal_id: 1,
+                    abstentions: 0,
+                    approvals: 0,
+                    rejections: 0,
+                    slashes: ALL_COUNCILORS.len() as u32,
+                    status: Slashed,
+                    finalized_at: 2
+                }
+            );
 
             // Check that proposer's balance reduced by burnt stake:
-            assert_eq!(Balances::free_balance(PROPOSER1), initial_balance() - min_stake());
+            assert_eq!(
+                Balances::free_balance(PROPOSER1),
+                initial_balance() - min_stake()
+            );
             assert_eq!(Balances::reserved_balance(PROPOSER1), 0);
 
             // TODO expect event ProposalStatusUpdated(1, Slashed)
@@ -1375,9 +1501,16 @@ mod tests {
             // Less than a quorum of councilors approved:
             let approvals = Proposals::approval_quorum_seats() - 1;
             for i in 0..approvals as usize {
-                let vote = if (i as u32) < approvals { Approve } else { Slash };
+                let vote = if (i as u32) < approvals {
+                    Approve
+                } else {
+                    Slash
+                };
                 assert_ok!(Proposals::vote_on_proposal(
-                    Origin::signed(ALL_COUNCILORS[i]), 1, vote));
+                    Origin::signed(ALL_COUNCILORS[i]),
+                    1,
+                    vote
+                ));
             }
             assert_eq!(Proposals::votes_by_proposal(1).len() as u32, approvals);
 
@@ -1392,18 +1525,24 @@ mod tests {
 
             assert!(Proposals::active_proposal_ids().is_empty());
             assert_eq!(Proposals::proposals(1).status, Expired);
-            assert_eq!(Proposals::tally_results(1), TallyResult {
-                proposal_id: 1,
-                abstentions: 0,
-                approvals: approvals,
-                rejections: 0,
-                slashes: 0,
-                status: Expired,
-                finalized_at: expiration_block
-            });
+            assert_eq!(
+                Proposals::tally_results(1),
+                TallyResult {
+                    proposal_id: 1,
+                    abstentions: 0,
+                    approvals: approvals,
+                    rejections: 0,
+                    slashes: 0,
+                    status: Expired,
+                    finalized_at: expiration_block
+                }
+            );
 
             // Check that proposer's balance reduced by burnt stake:
-            assert_eq!(Balances::free_balance(PROPOSER1), initial_balance() - rejection_fee());
+            assert_eq!(
+                Balances::free_balance(PROPOSER1),
+                initial_balance() - rejection_fee()
+            );
             assert_eq!(Balances::reserved_balance(PROPOSER1), 0);
 
             // TODO expect event ProposalStatusUpdated(1, Rejected)

+ 31 - 11
src/governance/sealed_vote.rs

@@ -1,23 +1,33 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
-use srml_support::{ensure};
 use parity_codec::Encode;
 use rstd::vec::Vec;
+use srml_support::ensure;
 
 #[derive(Clone, Copy, Encode, Decode, Default)]
 pub struct SealedVote<AccountId, Stake, Hash, Vote>
-    where Vote: Encode, Hash: PartialEq, AccountId: PartialEq
+where
+    Vote: Encode,
+    Hash: PartialEq,
+    AccountId: PartialEq,
 {
-  pub voter: AccountId,
-  pub commitment: Hash, // 32 bytes - salted hash of serialized Vote
-  pub stake: Stake,
-  vote: Option<Vote>, // will be set when unsealing
+    pub voter: AccountId,
+    pub commitment: Hash, // 32 bytes - salted hash of serialized Vote
+    pub stake: Stake,
+    vote: Option<Vote>, // will be set when unsealing
 }
 
 impl<AccountId, Stake, Hash, Vote> SealedVote<AccountId, Stake, Hash, Vote>
-    where Vote: Encode, Hash: PartialEq, AccountId: PartialEq
+where
+    Vote: Encode,
+    Hash: PartialEq,
+    AccountId: PartialEq,
 {
-    pub fn new(voter: AccountId, stake: Stake, commitment: Hash) -> SealedVote<AccountId, Stake, Hash, Vote> {
+    pub fn new(
+        voter: AccountId,
+        stake: Stake,
+        commitment: Hash,
+    ) -> SealedVote<AccountId, Stake, Hash, Vote> {
         SealedVote {
             voter,
             commitment,
@@ -26,7 +36,12 @@ impl<AccountId, Stake, Hash, Vote> SealedVote<AccountId, Stake, Hash, Vote>
         }
     }
 
-    pub fn new_unsealed(voter: AccountId, stake: Stake, commitment: Hash, vote: Vote) -> SealedVote<AccountId, Stake, Hash, Vote> {
+    pub fn new_unsealed(
+        voter: AccountId,
+        stake: Stake,
+        commitment: Hash,
+        vote: Vote,
+    ) -> SealedVote<AccountId, Stake, Hash, Vote> {
         SealedVote {
             voter,
             commitment,
@@ -35,7 +50,12 @@ impl<AccountId, Stake, Hash, Vote> SealedVote<AccountId, Stake, Hash, Vote>
         }
     }
 
-    pub fn unseal(&mut self, vote: Vote, salt: &mut Vec<u8>, hasher: fn(&[u8]) -> Hash) -> Result<(), &'static str> {
+    pub fn unseal(
+        &mut self,
+        vote: Vote,
+        salt: &mut Vec<u8>,
+        hasher: fn(&[u8]) -> Hash,
+    ) -> Result<(), &'static str> {
         // only unseal once
         ensure!(self.is_not_revealed(), "vote already unsealed");
 
@@ -67,4 +87,4 @@ impl<AccountId, Stake, Hash, Vote> SealedVote<AccountId, Stake, Hash, Vote>
     pub fn is_not_revealed(&self) -> bool {
         self.vote.is_none()
     }
-}
+}

+ 17 - 10
src/governance/stake.rs

@@ -1,18 +1,20 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
 use rstd::cmp::Ordering;
-use runtime_primitives::traits::{SimpleArithmetic};
+use runtime_primitives::traits::SimpleArithmetic;
 
 #[derive(Encode, Decode, Clone, Copy, Default, Debug)]
 pub struct Stake<Balance>
-    where Balance: Copy + SimpleArithmetic,
+where
+    Balance: Copy + SimpleArithmetic,
 {
     pub new: Balance,
     pub transferred: Balance,
 }
 
 impl<Balance> Stake<Balance>
-    where Balance: Copy + SimpleArithmetic,
+where
+    Balance: Copy + SimpleArithmetic,
 {
     pub fn total(&self) -> Balance {
         self.new + self.transferred
@@ -21,7 +23,7 @@ impl<Balance> Stake<Balance>
     pub fn add(&self, v: &Self) -> Self {
         Self {
             new: self.new + v.new,
-            transferred: self.transferred + v.transferred
+            transferred: self.transferred + v.transferred,
         }
     }
 }
@@ -63,8 +65,10 @@ mod tests {
 
     #[test]
     fn adding() {
-        let a1: u128 = 3; let b1: u128 = 2;
-        let a2: u128 = 5; let b2: u128 = 7;
+        let a1: u128 = 3;
+        let b1: u128 = 2;
+        let a2: u128 = 5;
+        let b2: u128 = 7;
 
         let s1 = Stake {
             new: a1,
@@ -84,9 +88,12 @@ mod tests {
 
     #[test]
     fn equality() {
-        let a1: u128 = 3; let b1: u128 = 2;
-        let a2: u128 = 2; let b2: u128 = 3;
-        let a3: u128 = 10; let b3: u128 = 10;
+        let a1: u128 = 3;
+        let b1: u128 = 2;
+        let a2: u128 = 2;
+        let b2: u128 = 3;
+        let a3: u128 = 10;
+        let b3: u128 = 10;
 
         let s1 = Stake {
             new: a1,
@@ -111,4 +118,4 @@ mod tests {
 
         assert_ne!(s1, s4);
     }
-}
+}

+ 215 - 212
src/lib.rs

@@ -3,7 +3,7 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 #![cfg_attr(not(feature = "std"), feature(alloc))]
 // `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
-#![recursion_limit="256"]
+#![recursion_limit = "256"]
 
 #[cfg(feature = "std")]
 #[macro_use]
@@ -15,42 +15,47 @@ use substrate_client as client;
 extern crate parity_codec_derive;
 
 pub mod governance;
-use governance::{election, council, proposals};
+use governance::{council, election, proposals};
 pub mod storage;
-use storage::{data_object_type_registry, data_directory, data_object_storage_registry, downloads, content_directory};
+use storage::{
+    content_directory, data_directory, data_object_storage_registry, data_object_type_registry,
+    downloads,
+};
+mod membership;
 mod memo;
 mod traits;
-mod membership;
 use membership::members;
 mod migration;
 mod roles;
 use roles::actors;
 
-use rstd::prelude::*;
+use client::{
+    block_builder::api::{self as block_builder_api, CheckInherentsResult, InherentData},
+    impl_runtime_apis, runtime_api,
+};
 #[cfg(feature = "std")]
 use primitives::bytes;
 use primitives::{Ed25519AuthorityId, OpaqueMetadata};
+use rstd::prelude::*;
 use runtime_primitives::{
-	ApplyResult, transaction_validity::TransactionValidity, Ed25519Signature, generic,
-	traits::{self as runtime_traits, Convert, BlakeTwo256, Block as BlockT, StaticLookup}, create_runtime_str
-};
-use client::{
-	block_builder::api::{CheckInherentsResult, InherentData, self as block_builder_api},
-	runtime_api, impl_runtime_apis
+    create_runtime_str, generic,
+    traits::{self as runtime_traits, BlakeTwo256, Block as BlockT, Convert, StaticLookup},
+    transaction_validity::TransactionValidity,
+    ApplyResult, Ed25519Signature,
 };
-use version::RuntimeVersion;
 #[cfg(feature = "std")]
 use version::NativeVersion;
+use version::RuntimeVersion;
 
 // A few exports that help ease life for downstream crates.
+pub use balances::Call as BalancesCall;
+pub use consensus::Call as ConsensusCall;
 #[cfg(any(feature = "std", test))]
 pub use runtime_primitives::BuildStorage;
-pub use consensus::Call as ConsensusCall;
-pub use timestamp::Call as TimestampCall;
-pub use balances::Call as BalancesCall;
-pub use runtime_primitives::{Permill, Perbill};
+pub use runtime_primitives::{Perbill, Permill};
+pub use srml_support::{construct_runtime, StorageValue};
 pub use timestamp::BlockPeriod;
-pub use srml_support::{StorageValue, construct_runtime};
+pub use timestamp::Call as TimestampCall;
 
 /// Alias to Ed25519 pubkey that identifies an account on the chain.
 pub type AccountId = primitives::H256;
@@ -72,222 +77,219 @@ pub type Nonce = u64;
 /// of data like extrinsics, allowing for them to continue syncing the network through upgrades
 /// to even the core datastructures.
 pub mod opaque {
-	use super::*;
-
-	/// Opaque, encoded, unchecked extrinsic.
-	#[derive(PartialEq, Eq, Clone, Default, Encode, Decode)]
-	#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
-	pub struct UncheckedExtrinsic(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
-	impl runtime_traits::Extrinsic for UncheckedExtrinsic {
-		fn is_signed(&self) -> Option<bool> {
-			None
-		}
-	}
-	/// Opaque block header type.
-	pub type Header = generic::Header<BlockNumber, BlakeTwo256, generic::DigestItem<Hash, Ed25519AuthorityId>>;
-	/// Opaque block type.
-	pub type Block = generic::Block<Header, UncheckedExtrinsic>;
-	/// Opaque block identifier type.
-	pub type BlockId = generic::BlockId<Block>;
-	/// Opaque session key type.
-	pub type SessionKey = Ed25519AuthorityId;
+    use super::*;
+
+    /// Opaque, encoded, unchecked extrinsic.
+    #[derive(PartialEq, Eq, Clone, Default, Encode, Decode)]
+    #[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
+    pub struct UncheckedExtrinsic(#[cfg_attr(feature = "std", serde(with = "bytes"))] pub Vec<u8>);
+    impl runtime_traits::Extrinsic for UncheckedExtrinsic {
+        fn is_signed(&self) -> Option<bool> {
+            None
+        }
+    }
+    /// Opaque block header type.
+    pub type Header =
+        generic::Header<BlockNumber, BlakeTwo256, generic::DigestItem<Hash, Ed25519AuthorityId>>;
+    /// Opaque block type.
+    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
+    /// Opaque block identifier type.
+    pub type BlockId = generic::BlockId<Block>;
+    /// Opaque session key type.
+    pub type SessionKey = Ed25519AuthorityId;
 }
 
 /// This runtime version.
 pub const VERSION: RuntimeVersion = RuntimeVersion {
-	spec_name: create_runtime_str!("joystream-node"),
-	impl_name: create_runtime_str!("joystream-node"),
-	authoring_version: 3,
-	spec_version: 5,
-	impl_version: 0,
-	apis: RUNTIME_API_VERSIONS,
+    spec_name: create_runtime_str!("joystream-node"),
+    impl_name: create_runtime_str!("joystream-node"),
+    authoring_version: 3,
+    spec_version: 5,
+    impl_version: 0,
+    apis: RUNTIME_API_VERSIONS,
 };
 
 /// The version infromation used to identify this runtime when compiled natively.
 #[cfg(feature = "std")]
 pub fn native_version() -> NativeVersion {
-	NativeVersion {
-		runtime_version: VERSION,
-		can_author_with: Default::default(),
-	}
+    NativeVersion {
+        runtime_version: VERSION,
+        can_author_with: Default::default(),
+    }
 }
 
 impl system::Trait for Runtime {
-	/// The identifier used to distinguish between accounts.
-	type AccountId = AccountId;
-	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
-	type Lookup = Indices;
-	/// The index type for storing how many extrinsics an account has signed.
-	type Index = Nonce;
-	/// The index type for blocks.
-	type BlockNumber = BlockNumber;
-	/// The type for hashing blocks and tries.
-	type Hash = Hash;
-	/// The hashing algorithm used.
-	type Hashing = BlakeTwo256;
-	/// The header digest type.
-	type Digest = generic::Digest<Log>;
-	/// The header type.
-	type Header = generic::Header<BlockNumber, BlakeTwo256, Log>;
-	/// The ubiquitous event type.
-	type Event = Event;
-	/// The ubiquitous log type.
-	type Log = Log;
-	/// The ubiquitous origin type.
-	type Origin = Origin;
+    /// The identifier used to distinguish between accounts.
+    type AccountId = AccountId;
+    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
+    type Lookup = Indices;
+    /// The index type for storing how many extrinsics an account has signed.
+    type Index = Nonce;
+    /// The index type for blocks.
+    type BlockNumber = BlockNumber;
+    /// The type for hashing blocks and tries.
+    type Hash = Hash;
+    /// The hashing algorithm used.
+    type Hashing = BlakeTwo256;
+    /// The header digest type.
+    type Digest = generic::Digest<Log>;
+    /// The header type.
+    type Header = generic::Header<BlockNumber, BlakeTwo256, Log>;
+    /// The ubiquitous event type.
+    type Event = Event;
+    /// The ubiquitous log type.
+    type Log = Log;
+    /// The ubiquitous origin type.
+    type Origin = Origin;
 }
 
 impl aura::Trait for Runtime {
-	type HandleReport = aura::StakingSlasher<Runtime>;
+    type HandleReport = aura::StakingSlasher<Runtime>;
 }
 
 impl consensus::Trait for Runtime {
-	/// The identifier we use to refer to authorities.
-	type SessionKey = Ed25519AuthorityId;
-	// The aura module handles offline-reports internally
-	// rather than using an explicit report system.
-	type InherentOfflineReport = ();
-	/// The ubiquitous log type.
-	type Log = Log;
+    /// The identifier we use to refer to authorities.
+    type SessionKey = Ed25519AuthorityId;
+    // The aura module handles offline-reports internally
+    // rather than using an explicit report system.
+    type InherentOfflineReport = ();
+    /// The ubiquitous log type.
+    type Log = Log;
 }
 
 /// Session key conversion.
 pub struct SessionKeyConversion;
 impl Convert<AccountId, Ed25519AuthorityId> for SessionKeyConversion {
-	fn convert(a: AccountId) -> Ed25519AuthorityId {
-		a.to_fixed_bytes().into()
-	}
+    fn convert(a: AccountId) -> Ed25519AuthorityId {
+        a.to_fixed_bytes().into()
+    }
 }
 
 impl session::Trait for Runtime {
-	type ConvertAccountIdToSessionKey = SessionKeyConversion;
-	type OnSessionChange = (Staking, );
-	type Event = Event;
+    type ConvertAccountIdToSessionKey = SessionKeyConversion;
+    type OnSessionChange = (Staking,);
+    type Event = Event;
 }
 
 impl indices::Trait for Runtime {
-	/// The type for recording indexing into the account enumeration. If this ever overflows, there
-	/// will be problems!
-	type AccountIndex = u32;
-	/// Use the standard means of resolving an index hint from an id.
-	type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>;
-	/// Determine whether an account is dead.
-	type IsDeadAccount = Balances;
-	/// The uniquitous event type.
-	type Event = Event;
+    /// The type for recording indexing into the account enumeration. If this ever overflows, there
+    /// will be problems!
+    type AccountIndex = u32;
+    /// Use the standard means of resolving an index hint from an id.
+    type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>;
+    /// Determine whether an account is dead.
+    type IsDeadAccount = Balances;
+    /// The uniquitous event type.
+    type Event = Event;
 }
 
 impl timestamp::Trait for Runtime {
-	/// A timestamp: seconds since the unix epoch.
-	type Moment = u64;
-	type OnTimestampSet = Aura;
+    /// A timestamp: seconds since the unix epoch.
+    type Moment = u64;
+    type OnTimestampSet = Aura;
 }
 
 impl balances::Trait for Runtime {
-	/// The type for recording an account's balance.
-	type Balance = u128;
-	/// What to do if an account's free balance gets zeroed.
-	type OnFreeBalanceZero = Staking;
-	/// What to do if a new account is created.
-	type OnNewAccount = Indices;
-	/// Restrict whether an account can transfer funds. We don't place any further restrictions.
-	type EnsureAccountLiquid = (Staking, Actors);
-	/// The uniquitous event type.
-	type Event = Event;
+    /// The type for recording an account's balance.
+    type Balance = u128;
+    /// What to do if an account's free balance gets zeroed.
+    type OnFreeBalanceZero = Staking;
+    /// What to do if a new account is created.
+    type OnNewAccount = Indices;
+    /// Restrict whether an account can transfer funds. We don't place any further restrictions.
+    type EnsureAccountLiquid = (Staking, Actors);
+    /// The uniquitous event type.
+    type Event = Event;
 }
 
 impl fees::Trait for Runtime {
-	type TransferAsset = Balances;
-	type Event = Event;
+    type TransferAsset = Balances;
+    type Event = Event;
 }
 
 impl sudo::Trait for Runtime {
-	/// The uniquitous event type.
-	type Event = Event;
-	type Proposal = Call;
+    /// The uniquitous event type.
+    type Event = Event;
+    type Proposal = Call;
 }
 
 impl staking::Trait for Runtime {
-	type Currency = balances::Module<Self>;
-	type OnRewardMinted = ();
-	type Event = Event;
+    type Currency = balances::Module<Self>;
+    type OnRewardMinted = ();
+    type Event = Event;
 }
 
 impl governance::GovernanceCurrency for Runtime {
-	type Currency = balances::Module<Self>;
+    type Currency = balances::Module<Self>;
 }
 
 impl governance::proposals::Trait for Runtime {
-	type Event = Event;
-	type Members = Members;
+    type Event = Event;
+    type Members = Members;
 }
 
 impl governance::election::Trait for Runtime {
-	type Event = Event;
-	type CouncilElected = (Council,);
-	type Members = Members;
+    type Event = Event;
+    type CouncilElected = (Council,);
+    type Members = Members;
 }
 
 impl governance::council::Trait for Runtime {
-	type Event = Event;
-	type CouncilTermEnded = (CouncilElection,);
+    type Event = Event;
+    type CouncilTermEnded = (CouncilElection,);
 }
 
 impl memo::Trait for Runtime {
-	type Event = Event;
+    type Event = Event;
 }
 
 impl storage::data_object_type_registry::Trait for Runtime {
-	type Event = Event;
-	type DataObjectTypeId = u64;
+    type Event = Event;
+    type DataObjectTypeId = u64;
 }
 
-impl storage::data_directory::Trait for Runtime
-{
-	type Event = Event;
-	type ContentId = ContentId;
-	type Members = Members;
-	type IsActiveDataObjectType = DataObjectTypeRegistry;
+impl storage::data_directory::Trait for Runtime {
+    type Event = Event;
+    type ContentId = ContentId;
+    type Members = Members;
+    type IsActiveDataObjectType = DataObjectTypeRegistry;
 }
 
-impl storage::downloads::Trait for Runtime
-{
-	type Event = Event;
-	type DownloadSessionId = u64;
-	type ContentHasStorage = DataObjectStorageRegistry;
+impl storage::downloads::Trait for Runtime {
+    type Event = Event;
+    type DownloadSessionId = u64;
+    type ContentHasStorage = DataObjectStorageRegistry;
 }
 
-impl storage::data_object_storage_registry::Trait for Runtime
-{
-	type Event = Event;
-	type DataObjectStorageRelationshipId = u64;
-	type Members = Members;
-	type ContentIdExists = DataDirectory;
+impl storage::data_object_storage_registry::Trait for Runtime {
+    type Event = Event;
+    type DataObjectStorageRelationshipId = u64;
+    type Members = Members;
+    type ContentIdExists = DataDirectory;
 }
 
-impl storage::content_directory::Trait for Runtime
-{
-	type Event = Event;
-	type MetadataId = u64;
-	type SchemaId = u64;
-	type Members = Members;
+impl storage::content_directory::Trait for Runtime {
+    type Event = Event;
+    type MetadataId = u64;
+    type SchemaId = u64;
+    type Members = Members;
 }
 
 impl members::Trait for Runtime {
-	type Event = Event;
-	type MemberId = u64;
-	type PaidTermId = u64;
-	type SubscriptionId = u64;
-	type Roles = Actors;
+    type Event = Event;
+    type MemberId = u64;
+    type PaidTermId = u64;
+    type SubscriptionId = u64;
+    type Roles = Actors;
 }
 
 impl migration::Trait for Runtime {
-	type Event = Event;
+    type Event = Event;
 }
 
 impl actors::Trait for Runtime {
-	type Event = Event;
-	type Members = Members;
+    type Event = Event;
+    type Members = Members;
 }
 
 construct_runtime!(
@@ -332,7 +334,8 @@ pub type Block = generic::Block<Header, UncheckedExtrinsic>;
 /// BlockId type as expected by this runtime.
 pub type BlockId = generic::BlockId<Block>;
 /// Unchecked extrinsic type as expected by this runtime.
-pub type UncheckedExtrinsic = generic::UncheckedMortalCompactExtrinsic<Address, Nonce, Call, Ed25519Signature>;
+pub type UncheckedExtrinsic =
+    generic::UncheckedMortalCompactExtrinsic<Address, Nonce, Call, Ed25519Signature>;
 /// Extrinsic type that has already been checked.
 pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Nonce, Call>;
 /// Executive: handles dispatch to the various modules.
@@ -340,61 +343,61 @@ pub type Executive = executive::Executive<Runtime, Block, Context, Fees, AllModu
 
 // Implement our runtime API endpoints. This is just a bunch of proxying.
 impl_runtime_apis! {
-	impl runtime_api::Core<Block> for Runtime {
-		fn version() -> RuntimeVersion {
-			VERSION
-		}
-
-		fn authorities() -> Vec<Ed25519AuthorityId> {
-			Consensus::authorities()
-		}
-
-		fn execute_block(block: Block) {
-			Executive::execute_block(block)
-		}
-
-		fn initialise_block(header: &<Block as BlockT>::Header) {
-			Executive::initialise_block(header)
-		}
-	}
-
-	impl runtime_api::Metadata<Block> for Runtime {
-		fn metadata() -> OpaqueMetadata {
-			Runtime::metadata().into()
-		}
-	}
-
-	impl block_builder_api::BlockBuilder<Block> for Runtime {
-		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult {
-			Executive::apply_extrinsic(extrinsic)
-		}
-
-		fn finalise_block() -> <Block as BlockT>::Header {
-			Executive::finalise_block()
-		}
-
-		fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
-			data.create_extrinsics()
-		}
-
-		fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult {
-			data.check_extrinsics(&block)
-		}
-
-		fn random_seed() -> <Block as BlockT>::Hash {
-			System::random_seed()
-		}
-	}
-
-	impl runtime_api::TaggedTransactionQueue<Block> for Runtime {
-		fn validate_transaction(tx: <Block as BlockT>::Extrinsic) -> TransactionValidity {
-			Executive::validate_transaction(tx)
-		}
-	}
-
-	impl consensus_aura::AuraApi<Block> for Runtime {
-		fn slot_duration() -> u64 {
-			Aura::slot_duration()
-		}
-	}
+    impl runtime_api::Core<Block> for Runtime {
+        fn version() -> RuntimeVersion {
+            VERSION
+        }
+
+        fn authorities() -> Vec<Ed25519AuthorityId> {
+            Consensus::authorities()
+        }
+
+        fn execute_block(block: Block) {
+            Executive::execute_block(block)
+        }
+
+        fn initialise_block(header: &<Block as BlockT>::Header) {
+            Executive::initialise_block(header)
+        }
+    }
+
+    impl runtime_api::Metadata<Block> for Runtime {
+        fn metadata() -> OpaqueMetadata {
+            Runtime::metadata().into()
+        }
+    }
+
+    impl block_builder_api::BlockBuilder<Block> for Runtime {
+        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult {
+            Executive::apply_extrinsic(extrinsic)
+        }
+
+        fn finalise_block() -> <Block as BlockT>::Header {
+            Executive::finalise_block()
+        }
+
+        fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
+            data.create_extrinsics()
+        }
+
+        fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult {
+            data.check_extrinsics(&block)
+        }
+
+        fn random_seed() -> <Block as BlockT>::Hash {
+            System::random_seed()
+        }
+    }
+
+    impl runtime_api::TaggedTransactionQueue<Block> for Runtime {
+        fn validate_transaction(tx: <Block as BlockT>::Extrinsic) -> TransactionValidity {
+            Executive::validate_transaction(tx)
+        }
+    }
+
+    impl consensus_aura::AuraApi<Block> for Runtime {
+        fn slot_duration() -> u64 {
+            Aura::slot_duration()
+        }
+    }
 }

+ 90 - 36
src/membership/members.rs

@@ -1,27 +1,53 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
-use rstd::prelude::*;
+use crate::governance::{BalanceOf, GovernanceCurrency};
+use crate::traits::{Members, Roles};
 use parity_codec::Codec;
-use parity_codec_derive::{Encode, Decode};
-use srml_support::{StorageMap, StorageValue, dispatch, decl_module, decl_storage, decl_event, ensure, Parameter};
-use srml_support::traits::{Currency};
-use runtime_primitives::traits::{SimpleArithmetic, As, Member, MaybeSerializeDebug};
+use parity_codec_derive::{Decode, Encode};
+use rstd::prelude::*;
+use runtime_primitives::traits::{As, MaybeSerializeDebug, Member, SimpleArithmetic};
+use srml_support::traits::Currency;
+use srml_support::{
+    decl_event, decl_module, decl_storage, dispatch, ensure, Parameter, StorageMap, StorageValue,
+};
 use system::{self, ensure_signed};
-use crate::governance::{GovernanceCurrency, BalanceOf };
-use {timestamp};
-use crate::traits::{Members, Roles};
+use timestamp;
 
 pub trait Trait: system::Trait + GovernanceCurrency + timestamp::Trait {
     type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
 
-    type MemberId: Parameter + Member + SimpleArithmetic + Codec + Default + Copy
-        + As<usize> + As<u64> + MaybeSerializeDebug + PartialEq;
-
-    type PaidTermId: Parameter + Member + SimpleArithmetic + Codec + Default + Copy
-        + As<usize> + As<u64> + MaybeSerializeDebug + PartialEq;
-
-    type SubscriptionId: Parameter + Member + SimpleArithmetic + Codec + Default + Copy
-        + As<usize> + As<u64> + MaybeSerializeDebug + PartialEq;
+    type MemberId: Parameter
+        + Member
+        + SimpleArithmetic
+        + Codec
+        + Default
+        + Copy
+        + As<usize>
+        + As<u64>
+        + MaybeSerializeDebug
+        + PartialEq;
+
+    type PaidTermId: Parameter
+        + Member
+        + SimpleArithmetic
+        + Codec
+        + Default
+        + Copy
+        + As<usize>
+        + As<u64>
+        + MaybeSerializeDebug
+        + PartialEq;
+
+    type SubscriptionId: Parameter
+        + Member
+        + SimpleArithmetic
+        + Codec
+        + Default
+        + Copy
+        + As<usize>
+        + As<u64>
+        + MaybeSerializeDebug
+        + PartialEq;
 
     type Roles: Roles<Self>;
 }
@@ -84,7 +110,7 @@ pub struct PaidMembershipTerms<T: Trait> {
     /// Quantity of native tokens which must be provably burned
     pub fee: BalanceOf<T>,
     /// String of capped length describing human readable conditions which are being agreed upon
-    pub text: Vec<u8>
+    pub text: Vec<u8>,
 }
 
 impl<T: Trait> Default for PaidMembershipTerms<T> {
@@ -92,7 +118,7 @@ impl<T: Trait> Default for PaidMembershipTerms<T> {
         PaidMembershipTerms {
             id: T::PaidTermId::sa(DEFAULT_PAID_TERM_ID),
             fee: BalanceOf::<T>::sa(DEFAULT_PAID_TERM_FEE),
-            text: DEFAULT_PAID_TERM_TEXT.as_bytes().to_vec()
+            text: DEFAULT_PAID_TERM_TEXT.as_bytes().to_vec(),
         }
     }
 }
@@ -179,11 +205,9 @@ impl<T: Trait> Members<T> for Module<T> {
     type Id = T::MemberId;
 
     fn is_active_member(who: &T::AccountId) -> bool {
-        match Self::ensure_is_member(who)
-            .and_then(|member_id| Self::ensure_profile(member_id))
-        {
+        match Self::ensure_is_member(who).and_then(|member_id| Self::ensure_profile(member_id)) {
             Ok(profile) => !profile.suspended,
-            Err(_err) => false
+            Err(_err) => false,
         }
     }
 
@@ -310,18 +334,25 @@ decl_module! {
 
 impl<T: Trait> Module<T> {
     fn ensure_not_member(who: &T::AccountId) -> dispatch::Result {
-        ensure!(!<MemberIdByAccountId<T>>::exists(who), "account already associated with a membership");
+        ensure!(
+            !<MemberIdByAccountId<T>>::exists(who),
+            "account already associated with a membership"
+        );
         Ok(())
     }
 
     pub fn ensure_is_member(who: &T::AccountId) -> Result<T::MemberId, &'static str> {
-        let member_id = Self::member_id_by_account_id(who).ok_or("no member id found for accountid")?;
+        let member_id =
+            Self::member_id_by_account_id(who).ok_or("no member id found for accountid")?;
         Ok(member_id)
     }
 
     fn ensure_is_member_primary_account(who: T::AccountId) -> Result<T::MemberId, &'static str> {
         let member_id = Self::ensure_is_member(&who)?;
-        ensure!(Self::account_id_by_member_id(member_id) == who, "not primary account");
+        ensure!(
+            Self::account_id_by_member_id(member_id) == who,
+            "not primary account"
+        );
         Ok(member_id)
     }
 
@@ -330,21 +361,33 @@ impl<T: Trait> Module<T> {
         Ok(profile)
     }
 
-    fn ensure_active_terms_id(terms_id: T::PaidTermId) -> Result<PaidMembershipTerms<T>, &'static str> {
+    fn ensure_active_terms_id(
+        terms_id: T::PaidTermId,
+    ) -> Result<PaidMembershipTerms<T>, &'static str> {
         let active_terms = Self::active_paid_membership_terms();
-        ensure!(active_terms.iter().any(|&id| id == terms_id), "paid terms id not active");
-        let terms = Self::paid_membership_terms_by_id(terms_id).ok_or("paid membership term id does not exist")?;
+        ensure!(
+            active_terms.iter().any(|&id| id == terms_id),
+            "paid terms id not active"
+        );
+        let terms = Self::paid_membership_terms_by_id(terms_id)
+            .ok_or("paid membership term id does not exist")?;
         Ok(terms)
     }
 
-    fn ensure_unique_handle(handle: &Vec<u8> ) -> dispatch::Result {
+    fn ensure_unique_handle(handle: &Vec<u8>) -> dispatch::Result {
         ensure!(!<Handles<T>>::exists(handle), "handle already registered");
         Ok(())
     }
 
     fn validate_handle(handle: &Vec<u8>) -> dispatch::Result {
-        ensure!(handle.len() >= Self::min_handle_length() as usize, "handle too short");
-        ensure!(handle.len() <= Self::max_handle_length() as usize, "handle too long");
+        ensure!(
+            handle.len() >= Self::min_handle_length() as usize,
+            "handle too short"
+        );
+        ensure!(
+            handle.len() <= Self::max_handle_length() as usize,
+            "handle too long"
+        );
         Ok(())
     }
 
@@ -355,14 +398,19 @@ impl<T: Trait> Module<T> {
     }
 
     fn validate_avatar(uri: &Vec<u8>) -> dispatch::Result {
-        ensure!(uri.len() <= Self::max_avatar_uri_length() as usize, "avatar uri too long");
+        ensure!(
+            uri.len() <= Self::max_avatar_uri_length() as usize,
+            "avatar uri too long"
+        );
         Ok(())
     }
 
     /// Basic user input validation
     fn check_user_registration_info(user_info: UserInfo) -> Result<CheckedUserInfo, &'static str> {
         // Handle is required during registration
-        let handle = user_info.handle.ok_or("handle must be provided during registration")?;
+        let handle = user_info
+            .handle
+            .ok_or("handle must be provided during registration")?;
         Self::validate_handle(&handle)?;
 
         let about = Self::validate_text(&user_info.about.unwrap_or_default());
@@ -377,7 +425,11 @@ impl<T: Trait> Module<T> {
     }
 
     // Mutating methods
-    fn insert_member(who: &T::AccountId, user_info: &CheckedUserInfo, entry_method: EntryMethod<T>) -> T::MemberId {
+    fn insert_member(
+        who: &T::AccountId,
+        user_info: &CheckedUserInfo,
+        entry_method: EntryMethod<T>,
+    ) -> T::MemberId {
         let new_member_id = Self::next_member_id();
 
         let profile: Profile<T> = Profile {
@@ -396,12 +448,14 @@ impl<T: Trait> Module<T> {
         <AccountIdByMemberId<T>>::insert(new_member_id, who.clone());
         <MemberProfile<T>>::insert(new_member_id, profile);
         <Handles<T>>::insert(user_info.handle.clone(), new_member_id);
-        <NextMemberId<T>>::mutate(|n| { *n += T::MemberId::sa(1); });
+        <NextMemberId<T>>::mutate(|n| {
+            *n += T::MemberId::sa(1);
+        });
 
         new_member_id
     }
 
-    fn _change_member_about_text (id: T::MemberId, text: &Vec<u8>) -> dispatch::Result {
+    fn _change_member_about_text(id: T::MemberId, text: &Vec<u8>) -> dispatch::Result {
         let mut profile = Self::ensure_profile(id)?;
         let text = Self::validate_text(text);
         profile.about = text;

+ 35 - 27
src/membership/mock.rs

@@ -1,14 +1,14 @@
 #![cfg(test)]
 
-pub use crate::governance::{GovernanceCurrency};
-pub use super::{members};
+pub use super::members;
+pub use crate::governance::GovernanceCurrency;
 pub use system;
 
-pub use primitives::{H256, Blake2Hasher};
+pub use primitives::{Blake2Hasher, H256};
 pub use runtime_primitives::{
+    testing::{Digest, DigestItem, Header, UintAuthorityId},
+    traits::{BlakeTwo256, IdentityLookup, OnFinalise},
     BuildStorage,
-    traits::{BlakeTwo256, OnFinalise, IdentityLookup},
-    testing::{Digest, DigestItem, Header, UintAuthorityId}
 };
 
 use srml_support::impl_outer_origin;
@@ -77,34 +77,42 @@ impl members::Trait for Test {
 }
 
 pub struct ExtBuilder {
-	first_member_id: u32,
-	default_paid_membership_fee: u32,
+    first_member_id: u32,
+    default_paid_membership_fee: u32,
 }
 impl Default for ExtBuilder {
-	fn default() -> Self {
-		Self {
-			first_member_id: 1,
-			default_paid_membership_fee: 100,
-		}
-	}
+    fn default() -> Self {
+        Self {
+            first_member_id: 1,
+            default_paid_membership_fee: 100,
+        }
+    }
 }
 
 impl ExtBuilder {
-	pub fn first_member_id(mut self, first_member_id: u32) -> Self {
-		self.first_member_id = first_member_id;
-		self
-	}
-	pub fn default_paid_membership_fee(mut self, default_paid_membership_fee: u32) -> Self {
-		self.default_paid_membership_fee = default_paid_membership_fee;
-		self
-	}
+    pub fn first_member_id(mut self, first_member_id: u32) -> Self {
+        self.first_member_id = first_member_id;
+        self
+    }
+    pub fn default_paid_membership_fee(mut self, default_paid_membership_fee: u32) -> Self {
+        self.default_paid_membership_fee = default_paid_membership_fee;
+        self
+    }
     pub fn build(self) -> runtime_io::TestExternalities<Blake2Hasher> {
-        let mut t = system::GenesisConfig::<Test>::default().build_storage().unwrap().0;
-
-        t.extend(members::GenesisConfig::<Test>{
-            first_member_id: self.first_member_id,
-            default_paid_membership_fee: self.default_paid_membership_fee,
-        }.build_storage().unwrap().0);
+        let mut t = system::GenesisConfig::<Test>::default()
+            .build_storage()
+            .unwrap()
+            .0;
+
+        t.extend(
+            members::GenesisConfig::<Test> {
+                first_member_id: self.first_member_id,
+                default_paid_membership_fee: self.default_paid_membership_fee,
+            }
+            .build_storage()
+            .unwrap()
+            .0,
+        );
 
         t.into()
     }

+ 1 - 1
src/membership/mod.rs

@@ -3,4 +3,4 @@
 pub mod members;
 
 mod mock;
-mod tests;
+mod tests;

+ 166 - 106
src/membership/tests.rs

@@ -1,6 +1,5 @@
 #![cfg(test)]
 
-use super::*;
 use super::mock::*;
 
 use runtime_io::with_externalities;
@@ -8,15 +7,22 @@ use srml_support::*;
 
 fn assert_ok_unwrap<T>(value: Option<T>, err: &'static str) -> T {
     match value {
-        None => { assert!(false, err); value.unwrap() },
-        Some(v) => v
+        None => {
+            assert!(false, err);
+            value.unwrap()
+        }
+        Some(v) => v,
     }
 }
 
 fn get_alice_info() -> members::UserInfo {
     members::UserInfo {
         handle: Some(String::from("alice").as_bytes().to_vec()),
-        avatar_uri: Some(String::from("http://avatar-url.com/alice").as_bytes().to_vec()),
+        avatar_uri: Some(
+            String::from("http://avatar-url.com/alice")
+                .as_bytes()
+                .to_vec(),
+        ),
         about: Some(String::from("my name is alice").as_bytes().to_vec()),
     }
 }
@@ -24,7 +30,11 @@ fn get_alice_info() -> members::UserInfo {
 fn get_bob_info() -> members::UserInfo {
     members::UserInfo {
         handle: Some(String::from("bobby").as_bytes().to_vec()),
-        avatar_uri: Some(String::from("http://avatar-url.com/bob").as_bytes().to_vec()),
+        avatar_uri: Some(
+            String::from("http://avatar-url.com/bob")
+                .as_bytes()
+                .to_vec(),
+        ),
         about: Some(String::from("my name is bob").as_bytes().to_vec()),
     }
 }
@@ -33,7 +43,11 @@ const ALICE_ACCOUNT_ID: u64 = 1;
 const DEFAULT_TERMS_ID: u32 = 0;
 
 fn buy_default_membership_as_alice() -> dispatch::Result {
-    Members::buy_membership(Origin::signed(ALICE_ACCOUNT_ID), DEFAULT_TERMS_ID, get_alice_info())
+    Members::buy_membership(
+        Origin::signed(ALICE_ACCOUNT_ID),
+        DEFAULT_TERMS_ID,
+        get_alice_info(),
+    )
 }
 
 fn set_alice_free_balance(balance: u32) {
@@ -45,18 +59,24 @@ fn initial_state() {
     const DEFAULT_FEE: u32 = 500;
     const DEFAULT_FIRST_ID: u32 = 1000;
 
-    with_externalities(&mut ExtBuilder::default()
-        .default_paid_membership_fee(DEFAULT_FEE)
-        .first_member_id(DEFAULT_FIRST_ID).build(), ||
-    {
-        assert_eq!(Members::first_member_id(), DEFAULT_FIRST_ID);
-        assert_eq!(Members::next_member_id(), DEFAULT_FIRST_ID);
-
-        let default_terms = assert_ok_unwrap(Members::paid_membership_terms_by_id(DEFAULT_TERMS_ID), "default terms not initialized");
-
-        assert_eq!(default_terms.id, DEFAULT_TERMS_ID);
-        assert_eq!(default_terms.fee, DEFAULT_FEE);
-    });
+    with_externalities(
+        &mut ExtBuilder::default()
+            .default_paid_membership_fee(DEFAULT_FEE)
+            .first_member_id(DEFAULT_FIRST_ID)
+            .build(),
+        || {
+            assert_eq!(Members::first_member_id(), DEFAULT_FIRST_ID);
+            assert_eq!(Members::next_member_id(), DEFAULT_FIRST_ID);
+
+            let default_terms = assert_ok_unwrap(
+                Members::paid_membership_terms_by_id(DEFAULT_TERMS_ID),
+                "default terms not initialized",
+            );
+
+            assert_eq!(default_terms.id, DEFAULT_TERMS_ID);
+            assert_eq!(default_terms.fee, DEFAULT_FEE);
+        },
+    );
 }
 
 #[test]
@@ -65,56 +85,70 @@ fn buy_membership() {
     const DEFAULT_FIRST_ID: u32 = 1000;
     const SURPLUS_BALANCE: u32 = 500;
 
-    with_externalities(&mut ExtBuilder::default()
-        .default_paid_membership_fee(DEFAULT_FEE)
-        .first_member_id(DEFAULT_FIRST_ID).build(), ||
-    {
-        let initial_balance = DEFAULT_FEE + SURPLUS_BALANCE;
-        set_alice_free_balance(initial_balance);
-
-        assert_ok!(buy_default_membership_as_alice());
-
-        let member_id = assert_ok_unwrap(Members::member_id_by_account_id(&ALICE_ACCOUNT_ID), "member id not assigned");
-
-        let profile = assert_ok_unwrap(Members::member_profile(&member_id), "member profile not created");
-
-        assert_eq!(Some(profile.handle), get_alice_info().handle);
-        assert_eq!(Some(profile.avatar_uri), get_alice_info().avatar_uri);
-        assert_eq!(Some(profile.about), get_alice_info().about);
-
-        assert_eq!(Balances::free_balance(&ALICE_ACCOUNT_ID), SURPLUS_BALANCE);
-
-    });
+    with_externalities(
+        &mut ExtBuilder::default()
+            .default_paid_membership_fee(DEFAULT_FEE)
+            .first_member_id(DEFAULT_FIRST_ID)
+            .build(),
+        || {
+            let initial_balance = DEFAULT_FEE + SURPLUS_BALANCE;
+            set_alice_free_balance(initial_balance);
+
+            assert_ok!(buy_default_membership_as_alice());
+
+            let member_id = assert_ok_unwrap(
+                Members::member_id_by_account_id(&ALICE_ACCOUNT_ID),
+                "member id not assigned",
+            );
+
+            let profile = assert_ok_unwrap(
+                Members::member_profile(&member_id),
+                "member profile not created",
+            );
+
+            assert_eq!(Some(profile.handle), get_alice_info().handle);
+            assert_eq!(Some(profile.avatar_uri), get_alice_info().avatar_uri);
+            assert_eq!(Some(profile.about), get_alice_info().about);
+
+            assert_eq!(Balances::free_balance(&ALICE_ACCOUNT_ID), SURPLUS_BALANCE);
+        },
+    );
 }
 
 #[test]
 fn buy_membership_fails_without_enough_balance() {
     const DEFAULT_FEE: u32 = 500;
 
-    with_externalities(&mut ExtBuilder::default()
-        .default_paid_membership_fee(DEFAULT_FEE).build(), ||
-    {
-        let initial_balance = DEFAULT_FEE - 1;
-        set_alice_free_balance(initial_balance);
-
-        assert!(buy_default_membership_as_alice().is_err());
-    });
+    with_externalities(
+        &mut ExtBuilder::default()
+            .default_paid_membership_fee(DEFAULT_FEE)
+            .build(),
+        || {
+            let initial_balance = DEFAULT_FEE - 1;
+            set_alice_free_balance(initial_balance);
+
+            assert!(buy_default_membership_as_alice().is_err());
+        },
+    );
 }
 
 #[test]
 fn new_memberships_allowed_flag() {
     const DEFAULT_FEE: u32 = 500;
 
-    with_externalities(&mut ExtBuilder::default()
-        .default_paid_membership_fee(DEFAULT_FEE).build(), ||
-    {
-        let initial_balance = DEFAULT_FEE + 1;
-        set_alice_free_balance(initial_balance);
+    with_externalities(
+        &mut ExtBuilder::default()
+            .default_paid_membership_fee(DEFAULT_FEE)
+            .build(),
+        || {
+            let initial_balance = DEFAULT_FEE + 1;
+            set_alice_free_balance(initial_balance);
 
-        <members::NewMembershipsAllowed<Test>>::put(false);
+            <members::NewMembershipsAllowed<Test>>::put(false);
 
-        assert!(buy_default_membership_as_alice().is_err());
-    });
+            assert!(buy_default_membership_as_alice().is_err());
+        },
+    );
 }
 
 #[test]
@@ -122,19 +156,21 @@ fn account_cannot_create_multiple_memberships() {
     const DEFAULT_FEE: u32 = 500;
     const SURPLUS_BALANCE: u32 = 500;
 
-    with_externalities(&mut ExtBuilder::default()
-        .default_paid_membership_fee(DEFAULT_FEE).build(), ||
-    {
-        let initial_balance = DEFAULT_FEE + SURPLUS_BALANCE;
-        set_alice_free_balance(initial_balance);
-
-        // First time it works
-        assert_ok!(buy_default_membership_as_alice());
-
-        // second attempt should fail
-        assert!(buy_default_membership_as_alice().is_err());
-
-    });
+    with_externalities(
+        &mut ExtBuilder::default()
+            .default_paid_membership_fee(DEFAULT_FEE)
+            .build(),
+        || {
+            let initial_balance = DEFAULT_FEE + SURPLUS_BALANCE;
+            set_alice_free_balance(initial_balance);
+
+            // First time it works
+            assert_ok!(buy_default_membership_as_alice());
+
+            // second attempt should fail
+            assert!(buy_default_membership_as_alice().is_err());
+        },
+    );
 }
 
 #[test]
@@ -142,19 +178,21 @@ fn unique_handles() {
     const DEFAULT_FEE: u32 = 500;
     const SURPLUS_BALANCE: u32 = 500;
 
-    with_externalities(&mut ExtBuilder::default()
-        .default_paid_membership_fee(DEFAULT_FEE).build(), ||
-    {
-        let initial_balance = DEFAULT_FEE + SURPLUS_BALANCE;
-        set_alice_free_balance(initial_balance);
-
-        // alice's handle already taken
-        <members::Handles<Test>>::insert(get_alice_info().handle.unwrap(), 1);
-
-        // should not be allowed to buy membership with that handle
-        assert!(buy_default_membership_as_alice().is_err());
-
-    });
+    with_externalities(
+        &mut ExtBuilder::default()
+            .default_paid_membership_fee(DEFAULT_FEE)
+            .build(),
+        || {
+            let initial_balance = DEFAULT_FEE + SURPLUS_BALANCE;
+            set_alice_free_balance(initial_balance);
+
+            // alice's handle already taken
+            <members::Handles<Test>>::insert(get_alice_info().handle.unwrap(), 1);
+
+            // should not be allowed to buy membership with that handle
+            assert!(buy_default_membership_as_alice().is_err());
+        },
+    );
 }
 
 #[test]
@@ -162,44 +200,66 @@ fn update_profile() {
     const DEFAULT_FEE: u32 = 500;
     const SURPLUS_BALANCE: u32 = 500;
 
-    with_externalities(&mut ExtBuilder::default()
-        .default_paid_membership_fee(DEFAULT_FEE).build(), ||
-    {
-        let initial_balance = DEFAULT_FEE + SURPLUS_BALANCE;
-        set_alice_free_balance(initial_balance);
-
-        assert_ok!(buy_default_membership_as_alice());
-
-        assert_ok!(Members::update_profile(Origin::signed(ALICE_ACCOUNT_ID), get_bob_info()));
-
-        let member_id = assert_ok_unwrap(Members::member_id_by_account_id(&ALICE_ACCOUNT_ID), "member id not assigned");
-
-        let profile = assert_ok_unwrap(Members::member_profile(&member_id), "member profile created");
-
-        assert_eq!(Some(profile.handle), get_bob_info().handle);
-        assert_eq!(Some(profile.avatar_uri), get_bob_info().avatar_uri);
-        assert_eq!(Some(profile.about), get_bob_info().about);
-
-    });
+    with_externalities(
+        &mut ExtBuilder::default()
+            .default_paid_membership_fee(DEFAULT_FEE)
+            .build(),
+        || {
+            let initial_balance = DEFAULT_FEE + SURPLUS_BALANCE;
+            set_alice_free_balance(initial_balance);
+
+            assert_ok!(buy_default_membership_as_alice());
+
+            assert_ok!(Members::update_profile(
+                Origin::signed(ALICE_ACCOUNT_ID),
+                get_bob_info()
+            ));
+
+            let member_id = assert_ok_unwrap(
+                Members::member_id_by_account_id(&ALICE_ACCOUNT_ID),
+                "member id not assigned",
+            );
+
+            let profile = assert_ok_unwrap(
+                Members::member_profile(&member_id),
+                "member profile created",
+            );
+
+            assert_eq!(Some(profile.handle), get_bob_info().handle);
+            assert_eq!(Some(profile.avatar_uri), get_bob_info().avatar_uri);
+            assert_eq!(Some(profile.about), get_bob_info().about);
+        },
+    );
 }
 
 #[test]
 fn add_screened_member() {
-    with_externalities(&mut ExtBuilder::default().build(), ||
-    {
+    with_externalities(&mut ExtBuilder::default().build(), || {
         let screening_authority = 5;
         <members::ScreeningAuthority<Test>>::put(&screening_authority);
 
-        assert_ok!(Members::add_screened_member(Origin::signed(screening_authority), ALICE_ACCOUNT_ID, get_alice_info()));
+        assert_ok!(Members::add_screened_member(
+            Origin::signed(screening_authority),
+            ALICE_ACCOUNT_ID,
+            get_alice_info()
+        ));
 
-        let member_id = assert_ok_unwrap(Members::member_id_by_account_id(&ALICE_ACCOUNT_ID), "member id not assigned");
+        let member_id = assert_ok_unwrap(
+            Members::member_id_by_account_id(&ALICE_ACCOUNT_ID),
+            "member id not assigned",
+        );
 
-        let profile = assert_ok_unwrap(Members::member_profile(&member_id), "member profile created");
+        let profile = assert_ok_unwrap(
+            Members::member_profile(&member_id),
+            "member profile created",
+        );
 
         assert_eq!(Some(profile.handle), get_alice_info().handle);
         assert_eq!(Some(profile.avatar_uri), get_alice_info().avatar_uri);
         assert_eq!(Some(profile.about), get_alice_info().about);
-        assert_eq!(members::EntryMethod::Screening(screening_authority), profile.entry);
-
+        assert_eq!(
+            members::EntryMethod::Screening(screening_authority),
+            profile.entry
+        );
     });
 }

+ 5 - 5
src/memo.rs

@@ -1,11 +1,11 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
-use srml_support::{StorageMap, decl_module, decl_storage, decl_event, ensure};
-use srml_support::traits::{Currency};
-use runtime_primitives::traits::{Zero};
-use system::{self, ensure_signed};
-use rstd::prelude::*;
 use crate::governance::GovernanceCurrency;
+use rstd::prelude::*;
+use runtime_primitives::traits::Zero;
+use srml_support::traits::Currency;
+use srml_support::{decl_event, decl_module, decl_storage, ensure, StorageMap};
+use system::{self, ensure_signed};
 
 pub trait Trait: system::Trait + GovernanceCurrency {
     type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;

+ 30 - 22
src/migration.rs

@@ -1,14 +1,14 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
-use srml_support::{StorageValue, decl_module, decl_storage, decl_event};
-use system;
-use rstd::prelude::*;
-use runtime_io::print;
-use crate::{VERSION};
+use crate::governance::BalanceOf;
 use crate::membership::members;
 use crate::roles::actors;
-use crate::governance::{BalanceOf};
-use runtime_primitives::traits::{As};
+use crate::VERSION;
+use rstd::prelude::*;
+use runtime_io::print;
+use runtime_primitives::traits::As;
+use srml_support::{decl_event, decl_module, decl_storage, StorageValue};
+use system;
 
 // When preparing a new major runtime release version bump this value to match it and update
 // the initialization code in runtime_initialization(). Because of the way substrate runs runtime code
@@ -19,34 +19,42 @@ const MIGRATION_FOR_SPEC_VERSION: u32 = 5;
 
 impl<T: Trait> Module<T> {
     fn runtime_initialization() {
-        if VERSION.spec_version != MIGRATION_FOR_SPEC_VERSION { return }
+        if VERSION.spec_version != MIGRATION_FOR_SPEC_VERSION {
+            return;
+        }
 
         print("running runtime initializers");
 
         <members::Module<T>>::initialize_storage();
 
         // Initialize Storage provider role parameters
-        <actors::Module<T>>::set_role_parameters(actors::Role::Storage, actors::RoleParameters {
-            min_stake: BalanceOf::<T>::sa(3000),
-            max_actors: 10,
-            reward: BalanceOf::<T>::sa(10),
-            reward_period: T::BlockNumber::sa(600),
-            unbonding_period: T::BlockNumber::sa(600),
-            entry_request_fee: BalanceOf::<T>::sa(50),
+        <actors::Module<T>>::set_role_parameters(
+            actors::Role::Storage,
+            actors::RoleParameters {
+                min_stake: BalanceOf::<T>::sa(3000),
+                max_actors: 10,
+                reward: BalanceOf::<T>::sa(10),
+                reward_period: T::BlockNumber::sa(600),
+                unbonding_period: T::BlockNumber::sa(600),
+                entry_request_fee: BalanceOf::<T>::sa(50),
 
-            // not currently used
-            min_actors: 5,
-            bonding_period: T::BlockNumber::sa(600),
-            min_service_period: T::BlockNumber::sa(600),
-            startup_grace_period: T::BlockNumber::sa(600),
-        });
+                // not currently used
+                min_actors: 5,
+                bonding_period: T::BlockNumber::sa(600),
+                min_service_period: T::BlockNumber::sa(600),
+                startup_grace_period: T::BlockNumber::sa(600),
+            },
+        );
         <actors::Module<T>>::set_available_roles(vec![actors::Role::Storage]);
 
         // ...
         // add initialization of other modules introduced in this runtime
         // ...
 
-        Self::deposit_event(RawEvent::Migrated(<system::Module<T>>::block_number(), VERSION.spec_version));
+        Self::deposit_event(RawEvent::Migrated(
+            <system::Module<T>>::block_number(),
+            VERSION.spec_version,
+        ));
     }
 }
 

+ 7 - 4
src/roles/actors.rs

@@ -3,9 +3,7 @@
 use crate::governance::{BalanceOf, GovernanceCurrency};
 use parity_codec_derive::{Decode, Encode};
 use rstd::prelude::*;
-use runtime_primitives::traits::{
-    As, Bounded, MaybeDebug, Zero,
-};
+use runtime_primitives::traits::{As, Bounded, MaybeDebug, Zero};
 use srml_support::traits::{Currency, EnsureAccountLiquid};
 use srml_support::{
     decl_event, decl_module, decl_storage, dispatch, ensure, StorageMap, StorageValue,
@@ -72,7 +70,12 @@ pub trait Trait: system::Trait + GovernanceCurrency + MaybeDebug {
 
 pub type MemberId<T> = <<T as Trait>::Members as Members<T>>::Id;
 // actor account, memberid, role, expires
-pub type Request<T> = (<T as system::Trait>::AccountId, MemberId<T>, Role, <T as system::Trait>::BlockNumber);
+pub type Request<T> = (
+    <T as system::Trait>::AccountId,
+    MemberId<T>,
+    Role,
+    <T as system::Trait>::BlockNumber,
+);
 pub type Requests<T> = Vec<Request<T>>;
 
 pub const REQUEST_LIFETIME: u64 = 300;

+ 1 - 1
src/storage/mod.rs

@@ -1,9 +1,9 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
+pub mod content_directory;
 pub mod data_directory;
 pub mod data_object_storage_registry;
 pub mod data_object_type_registry;
 pub mod downloads;
-pub mod content_directory;
 
 mod mock;

+ 171 - 123
src/storage/tests.rs

@@ -1,158 +1,206 @@
 #![cfg(test)]
 
-use super::*;
 use super::mock::*;
+use super::*;
 
 use runtime_io::with_externalities;
-use system::{self, Phase, EventRecord};
+use system::{self, EventRecord, Phase};
 
 #[test]
 fn initial_state() {
     const DEFAULT_FIRST_ID: u64 = 1000;
 
-    with_externalities(&mut ExtBuilder::default()
-        .first_data_object_type_id(DEFAULT_FIRST_ID).build(), || {
-        assert_eq!(TestDataObjectTypeRegistry::first_data_object_type_id(), DEFAULT_FIRST_ID);
-    });
+    with_externalities(
+        &mut ExtBuilder::default()
+            .first_data_object_type_id(DEFAULT_FIRST_ID)
+            .build(),
+        || {
+            assert_eq!(
+                TestDataObjectTypeRegistry::first_data_object_type_id(),
+                DEFAULT_FIRST_ID
+            );
+        },
+    );
 }
 
 #[test]
 fn fail_register_without_root() {
     const DEFAULT_FIRST_ID: u64 = 1000;
 
-    with_externalities(&mut ExtBuilder::default()
-        .first_data_object_type_id(DEFAULT_FIRST_ID).build(), || {
-        let data: TestDataObjectType = TestDataObjectType {
-            id: None,
-            description: "foo".as_bytes().to_vec(),
-            active: false,
-        };
-        let res = TestDataObjectTypeRegistry::register_data_object_type(Origin::signed(1), data);
-        assert!(res.is_err());
-    });
+    with_externalities(
+        &mut ExtBuilder::default()
+            .first_data_object_type_id(DEFAULT_FIRST_ID)
+            .build(),
+        || {
+            let data: TestDataObjectType = TestDataObjectType {
+                id: None,
+                description: "foo".as_bytes().to_vec(),
+                active: false,
+            };
+            let res =
+                TestDataObjectTypeRegistry::register_data_object_type(Origin::signed(1), data);
+            assert!(res.is_err());
+        },
+    );
 }
 
 #[test]
 fn succeed_register_as_root() {
     const DEFAULT_FIRST_ID: u64 = 1000;
 
-    with_externalities(&mut ExtBuilder::default()
-        .first_data_object_type_id(DEFAULT_FIRST_ID).build(), || {
-        let data: TestDataObjectType = TestDataObjectType {
-            id: None,
-            description: "foo".as_bytes().to_vec(),
-            active: false,
-        };
-        let res = TestDataObjectTypeRegistry::register_data_object_type(Origin::ROOT, data);
-        assert!(res.is_ok());
-    });
+    with_externalities(
+        &mut ExtBuilder::default()
+            .first_data_object_type_id(DEFAULT_FIRST_ID)
+            .build(),
+        || {
+            let data: TestDataObjectType = TestDataObjectType {
+                id: None,
+                description: "foo".as_bytes().to_vec(),
+                active: false,
+            };
+            let res = TestDataObjectTypeRegistry::register_data_object_type(Origin::ROOT, data);
+            assert!(res.is_ok());
+        },
+    );
 }
 
 #[test]
 fn update_existing() {
     const DEFAULT_FIRST_ID: u64 = 1000;
 
-    with_externalities(&mut ExtBuilder::default()
-        .first_data_object_type_id(DEFAULT_FIRST_ID).build(), || {
-        // First register a type
-        let data: TestDataObjectType = TestDataObjectType {
-            id: None,
-            description: "foo".as_bytes().to_vec(),
-            active: false,
-        };
-        let id_res = TestDataObjectTypeRegistry::register_data_object_type(Origin::ROOT, data);
-        assert!(id_res.is_ok());
-        assert_eq!(*System::events().last().unwrap(),
-            EventRecord {
-                phase: Phase::ApplyExtrinsic(0),
-                event: MetaEvent::data_object_type_registry(data_object_type_registry::RawEvent::DataObjectTypeRegistered(DEFAULT_FIRST_ID)),
-            }
-        );
-
-
-        // Now update it with new data - we need the ID to be the same as in
-        // returned by the previous call. First, though, try and fail without
-        let updated1: TestDataObjectType = TestDataObjectType {
-            id: None,
-            description: "bar".as_bytes().to_vec(),
-            active: false,
-        };
-        let res = TestDataObjectTypeRegistry::update_data_object_type(Origin::ROOT, updated1);
-        assert!(res.is_err());
-
-        // Now try with a bad ID
-        let updated2: TestDataObjectType = TestDataObjectType {
-            id: Some(DEFAULT_FIRST_ID + 1),
-            description: "bar".as_bytes().to_vec(),
-            active: false,
-        };
-        let res = TestDataObjectTypeRegistry::update_data_object_type(Origin::ROOT, updated2);
-        assert!(res.is_err());
-
-        // Finally with an existing ID, it should work.
-        let updated3: TestDataObjectType = TestDataObjectType {
-            id: Some(DEFAULT_FIRST_ID),
-            description: "bar".as_bytes().to_vec(),
-            active: false,
-        };
-        let res = TestDataObjectTypeRegistry::update_data_object_type(Origin::ROOT, updated3);
-        assert!(res.is_ok());
-        assert_eq!(*System::events().last().unwrap(),
-            EventRecord {
-                phase: Phase::ApplyExtrinsic(0),
-                event: MetaEvent::data_object_type_registry(data_object_type_registry::RawEvent::DataObjectTypeUpdated(DEFAULT_FIRST_ID)),
-            }
-        );
-    });
+    with_externalities(
+        &mut ExtBuilder::default()
+            .first_data_object_type_id(DEFAULT_FIRST_ID)
+            .build(),
+        || {
+            // First register a type
+            let data: TestDataObjectType = TestDataObjectType {
+                id: None,
+                description: "foo".as_bytes().to_vec(),
+                active: false,
+            };
+            let id_res = TestDataObjectTypeRegistry::register_data_object_type(Origin::ROOT, data);
+            assert!(id_res.is_ok());
+            assert_eq!(
+                *System::events().last().unwrap(),
+                EventRecord {
+                    phase: Phase::ApplyExtrinsic(0),
+                    event: MetaEvent::data_object_type_registry(
+                        data_object_type_registry::RawEvent::DataObjectTypeRegistered(
+                            DEFAULT_FIRST_ID
+                        )
+                    ),
+                }
+            );
+
+            // Now update it with new data - we need the ID to be the same as in
+            // returned by the previous call. First, though, try and fail without
+            let updated1: TestDataObjectType = TestDataObjectType {
+                id: None,
+                description: "bar".as_bytes().to_vec(),
+                active: false,
+            };
+            let res = TestDataObjectTypeRegistry::update_data_object_type(Origin::ROOT, updated1);
+            assert!(res.is_err());
+
+            // Now try with a bad ID
+            let updated2: TestDataObjectType = TestDataObjectType {
+                id: Some(DEFAULT_FIRST_ID + 1),
+                description: "bar".as_bytes().to_vec(),
+                active: false,
+            };
+            let res = TestDataObjectTypeRegistry::update_data_object_type(Origin::ROOT, updated2);
+            assert!(res.is_err());
+
+            // Finally with an existing ID, it should work.
+            let updated3: TestDataObjectType = TestDataObjectType {
+                id: Some(DEFAULT_FIRST_ID),
+                description: "bar".as_bytes().to_vec(),
+                active: false,
+            };
+            let res = TestDataObjectTypeRegistry::update_data_object_type(Origin::ROOT, updated3);
+            assert!(res.is_ok());
+            assert_eq!(
+                *System::events().last().unwrap(),
+                EventRecord {
+                    phase: Phase::ApplyExtrinsic(0),
+                    event: MetaEvent::data_object_type_registry(
+                        data_object_type_registry::RawEvent::DataObjectTypeUpdated(
+                            DEFAULT_FIRST_ID
+                        )
+                    ),
+                }
+            );
+        },
+    );
 }
 
-
 #[test]
 fn activate_existing() {
     const DEFAULT_FIRST_ID: u64 = 1000;
 
-    with_externalities(&mut ExtBuilder::default()
-        .first_data_object_type_id(DEFAULT_FIRST_ID).build(), || {
-        // First register a type
-        let data: TestDataObjectType = TestDataObjectType {
-            id: None,
-            description: "foo".as_bytes().to_vec(),
-            active: false,
-        };
-        let id_res = TestDataObjectTypeRegistry::register_data_object_type(Origin::ROOT, data);
-        assert!(id_res.is_ok());
-        assert_eq!(*System::events().last().unwrap(),
-            EventRecord {
-                phase: Phase::ApplyExtrinsic(0),
-                event: MetaEvent::data_object_type_registry(data_object_type_registry::RawEvent::DataObjectTypeRegistered(DEFAULT_FIRST_ID)),
-            }
-        );
-
-        // Retrieve, and ensure it's not active.
-        let data = TestDataObjectTypeRegistry::data_object_type(DEFAULT_FIRST_ID);
-        assert!(data.is_some());
-        assert!(!data.unwrap().active);
-
-        // Now activate the data object type
-        let res = TestDataObjectTypeRegistry::activate_data_object_type(Origin::ROOT, DEFAULT_FIRST_ID);
-        assert!(res.is_ok());
-        assert_eq!(*System::events().last().unwrap(),
-            EventRecord {
-                phase: Phase::ApplyExtrinsic(0),
-                event: MetaEvent::data_object_type_registry(data_object_type_registry::RawEvent::DataObjectTypeUpdated(DEFAULT_FIRST_ID)),
-            }
-        );
-
-        // Ensure that the item is actually activated.
-        let data = TestDataObjectTypeRegistry::data_object_type(DEFAULT_FIRST_ID);
-        assert!(data.is_some());
-        assert!(data.unwrap().active);
-
-        // Deactivate again.
-        let res = TestDataObjectTypeRegistry::deactivate_data_object_type(Origin::ROOT, DEFAULT_FIRST_ID);
-        assert!(res.is_ok());
-        let data = TestDataObjectTypeRegistry::data_object_type(DEFAULT_FIRST_ID);
-        assert!(data.is_some());
-        assert!(!data.unwrap().active);
-    });
+    with_externalities(
+        &mut ExtBuilder::default()
+            .first_data_object_type_id(DEFAULT_FIRST_ID)
+            .build(),
+        || {
+            // First register a type
+            let data: TestDataObjectType = TestDataObjectType {
+                id: None,
+                description: "foo".as_bytes().to_vec(),
+                active: false,
+            };
+            let id_res = TestDataObjectTypeRegistry::register_data_object_type(Origin::ROOT, data);
+            assert!(id_res.is_ok());
+            assert_eq!(
+                *System::events().last().unwrap(),
+                EventRecord {
+                    phase: Phase::ApplyExtrinsic(0),
+                    event: MetaEvent::data_object_type_registry(
+                        data_object_type_registry::RawEvent::DataObjectTypeRegistered(
+                            DEFAULT_FIRST_ID
+                        )
+                    ),
+                }
+            );
+
+            // Retrieve, and ensure it's not active.
+            let data = TestDataObjectTypeRegistry::data_object_type(DEFAULT_FIRST_ID);
+            assert!(data.is_some());
+            assert!(!data.unwrap().active);
+
+            // Now activate the data object type
+            let res = TestDataObjectTypeRegistry::activate_data_object_type(
+                Origin::ROOT,
+                DEFAULT_FIRST_ID,
+            );
+            assert!(res.is_ok());
+            assert_eq!(
+                *System::events().last().unwrap(),
+                EventRecord {
+                    phase: Phase::ApplyExtrinsic(0),
+                    event: MetaEvent::data_object_type_registry(
+                        data_object_type_registry::RawEvent::DataObjectTypeUpdated(
+                            DEFAULT_FIRST_ID
+                        )
+                    ),
+                }
+            );
+
+            // Ensure that the item is actually activated.
+            let data = TestDataObjectTypeRegistry::data_object_type(DEFAULT_FIRST_ID);
+            assert!(data.is_some());
+            assert!(data.unwrap().active);
+
+            // Deactivate again.
+            let res = TestDataObjectTypeRegistry::deactivate_data_object_type(
+                Origin::ROOT,
+                DEFAULT_FIRST_ID,
+            );
+            assert!(res.is_ok());
+            let data = TestDataObjectTypeRegistry::data_object_type(DEFAULT_FIRST_ID);
+            assert!(data.is_some());
+            assert!(!data.unwrap().active);
+        },
+    );
 }

+ 16 - 6
src/traits.rs

@@ -1,15 +1,23 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
 use crate::storage::{data_directory, data_object_storage_registry, data_object_type_registry};
-use system;
 use parity_codec::Codec;
-use srml_support::{Parameter};
-use runtime_primitives::traits::{SimpleArithmetic, As, Member, MaybeSerializeDebug};
+use runtime_primitives::traits::{As, MaybeSerializeDebug, Member, SimpleArithmetic};
+use srml_support::Parameter;
+use system;
 
 // Members
 pub trait Members<T: system::Trait> {
-    type Id : Parameter + Member + SimpleArithmetic + Codec + Default + Copy
-        + As<usize> + As<u64> + MaybeSerializeDebug + PartialEq;
+    type Id: Parameter
+        + Member
+        + SimpleArithmetic
+        + Codec
+        + Default
+        + Copy
+        + As<usize>
+        + As<u64>
+        + MaybeSerializeDebug
+        + PartialEq;
 
     fn is_active_member(account_id: &T::AccountId) -> bool;
 
@@ -37,7 +45,9 @@ pub trait Roles<T: system::Trait> {
 }
 
 impl<T: system::Trait> Roles<T> for () {
-	fn is_role_account(_who: &T::AccountId) -> bool { false }
+    fn is_role_account(_who: &T::AccountId) -> bool {
+        false
+    }
 }
 
 // Storage

Some files were not shown because too many files changed in this diff