Browse Source

Merge branch 'nicaea' into fix-followin-working-group-refactor-dropping-actors-module

Mokhtar Naamani 4 years ago
parent
commit
d1e0505968
53 changed files with 842 additions and 2205 deletions
  1. 27 53
      Cargo.lock
  2. 1 2
      Cargo.toml
  3. 1 1
      node/Cargo.toml
  4. 23 24
      node/src/chain_spec.rs
  5. 2 2
      node/src/forum_config/from_serialized.rs
  6. 1 1
      node/src/forum_config/mod.rs
  7. 1 1
      node/src/service.rs
  8. 8 3
      runtime-modules/common/src/constraints.rs
  9. 1 1
      runtime-modules/content-working-group/src/genesis.rs
  10. 30 26
      runtime-modules/content-working-group/src/lib.rs
  11. 1 3
      runtime-modules/content-working-group/src/tests.rs
  12. 1 39
      runtime-modules/forum/Cargo.toml
  13. 62 22
      runtime-modules/forum/src/lib.rs
  14. 8 82
      runtime-modules/forum/src/mock.rs
  15. 103 46
      runtime-modules/forum/src/tests.rs
  16. 1 1
      runtime-modules/hiring/src/lib.rs
  17. 0 6
      runtime-modules/proposals/codex/Cargo.toml
  18. 0 284
      runtime-modules/proposals/codex/src/lib.rs
  19. 43 17
      runtime-modules/proposals/codex/src/proposal_types/mod.rs
  20. 0 28
      runtime-modules/proposals/codex/src/proposal_types/parameters.rs
  21. 0 9
      runtime-modules/proposals/codex/src/tests/mock.rs
  22. 0 287
      runtime-modules/proposals/codex/src/tests/mod.rs
  23. 0 88
      runtime-modules/roles/Cargo.toml
  24. 0 425
      runtime-modules/roles/src/actors.rs
  25. 0 8
      runtime-modules/roles/src/lib.rs
  26. 0 130
      runtime-modules/roles/src/mock.rs
  27. 0 204
      runtime-modules/roles/src/tests.rs
  28. 0 25
      runtime-modules/roles/src/traits.rs
  29. 4 4
      runtime-modules/service-discovery/Cargo.toml
  30. 11 8
      runtime-modules/service-discovery/src/lib.rs
  31. 11 8
      runtime-modules/service-discovery/src/mock.rs
  32. 4 4
      runtime-modules/storage/Cargo.toml
  33. 8 8
      runtime-modules/storage/src/data_directory.rs
  34. 9 9
      runtime-modules/storage/src/data_object_storage_registry.rs
  35. 10 10
      runtime-modules/storage/src/data_object_type_registry.rs
  36. 7 4
      runtime-modules/storage/src/lib.rs
  37. 3 3
      runtime-modules/storage/src/tests/data_object_storage_registry.rs
  38. 5 5
      runtime-modules/storage/src/tests/data_object_type_registry.rs
  39. 8 7
      runtime-modules/storage/src/tests/mock.rs
  40. 1 1
      runtime-modules/working-group/Cargo.toml
  41. 18 2
      runtime-modules/working-group/src/errors.rs
  42. 110 49
      runtime-modules/working-group/src/lib.rs
  43. 53 47
      runtime-modules/working-group/src/tests/fixtures.rs
  44. 33 8
      runtime-modules/working-group/src/tests/mock.rs
  45. 126 50
      runtime-modules/working-group/src/tests/mod.rs
  46. 0 0
      runtime-modules/working-group/src/types.rs
  47. 4 11
      runtime/Cargo.toml
  48. 13 8
      runtime/src/integration/proposals/proposal_encoder.rs
  49. 1 1
      runtime/src/integration/storage.rs
  50. 22 36
      runtime/src/lib.rs
  51. 62 2
      runtime/src/migration.rs
  52. 1 98
      runtime/src/tests/proposals_integration.rs
  53. 4 4
      runtime/src/tests/storage_integration.rs

+ 27 - 53
Cargo.lock

@@ -1569,7 +1569,7 @@ dependencies = [
 
 [[package]]
 name = "joystream-node"
-version = "2.3.0"
+version = "2.4.0"
 dependencies = [
  "ctrlc",
  "derive_more 0.14.1",
@@ -1645,7 +1645,6 @@ dependencies = [
  "srml-timestamp",
  "srml-transaction-payment",
  "substrate-authority-discovery-primitives",
- "substrate-bureaucracy-module",
  "substrate-client",
  "substrate-common-module",
  "substrate-consensus-babe-primitives",
@@ -1661,7 +1660,6 @@ dependencies = [
  "substrate-proposals-discussion-module",
  "substrate-proposals-engine-module",
  "substrate-recurring-reward-module",
- "substrate-roles-module",
  "substrate-service-discovery-module",
  "substrate-session",
  "substrate-stake-module",
@@ -1670,6 +1668,7 @@ dependencies = [
  "substrate-versioned-store",
  "substrate-versioned-store-permissions-module",
  "substrate-wasm-builder-runner",
+ "substrate-working-group-module",
 ]
 
 [[package]]
@@ -4462,28 +4461,6 @@ dependencies = [
  "sha2",
 ]
 
-[[package]]
-name = "substrate-bureaucracy-module"
-version = "1.0.0"
-dependencies = [
- "parity-scale-codec",
- "serde",
- "sr-io",
- "sr-primitives",
- "sr-std",
- "srml-balances",
- "srml-support",
- "srml-system",
- "srml-timestamp",
- "substrate-common-module",
- "substrate-hiring-module",
- "substrate-membership-module",
- "substrate-primitives",
- "substrate-recurring-reward-module",
- "substrate-stake-module",
- "substrate-token-mint-module",
-]
-
 [[package]]
 name = "substrate-chain-spec"
 version = "2.0.0"
@@ -4829,7 +4806,7 @@ dependencies = [
 
 [[package]]
 name = "substrate-forum-module"
-version = "1.2.1"
+version = "1.2.2"
 dependencies = [
  "hex-literal 0.1.4",
  "parity-scale-codec",
@@ -4844,14 +4821,8 @@ dependencies = [
  "srml-support-procedural",
  "srml-system",
  "srml-timestamp",
- "substrate-bureaucracy-module",
  "substrate-common-module",
- "substrate-hiring-module",
- "substrate-membership-module",
  "substrate-primitives",
- "substrate-recurring-reward-module",
- "substrate-stake-module",
- "substrate-token-mint-module",
 ]
 
 [[package]]
@@ -5159,7 +5130,6 @@ dependencies = [
  "substrate-proposals-discussion-module",
  "substrate-proposals-engine-module",
  "substrate-recurring-reward-module",
- "substrate-roles-module",
  "substrate-stake-module",
  "substrate-token-mint-module",
  "substrate-versioned-store",
@@ -5227,24 +5197,6 @@ dependencies = [
  "substrate-token-mint-module",
 ]
 
-[[package]]
-name = "substrate-roles-module"
-version = "1.0.1"
-dependencies = [
- "parity-scale-codec",
- "serde",
- "sr-io",
- "sr-primitives",
- "sr-std",
- "srml-balances",
- "srml-support",
- "srml-system",
- "srml-timestamp",
- "substrate-common-module",
- "substrate-membership-module",
- "substrate-primitives",
-]
-
 [[package]]
 name = "substrate-rpc"
 version = "2.0.0"
@@ -5379,7 +5331,6 @@ dependencies = [
  "srml-support",
  "srml-system",
  "srml-timestamp",
- "substrate-bureaucracy-module",
  "substrate-common-module",
  "substrate-hiring-module",
  "substrate-membership-module",
@@ -5387,6 +5338,7 @@ dependencies = [
  "substrate-recurring-reward-module",
  "substrate-stake-module",
  "substrate-token-mint-module",
+ "substrate-working-group-module",
 ]
 
 [[package]]
@@ -5463,7 +5415,6 @@ dependencies = [
  "srml-support",
  "srml-system",
  "srml-timestamp",
- "substrate-bureaucracy-module",
  "substrate-common-module",
  "substrate-hiring-module",
  "substrate-membership-module",
@@ -5471,6 +5422,7 @@ dependencies = [
  "substrate-recurring-reward-module",
  "substrate-stake-module",
  "substrate-token-mint-module",
+ "substrate-working-group-module",
 ]
 
 [[package]]
@@ -5613,6 +5565,28 @@ dependencies = [
  "wasmi",
 ]
 
+[[package]]
+name = "substrate-working-group-module"
+version = "1.0.0"
+dependencies = [
+ "parity-scale-codec",
+ "serde",
+ "sr-io",
+ "sr-primitives",
+ "sr-std",
+ "srml-balances",
+ "srml-support",
+ "srml-system",
+ "srml-timestamp",
+ "substrate-common-module",
+ "substrate-hiring-module",
+ "substrate-membership-module",
+ "substrate-primitives",
+ "substrate-recurring-reward-module",
+ "substrate-stake-module",
+ "substrate-token-mint-module",
+]
+
 [[package]]
 name = "subtle"
 version = "1.0.0"

+ 1 - 2
Cargo.toml

@@ -12,14 +12,13 @@ members = [
 	"runtime-modules/membership",
 	"runtime-modules/memo",
 	"runtime-modules/recurring-reward",
-	"runtime-modules/roles",
 	"runtime-modules/service-discovery",
 	"runtime-modules/stake",
 	"runtime-modules/storage",
 	"runtime-modules/token-minting",
 	"runtime-modules/versioned-store",
 	"runtime-modules/versioned-store-permissions",
-	"runtime-modules/bureaucracy",
+	"runtime-modules/working-group",
 	"node",
 	"utils/chain-spec-builder/"
 ]

+ 1 - 1
node/Cargo.toml

@@ -3,7 +3,7 @@ authors = ['Joystream']
 build = 'build.rs'
 edition = '2018'
 name = 'joystream-node'
-version = '2.3.0'
+version = '2.4.0'
 default-run = "joystream-node"
 
 [[bin]]

+ 23 - 24
node/src/chain_spec.rs

@@ -15,17 +15,18 @@
 // along with Joystream node.  If not, see <http://www.gnu.org/licenses/>.
 
 // Clippy linter warning.
-#![allow(clippy::identity_op)] // disable it because we use such syntax for a code readability
-                               // Example:  voting_period: 1 * DAY
+// Disable it because we use such syntax for a code readability.
+// Example:  voting_period: 1 * DAY
+#![allow(clippy::identity_op)]
 
 use node_runtime::{
-    versioned_store::InputValidationLengthConstraint as VsInputValidation, ActorsConfig,
+    versioned_store::InputValidationLengthConstraint as VsInputValidation,
     AuthorityDiscoveryConfig, BabeConfig, Balance, BalancesConfig, ContentWorkingGroupConfig,
     CouncilConfig, CouncilElectionConfig, DataObjectStorageRegistryConfig,
     DataObjectTypeRegistryConfig, ElectionParameters, GrandpaConfig, ImOnlineConfig, IndicesConfig,
     MembersConfig, MigrationConfig, Perbill, ProposalsCodexConfig, SessionConfig, SessionKeys,
-    Signature, StakerStatus, StakingConfig, SudoConfig, SystemConfig, VersionedStoreConfig, DAYS,
-    WASM_BINARY,
+    Signature, StakerStatus, StakingConfig, StorageWorkingGroupConfig, SudoConfig, SystemConfig,
+    VersionedStoreConfig, DAYS, WASM_BINARY,
 };
 pub use node_runtime::{AccountId, GenesisConfig};
 use primitives::{sr25519, Pair, Public};
@@ -41,6 +42,8 @@ type AccountPublic = <Signature as Verify>::Signer;
 /// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.
 pub type ChainSpec = substrate_service::ChainSpec<GenesisConfig>;
 
+use node_runtime::common::constraints::InputValidationLengthConstraint;
+
 /// The chain specification option. This is expected to come in from the CLI and
 /// is little more than one of a number of alternatives which can easily be converted
 /// from a string (`--chain=...`) into a `ChainSpec`.
@@ -186,6 +189,7 @@ pub fn testnet_genesis(
 
     // default codex proposals config parameters
     let cpcp = node_runtime::ProposalsConfigParameters::default();
+    let default_text_constraint = node_runtime::working_group::default_text_constraint();
 
     GenesisConfig {
         system: Some(SystemConfig {
@@ -264,9 +268,12 @@ pub fn testnet_genesis(
         data_object_storage_registry: Some(DataObjectStorageRegistryConfig {
             first_relationship_id: 1,
         }),
-        actors: Some(ActorsConfig {
-            enable_storage_role: true,
-            request_life_time: 300,
+        working_group_Instance2: Some(StorageWorkingGroupConfig {
+            phantom: Default::default(),
+            storage_working_group_mint_capacity: 0,
+            opening_human_readable_text_constraint: default_text_constraint,
+            worker_application_human_readable_text_constraint: default_text_constraint,
+            worker_exit_rationale_text_constraint: default_text_constraint,
         }),
         versioned_store: Some(VersionedStoreConfig {
             class_by_id: vec![],
@@ -293,14 +300,14 @@ pub fn testnet_genesis(
             next_principal_id: 0,
             channel_creation_enabled: true, // there is no extrinsic to change it so enabling at genesis
             unstaker_by_stake_id: vec![],
-            channel_handle_constraint: crate::forum_config::new_validation(5, 20),
-            channel_description_constraint: crate::forum_config::new_validation(1, 1024),
-            opening_human_readable_text: crate::forum_config::new_validation(1, 2048),
-            curator_application_human_readable_text: crate::forum_config::new_validation(1, 2048),
-            curator_exit_rationale_text: crate::forum_config::new_validation(1, 2048),
-            channel_avatar_constraint: crate::forum_config::new_validation(5, 1024),
-            channel_banner_constraint: crate::forum_config::new_validation(5, 1024),
-            channel_title_constraint: crate::forum_config::new_validation(5, 1024),
+            channel_handle_constraint: InputValidationLengthConstraint::new(5, 20),
+            channel_description_constraint: InputValidationLengthConstraint::new(1, 1024),
+            opening_human_readable_text: InputValidationLengthConstraint::new(1, 2048),
+            curator_application_human_readable_text: InputValidationLengthConstraint::new(1, 2048),
+            curator_exit_rationale_text: InputValidationLengthConstraint::new(1, 2048),
+            channel_avatar_constraint: InputValidationLengthConstraint::new(5, 1024),
+            channel_banner_constraint: InputValidationLengthConstraint::new(5, 1024),
+            channel_title_constraint: InputValidationLengthConstraint::new(5, 1024),
         }),
         migration: Some(MigrationConfig {}),
         proposals_codex: Some(ProposalsCodexConfig {
@@ -324,14 +331,6 @@ pub fn testnet_genesis(
             set_lead_proposal_grace_period: cpcp.set_lead_proposal_voting_period,
             spending_proposal_voting_period: cpcp.spending_proposal_voting_period,
             spending_proposal_grace_period: cpcp.spending_proposal_grace_period,
-            evict_storage_provider_proposal_voting_period: cpcp
-                .evict_storage_provider_proposal_voting_period,
-            evict_storage_provider_proposal_grace_period: cpcp
-                .evict_storage_provider_proposal_grace_period,
-            set_storage_role_parameters_proposal_voting_period: cpcp
-                .set_storage_role_parameters_proposal_voting_period,
-            set_storage_role_parameters_proposal_grace_period: cpcp
-                .set_storage_role_parameters_proposal_grace_period,
         }),
     }
 }

+ 2 - 2
node/src/forum_config/from_serialized.rs

@@ -23,8 +23,7 @@ fn parse_forum_json() -> Result<ForumData> {
     serde_json::from_str(data)
 }
 
-//TODO: should we set the forum_sudo account in the bureaucracy module?
-pub fn create(_forum_sudo: AccountId) -> ForumConfig {
+pub fn create(forum_sudo: AccountId) -> ForumConfig {
     let forum_data = parse_forum_json().expect("failed loading forum data");
 
     let next_category_id: CategoryId = forum_data
@@ -47,5 +46,6 @@ pub fn create(_forum_sudo: AccountId) -> ForumConfig {
         post_text_constraint: new_validation(10, 990),
         thread_moderation_rationale_constraint: new_validation(10, 290),
         post_moderation_rationale_constraint: new_validation(10, 290),
+        forum_sudo,
     }
 }

+ 1 - 1
node/src/forum_config/mod.rs

@@ -3,7 +3,7 @@ pub mod from_serialized;
 // Not exported - only here as sample code
 // mod from_encoded;
 
-use node_runtime::forum::InputValidationLengthConstraint;
+use node_runtime::common::constraints::InputValidationLengthConstraint;
 
 pub fn new_validation(min: u16, max_min_diff: u16) -> InputValidationLengthConstraint {
     InputValidationLengthConstraint { min, max_min_diff }

+ 1 - 1
node/src/service.rs

@@ -224,7 +224,7 @@ macro_rules! new_full {
 			(true, false) => {
 				// start the full GRANDPA voter
 				let grandpa_config = grandpa::GrandpaParams {
-					config: config,
+					config,
 					link: grandpa_link,
 					network: service.network(),
 					inherent_data_providers: inherent_data_providers.clone(),

+ 8 - 3
runtime-modules/common/src/constraints.rs

@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
 
 /// Length constraint for input validation
 #[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
-#[derive(Encode, Decode, Default, Clone, PartialEq, Eq)]
+#[derive(Encode, Decode, Default, Clone, PartialEq, Eq, Copy)]
 pub struct InputValidationLengthConstraint {
     /// Minimum length
     pub min: u16,
@@ -18,12 +18,12 @@ pub struct InputValidationLengthConstraint {
 
 impl InputValidationLengthConstraint {
     /// Helper for computing max
-    pub fn max(&self) -> u16 {
+    pub fn max(self) -> u16 {
         self.min + self.max_min_diff
     }
 
     pub fn ensure_valid(
-        &self,
+        self,
         len: usize,
         too_short_msg: &'static str,
         too_long_msg: &'static str,
@@ -37,4 +37,9 @@ impl InputValidationLengthConstraint {
             Ok(())
         }
     }
+
+    /// Create default input text constraints.
+    pub fn new(min: u16, max_min_diff: u16) -> Self {
+        InputValidationLengthConstraint { min, max_min_diff }
+    }
 }

+ 1 - 1
runtime-modules/content-working-group/src/genesis.rs

@@ -6,7 +6,7 @@ use rstd::prelude::*;
 
 /// DIRTY IMPORT BECAUSE
 /// InputValidationLengthConstraint has not been factored out yet!!!
-use forum::InputValidationLengthConstraint;
+use common::constraints::InputValidationLengthConstraint;
 
 /// The way a map (linked_map) is represented in the GenesisConfig produced by decl_storage
 //pub type GenesisConfigMap<K, V> = std::vec::Vec<(K, V)>;

+ 30 - 26
runtime-modules/content-working-group/src/lib.rs

@@ -1179,17 +1179,17 @@ decl_module! {
             let new_channel = Channel {
                 verified: false,
                 handle: handle.clone(),
-                title: title,
-                description: description,
-                avatar: avatar,
-                banner: banner,
-                content: content,
-                owner: owner,
-                role_account: role_account,
-                publication_status: publication_status,
+                title,
+                description,
+                avatar,
+                banner,
+                content,
+                owner,
+                role_account,
+                publication_status,
                 curation_status: ChannelCurationStatus::Normal,
                 created: <system::Module<T>>::block_number(),
-                principal_id: principal_id
+                principal_id,
             };
 
             // Add channel to ChannelById under id
@@ -1387,9 +1387,9 @@ decl_module! {
 
             // Create and add curator opening.
             let new_opening_by_id = CuratorOpening {
-                opening_id : opening_id,
+                opening_id,
                 curator_applications: BTreeSet::new(),
-                policy_commitment: policy_commitment
+                policy_commitment,
             };
 
             CuratorOpeningById::<T>::insert(new_curator_opening_id, new_opening_by_id);
@@ -1466,6 +1466,23 @@ decl_module! {
             // Ensure curator opening exists
             let (curator_opening, _) = Self::ensure_curator_opening_exists(&curator_opening_id)?;
 
+            // Ensure a mint exists if lead is providing a reward for positions being filled
+            let create_reward_settings = if let Some(policy) = reward_policy {
+                // A reward will need to be created so ensure our configured mint exists
+                let mint_id = Self::mint();
+
+                // Technically this is a bug-check and should not be here.
+                ensure!(<minting::Mints<T>>::exists(mint_id), MSG_FILL_CURATOR_OPENING_MINT_DOES_NOT_EXIST);
+
+                // Make sure valid parameters are selected for next payment at block number
+                ensure!(policy.next_payment_at_block > <system::Module<T>>::block_number(), MSG_FILL_CURATOR_OPENING_INVALID_NEXT_PAYMENT_BLOCK);
+
+                // The verified reward settings to use
+                Some((mint_id, policy))
+            } else {
+                None
+            };
+
             // Make iterator over successful curator application
             let successful_iter = successful_curator_application_ids
                                     .iter()
@@ -1516,21 +1533,6 @@ decl_module! {
                 )
             )?;
 
-            let create_reward_settings = if let Some(policy) = reward_policy {
-                // A reward will need to be created so ensure our configured mint exists
-                let mint_id = Self::mint();
-
-                ensure!(<minting::Mints<T>>::exists(mint_id), MSG_FILL_CURATOR_OPENING_MINT_DOES_NOT_EXIST);
-
-                // Make sure valid parameters are selected for next payment at block number
-                ensure!(policy.next_payment_at_block > <system::Module<T>>::block_number(), MSG_FILL_CURATOR_OPENING_INVALID_NEXT_PAYMENT_BLOCK);
-
-                // The verified reward settings to use
-                Some((mint_id, policy))
-            } else {
-                None
-            };
-
             //
             // == MUTATION SAFE ==
             //
@@ -1979,6 +1981,8 @@ decl_module! {
         ) {
             ensure_root(origin)?;
 
+            ensure!(<Mint<T>>::exists(), MSG_FILL_CURATOR_OPENING_MINT_DOES_NOT_EXIST);
+
             let mint_id = Self::mint();
 
             // Mint must exist - it is set at genesis

+ 1 - 3
runtime-modules/content-working-group/src/tests.rs

@@ -9,9 +9,7 @@ use rstd::collections::btree_set::BTreeSet;
 use sr_primitives::traits::One;
 use srml_support::{assert_err, assert_ok, StorageLinkedMap, StorageValue};
 
-/// DIRTY IMPORT BECAUSE
-/// InputValidationLengthConstraint has not been factored out yet!!!
-use forum::InputValidationLengthConstraint;
+use common::constraints::InputValidationLengthConstraint;
 
 #[test]
 fn create_channel_success() {

+ 1 - 39
runtime-modules/forum/Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = 'substrate-forum-module'
-version = '1.2.1'
+version = '1.2.2'
 authors = ['Joystream contributors']
 edition = '2018'
 
@@ -30,52 +30,15 @@ git = 'https://github.com/paritytech/substrate.git'
 package = 'sr-io'
 rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
 
-[dependencies.bureaucracy]
-default_features = false
-package = 'substrate-bureaucracy-module'
-path = '../bureaucracy'
-version = '1.0.0'
-
 [dev-dependencies]
 runtime-io = { package = 'sr-io', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
 primitives = { package = 'substrate-primitives', git = 'https://github.com/paritytech/substrate.git', rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'}
 
-[dev-dependencies.membership]
-default_features = false
-package = 'substrate-membership-module'
-path = '../membership'
-
-[dev-dependencies.minting]
-default_features = false
-package = 'substrate-token-mint-module'
-path = '../token-minting'
-
-[dev-dependencies.recurringrewards]
-default_features = false
-package = 'substrate-recurring-reward-module'
-path = '../recurring-reward'
-
-[dev-dependencies.balances]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'srml-balances'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
 [dependencies.common]
 default_features = false
 package = 'substrate-common-module'
 path = '../common'
 
-[dev-dependencies.hiring]
-default_features = false
-package = 'substrate-hiring-module'
-path = '../hiring'
-
-[dev-dependencies.stake]
-default_features = false
-package = 'substrate-stake-module'
-path = '../stake'
-
 [features]
 default = ['std']
 std = [
@@ -89,6 +52,5 @@ std = [
 	'system/std',
   	'balances/std',
 	'timestamp/std',
-	'bureaucracy/std',
 	'common/std',
 ]

+ 62 - 22
runtime-modules/forum/src/lib.rs

@@ -9,20 +9,19 @@
 #[cfg(feature = "std")]
 use serde_derive::{Deserialize, Serialize};
 
-use codec::{Codec, Decode, Encode};
 use rstd::borrow::ToOwned;
 use rstd::prelude::*;
-use runtime_primitives::traits::EnsureOrigin;
+
+use codec::{Codec, Decode, Encode};
 use runtime_primitives::traits::{MaybeSerialize, Member, One, SimpleArithmetic};
 use srml_support::{decl_event, decl_module, decl_storage, dispatch, ensure, Parameter};
-use system::{ensure_signed, RawOrigin};
-
-pub use common::constraints::InputValidationLengthConstraint;
-use common::BlockAndTime;
 
 mod mock;
 mod tests;
 
+use common::constraints::InputValidationLengthConstraint;
+use common::BlockAndTime;
+
 /// Constants
 /////////////////////////////////////////////////////////////////
 
@@ -31,6 +30,8 @@ mod tests;
 const MAX_CATEGORY_DEPTH: u16 = 3;
 
 /// Error messages for dispatchables
+const ERROR_FORUM_SUDO_NOT_SET: &str = "Forum sudo not set.";
+const ERROR_ORIGIN_NOT_FORUM_SUDO: &str = "Origin not forum sudo.";
 const ERROR_CATEGORY_TITLE_TOO_SHORT: &str = "Category title too short.";
 const ERROR_CATEGORY_TITLE_TOO_LONG: &str = "Category title too long.";
 const ERROR_CATEGORY_DESCRIPTION_TOO_SHORT: &str = "Category description too long.";
@@ -58,6 +59,8 @@ const ERROR_CATEGORY_NOT_BEING_UPDATED: &str = "Category not being updated.";
 const ERROR_CATEGORY_CANNOT_BE_UNARCHIVED_WHEN_DELETED: &str =
     "Category cannot be unarchived when deleted.";
 
+use system::{ensure_root, ensure_signed};
+
 /// Represents a user in this forum.
 #[derive(Debug, Copy, Clone)]
 pub struct ForumUser<AccountId> {
@@ -258,9 +261,6 @@ pub trait Trait: system::Trait + timestamp::Trait + Sized {
 
     type MembershipRegistry: ForumUserRegistry<Self::AccountId>;
 
-    /// Checks that provided signed account belongs to the leader
-    type EnsureForumLeader: EnsureOrigin<Self::Origin>;
-
     /// Thread Id type
     type ThreadId: Parameter
         + Member
@@ -303,6 +303,9 @@ decl_storage! {
         /// Post identifier value to be used for for next post created.
         pub NextPostId get(next_post_id) config(): T::PostId;
 
+        /// Account of forum sudo.
+        pub ForumSudo get(forum_sudo) config(): Option<T::AccountId>;
+
         /// Input constraints
         /// These are all forward looking, that is they are enforced on all
         /// future calls.
@@ -379,14 +382,39 @@ decl_module! {
 
         fn deposit_event() = default;
 
+        /// Set forum sudo.
+        fn set_forum_sudo(origin, new_forum_sudo: Option<T::AccountId>) -> dispatch::Result {
+            ensure_root(origin)?;
+
+            /*
+             * Question: when this routine is called by non sudo or with bad signature, what error is raised?
+             * Update ERror set in spec
+             */
+
+            // Hold on to old value
+            let old_forum_sudo = <ForumSudo<T>>::get();
+
+            // Update forum sudo
+            match new_forum_sudo.clone() {
+                Some(account_id) => <ForumSudo<T>>::put(account_id),
+                None => <ForumSudo<T>>::kill()
+            };
+
+            // Generate event
+            Self::deposit_event(RawEvent::ForumSudoSet(old_forum_sudo, new_forum_sudo));
+
+            // All good.
+            Ok(())
+        }
+
         /// Add a new category.
         fn create_category(origin, parent: Option<CategoryId>, title: Vec<u8>, description: Vec<u8>) -> dispatch::Result {
 
             // Check that its a valid signature
             let who = ensure_signed(origin)?;
 
-            // Not signed by forum lead
-            Self::ensure_is_forum_lead(&who)?;
+            // Not signed by forum SUDO
+            Self::ensure_is_forum_sudo(&who)?;
 
             // Validate title
             Self::ensure_category_title_is_valid(&title)?;
@@ -464,8 +492,8 @@ decl_module! {
             // Check that its a valid signature
             let who = ensure_signed(origin)?;
 
-            // Not signed by forum lead
-            Self::ensure_is_forum_lead(&who)?;
+            // Not signed by forum SUDO
+            Self::ensure_is_forum_sudo(&who)?;
 
             // Make sure something is actually being changed
             ensure!(
@@ -570,8 +598,8 @@ decl_module! {
             // Check that its a valid signature
             let who = ensure_signed(origin)?;
 
-            // Signed by forum lead
-            Self::ensure_is_forum_lead(&who)?;
+            // Signed by forum SUDO
+            Self::ensure_is_forum_sudo(&who)?;
 
             // Get thread
             let mut thread = Self::ensure_thread_exists(thread_id)?;
@@ -705,8 +733,8 @@ decl_module! {
             // Check that its a valid signature
             let who = ensure_signed(origin)?;
 
-            // Signed by forum lead
-            Self::ensure_is_forum_lead(&who)?;
+            // Signed by forum SUDO
+            Self::ensure_is_forum_sudo(&who)?;
 
             // Make sure post exists and is mutable
             let post = Self::ensure_post_is_mutable(post_id)?;
@@ -844,9 +872,20 @@ impl<T: Trait> Module<T> {
         }
     }
 
-    fn ensure_is_forum_lead(account_id: &T::AccountId) -> dispatch::Result {
-        T::EnsureForumLeader::ensure_origin(RawOrigin::Signed(account_id.clone()).into())?;
+    fn ensure_forum_sudo_set() -> Result<T::AccountId, &'static str> {
+        match <ForumSudo<T>>::get() {
+            Some(account_id) => Ok(account_id),
+            None => Err(ERROR_FORUM_SUDO_NOT_SET),
+        }
+    }
+
+    fn ensure_is_forum_sudo(account_id: &T::AccountId) -> dispatch::Result {
+        let forum_sudo_account = Self::ensure_forum_sudo_set()?;
 
+        ensure!(
+            *account_id == forum_sudo_account,
+            ERROR_ORIGIN_NOT_FORUM_SUDO
+        );
         Ok(())
     }
 
@@ -868,9 +907,10 @@ impl<T: Trait> Module<T> {
         Self::ensure_can_mutate_in_path_leaf(&category_tree_path)
     }
 
-    // Clippy linter warning
-    #[allow(clippy::ptr_arg)] // disable it because of possible frontend API break
-                              // TODO: remove post-Constaninople
+    // TODO: remove post-Constaninople
+    // Clippy linter warning.
+    // Disable it because of possible frontend API break.
+    #[allow(clippy::ptr_arg)]
     fn ensure_can_mutate_in_path_leaf(
         category_tree_path: &CategoryTreePath<T::BlockNumber, T::Moment, T::AccountId>,
     ) -> dispatch::Result {

+ 8 - 82
runtime-modules/forum/src/mock.rs

@@ -71,11 +71,6 @@ parameter_types! {
     pub const MaximumBlockLength: u32 = 2 * 1024;
     pub const AvailableBlockRatio: Perbill = Perbill::one();
     pub const MinimumPeriod: u64 = 5;
-    pub const InitialMembersBalance: u64 = 2000;
-    pub const ExistentialDeposit: u32 = 0;
-    pub const TransferFee: u32 = 0;
-    pub const CreationFee: u32 = 0;
-    pub const StakePoolId: [u8; 8] = *b"joystake";
 }
 
 impl system::Trait for Runtime {
@@ -103,66 +98,9 @@ impl timestamp::Trait for Runtime {
     type MinimumPeriod = MinimumPeriod;
 }
 
-impl bureaucracy::Trait<bureaucracy::Instance1> for Runtime {
-    type Event = ();
-}
-
-impl recurringrewards::Trait for Runtime {
-    type PayoutStatusHandler = ();
-    type RecipientId = u64;
-    type RewardRelationshipId = u64;
-}
-
-impl stake::Trait for Runtime {
-    type Currency = Balances;
-    type StakePoolId = StakePoolId;
-    type StakingEventsHandler = ();
-    type StakeId = u64;
-    type SlashId = u64;
-}
-
-impl hiring::Trait for Runtime {
-    type OpeningId = u64;
-    type ApplicationId = u64;
-    type ApplicationDeactivatedHandler = ();
-    type StakeHandlerProvider = hiring::Module<Self>;
-}
-
-impl membership::members::Trait for Runtime {
-    type Event = ();
-    type MemberId = u64;
-    type PaidTermId = u64;
-    type SubscriptionId = u64;
-    type ActorId = u64;
-    type InitialMembersBalance = InitialMembersBalance;
-}
-
-impl balances::Trait for Runtime {
-    type Balance = u64;
-    type OnFreeBalanceZero = ();
-    type OnNewAccount = ();
-    type Event = ();
-    type DustRemoval = ();
-    type TransferPayment = ();
-    type ExistentialDeposit = ExistentialDeposit;
-    type TransferFee = TransferFee;
-    type CreationFee = CreationFee;
-}
-pub type Balances = balances::Module<Runtime>;
-
-impl common::currency::GovernanceCurrency for Runtime {
-    type Currency = Balances;
-}
-
-impl minting::Trait for Runtime {
-    type Currency = Balances;
-    type MintId = u64;
-}
-
 impl Trait for Runtime {
     type Event = ();
     type MembershipRegistry = registry::TestMembershipRegistryModule;
-    type EnsureForumLeader = bureaucracy::Module<Runtime, bureaucracy::Instance1>;
     type ThreadId = u64;
     type PostId = u64;
 }
@@ -171,19 +109,17 @@ impl Trait for Runtime {
 pub enum OriginType {
     Signed(<Runtime as system::Trait>::AccountId),
     //Inherent, <== did not find how to make such an origin yet
-    //Root,
+    Root,
 }
 
 pub fn mock_origin(origin: OriginType) -> mock::Origin {
     match origin {
         OriginType::Signed(account_id) => Origin::signed(account_id),
         //OriginType::Inherent => Origin::inherent,
-        //OriginType::Root => system::RawOrigin::Root.into(), //Origin::root
+        OriginType::Root => system::RawOrigin::Root.into(), //Origin::root
     }
 }
 
-pub static ERROR_ORIGIN_NOT_FORUM_SUDO: &str = "Invalid origin";
-
 pub const NOT_FORUM_SUDO_ORIGIN: OriginType = OriginType::Signed(111);
 
 pub const NOT_MEMBER_ORIGIN: OriginType = OriginType::Signed(222);
@@ -194,10 +130,6 @@ pub const INVLAID_THREAD_ID: RuntimeThreadId = 444;
 
 pub const INVLAID_POST_ID: RuntimePostId = 555;
 
-pub(crate) const FORUM_SUDO_ID: u64 = 33;
-
-pub(crate) const FORUM_SUDO_MEMBER_ID: u64 = 1;
-
 pub fn generate_text(len: usize) -> Vec<u8> {
     vec![b'x'; len]
 }
@@ -241,7 +173,6 @@ pub struct CreateCategoryFixture {
 
 impl CreateCategoryFixture {
     pub fn call_and_assert(&self) {
-        set_bureaucracy_forum_lead();
         assert_eq!(
             TestForumModule::create_category(
                 mock_origin(self.origin.clone()),
@@ -264,7 +195,6 @@ pub struct UpdateCategoryFixture {
 
 impl UpdateCategoryFixture {
     pub fn call_and_assert(&self) {
-        set_bureaucracy_forum_lead();
         assert_eq!(
             TestForumModule::update_category(
                 mock_origin(self.origin.clone()),
@@ -285,15 +215,6 @@ pub struct CreateThreadFixture {
     pub result: dispatch::Result,
 }
 
-type Bureaucracy1 = bureaucracy::Module<Runtime, bureaucracy::Instance1>;
-
-pub(crate) fn set_bureaucracy_forum_lead() {
-    assert_eq!(
-        Bureaucracy1::set_lead(RawOrigin::Root.into(), FORUM_SUDO_MEMBER_ID, FORUM_SUDO_ID),
-        Ok(())
-    );
-}
-
 impl CreateThreadFixture {
     pub fn call_and_assert(&self) {
         assert_eq!(
@@ -464,7 +385,7 @@ pub fn assert_not_forum_sudo_cannot_update_category(
     update_operation: fn(OriginType, CategoryId) -> dispatch::Result,
 ) {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let category_id = create_root_category(origin.clone());
@@ -491,6 +412,8 @@ pub fn default_genesis_config() -> GenesisConfig<Runtime> {
         post_by_id: vec![],
         next_post_id: 1,
 
+        forum_sudo: 33,
+
         category_title_constraint: InputValidationLengthConstraint {
             min: 10,
             max_min_diff: 140,
@@ -547,6 +470,7 @@ pub type RuntimePost = Post<
 >;
 pub type RuntimeBlockchainTimestamp =
     BlockAndTime<<Runtime as system::Trait>::BlockNumber, <Runtime as timestamp::Trait>::Moment>;
+
 pub type RuntimeThreadId = <Runtime as Trait>::ThreadId;
 pub type RuntimePostId = <Runtime as Trait>::PostId;
 
@@ -557,6 +481,7 @@ pub fn genesis_config(
     next_thread_id: u64,
     post_by_id: &RuntimeMap<RuntimePostId, RuntimePost>,
     next_post_id: u64,
+    forum_sudo: <Runtime as system::Trait>::AccountId,
     category_title_constraint: &InputValidationLengthConstraint,
     category_description_constraint: &InputValidationLengthConstraint,
     thread_title_constraint: &InputValidationLengthConstraint,
@@ -571,6 +496,7 @@ pub fn genesis_config(
         next_thread_id,
         post_by_id: post_by_id.clone(),
         next_post_id,
+        forum_sudo,
         category_title_constraint: category_title_constraint.clone(),
         category_description_constraint: category_description_constraint.clone(),
         thread_title_constraint: thread_title_constraint.clone(),

+ 103 - 46
runtime-modules/forum/src/tests.rs

@@ -9,6 +9,64 @@ use srml_support::{assert_err, assert_ok};
 * NB!: No test checks for event emission!!!!
 */
 
+/*
+ * set_forum_sudo
+ * ==============================================================================
+ *
+ * Missing cases
+ *
+ * set_forum_bad_origin
+ *
+ */
+
+#[test]
+fn set_forum_sudo_unset() {
+    let config = default_genesis_config();
+
+    build_test_externalities(config).execute_with(|| {
+        // Ensure that forum sudo is default
+        assert_eq!(TestForumModule::forum_sudo(), Some(33));
+
+        // Unset forum sudo
+        assert_ok!(TestForumModule::set_forum_sudo(
+            mock_origin(OriginType::Root),
+            None
+        ));
+
+        // Sudo no longer set
+        assert!(TestForumModule::forum_sudo().is_none());
+
+        // event emitted?!
+    });
+}
+
+#[test]
+fn set_forum_sudo_update() {
+    let config = default_genesis_config();
+
+    build_test_externalities(config).execute_with(|| {
+        // Ensure that forum sudo is default
+        assert_eq!(
+            TestForumModule::forum_sudo(),
+            Some(default_genesis_config().forum_sudo)
+        );
+
+        let new_forum_sudo_account_id = 780;
+
+        // Unset forum sudo
+        assert_ok!(TestForumModule::set_forum_sudo(
+            mock_origin(OriginType::Root),
+            Some(new_forum_sudo_account_id)
+        ));
+
+        // Sudo no longer set
+        assert_eq!(
+            TestForumModule::forum_sudo(),
+            Some(new_forum_sudo_account_id)
+        );
+    });
+}
+
 /*
  * create_category
  * ==============================================================================
@@ -22,7 +80,7 @@ use srml_support::{assert_err, assert_ok};
 #[test]
 fn create_root_category_successfully() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         assert_create_category(origin, None, Ok(()));
@@ -32,7 +90,7 @@ fn create_root_category_successfully() {
 #[test]
 fn create_subcategory_successfully() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let root_category_id = create_root_category(origin.clone());
@@ -43,7 +101,7 @@ fn create_subcategory_successfully() {
 #[test]
 fn create_category_title_too_short() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let min_len = config.category_title_constraint.min as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -61,7 +119,7 @@ fn create_category_title_too_short() {
 #[test]
 fn create_category_title_too_long() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let max_len = config.category_title_constraint.max() as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -79,7 +137,7 @@ fn create_category_title_too_long() {
 #[test]
 fn create_category_description_too_short() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let min_len = config.category_description_constraint.min as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -97,7 +155,7 @@ fn create_category_description_too_short() {
 #[test]
 fn create_category_description_too_long() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let max_len = config.category_description_constraint.max() as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -131,7 +189,7 @@ fn update_category_undelete_and_unarchive() {
      * leaf category is deleted, and then try to undelete.
      */
 
-    let forum_sudo = FORUM_SUDO_ID;
+    let forum_sudo = 32;
 
     let created_at = RuntimeBlockchainTimestamp { block: 0, time: 0 };
 
@@ -190,6 +248,7 @@ fn update_category_undelete_and_unarchive() {
         1,                           // next_thread_id
         &vec![],                     // post_by_id
         1,                           // next_post_id
+        forum_sudo,
         &sloppy_constraint,
         &sloppy_constraint,
         &sloppy_constraint,
@@ -224,7 +283,7 @@ fn update_category_undelete_and_unarchive() {
 #[test]
 fn create_thread_successfully() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let category_id = create_root_category(origin);
@@ -244,7 +303,7 @@ fn create_thread_successfully() {
 #[test]
 fn create_thread_title_too_short() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let min_len = config.thread_title_constraint.min as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -265,7 +324,7 @@ fn create_thread_title_too_short() {
 #[test]
 fn create_thread_title_too_long() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let max_len = config.thread_title_constraint.max() as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -286,7 +345,7 @@ fn create_thread_title_too_long() {
 #[test]
 fn create_thread_text_too_short() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let min_len = config.post_text_constraint.min as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -307,7 +366,7 @@ fn create_thread_text_too_short() {
 #[test]
 fn create_thread_text_too_long() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let max_len = config.post_text_constraint.max() as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -328,7 +387,7 @@ fn create_thread_text_too_long() {
 #[test]
 fn create_post_successfully() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let (_, _, _, _) = create_root_category_and_thread_and_post(origin);
@@ -338,7 +397,7 @@ fn create_post_successfully() {
 #[test]
 fn create_post_text_too_short() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let min_len = config.post_text_constraint.min as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -357,7 +416,7 @@ fn create_post_text_too_short() {
 #[test]
 fn create_post_text_too_long() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let max_len = config.post_text_constraint.max() as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -379,7 +438,7 @@ fn create_post_text_too_long() {
 #[test]
 fn moderate_thread_successfully() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let (_, _, thread_id) = create_root_category_and_thread(origin.clone());
@@ -390,7 +449,7 @@ fn moderate_thread_successfully() {
 #[test]
 fn cannot_moderate_already_moderated_thread() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let (_, _, thread_id) = create_root_category_and_thread(origin.clone());
@@ -408,7 +467,7 @@ fn cannot_moderate_already_moderated_thread() {
 #[test]
 fn moderate_thread_rationale_too_short() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let min_len = config.thread_moderation_rationale_constraint.min as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -424,7 +483,7 @@ fn moderate_thread_rationale_too_short() {
 #[test]
 fn moderate_thread_rationale_too_long() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let max_len = config.thread_moderation_rationale_constraint.max() as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -440,7 +499,7 @@ fn moderate_thread_rationale_too_long() {
 #[test]
 fn moderate_post_successfully() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let (_, _, _, post_id) = create_root_category_and_thread_and_post(origin.clone());
@@ -451,7 +510,7 @@ fn moderate_post_successfully() {
 #[test]
 fn moderate_post_rationale_too_short() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let min_len = config.post_moderation_rationale_constraint.min as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -467,7 +526,7 @@ fn moderate_post_rationale_too_short() {
 #[test]
 fn moderate_post_rationale_too_long() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
     let max_len = config.post_moderation_rationale_constraint.max() as usize;
 
     build_test_externalities(config).execute_with(|| {
@@ -483,7 +542,7 @@ fn moderate_post_rationale_too_long() {
 #[test]
 fn cannot_moderate_already_moderated_post() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let (_, _, _, post_id) = create_root_category_and_thread_and_post(origin.clone());
@@ -517,7 +576,7 @@ fn not_forum_sudo_cannot_create_root_category() {
 #[test]
 fn not_forum_sudo_cannot_create_subcategory() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let root_category_id = create_root_category(origin);
@@ -552,7 +611,7 @@ fn not_forum_sudo_cannot_undelete_category() {
 #[test]
 fn not_forum_sudo_cannot_moderate_thread() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let (_, _, thread_id) = create_root_category_and_thread(origin.clone());
@@ -566,7 +625,7 @@ fn not_forum_sudo_cannot_moderate_thread() {
 #[test]
 fn not_forum_sudo_cannot_moderate_post() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let (_, _, _, post_id) = create_root_category_and_thread_and_post(origin.clone());
@@ -583,7 +642,7 @@ fn not_forum_sudo_cannot_moderate_post() {
 #[test]
 fn not_member_cannot_create_thread() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         CreateThreadFixture {
@@ -600,7 +659,7 @@ fn not_member_cannot_create_thread() {
 #[test]
 fn not_member_cannot_create_post() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let (_, _, thread_id) = create_root_category_and_thread(origin);
@@ -617,7 +676,7 @@ fn not_member_cannot_create_post() {
 #[test]
 fn not_member_cannot_edit_post() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let (_, _, _, post_id) = create_root_category_and_thread_and_post(origin);
@@ -638,7 +697,7 @@ fn not_member_cannot_edit_post() {
 #[test]
 fn cannot_create_subcategory_with_invalid_parent_category_id() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         assert_create_category(
@@ -683,10 +742,9 @@ fn cannot_create_post_with_invalid_thread_id() {
 #[test]
 fn cannot_moderate_thread_with_invalid_id() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
-        set_bureaucracy_forum_lead();
         assert_err!(
             moderate_thread(origin, INVLAID_THREAD_ID, good_rationale()),
             ERROR_THREAD_DOES_NOT_EXIST
@@ -697,10 +755,9 @@ fn cannot_moderate_thread_with_invalid_id() {
 #[test]
 fn cannot_moderate_post_with_invalid_id() {
     let config = default_genesis_config();
-    let origin = OriginType::Signed(FORUM_SUDO_ID);
+    let origin = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
-        mock::set_bureaucracy_forum_lead();
         assert_err!(
             moderate_post(origin, INVLAID_POST_ID, good_rationale()),
             ERROR_POST_DOES_NOT_EXIST
@@ -714,7 +771,7 @@ fn cannot_moderate_post_with_invalid_id() {
 #[test]
 fn archive_then_unarchive_category_successfully() {
     let config = default_genesis_config();
-    let forum_sudo = OriginType::Signed(FORUM_SUDO_ID);
+    let forum_sudo = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let category_id = create_root_category(forum_sudo.clone());
@@ -729,7 +786,7 @@ fn archive_then_unarchive_category_successfully() {
 #[test]
 fn delete_then_undelete_category_successfully() {
     let config = default_genesis_config();
-    let forum_sudo = OriginType::Signed(FORUM_SUDO_ID);
+    let forum_sudo = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let category_id = create_root_category(forum_sudo.clone());
@@ -745,7 +802,7 @@ fn delete_then_undelete_category_successfully() {
 // #[test]
 // fn cannot_unarchive_not_archived_category() {
 //     let config = default_genesis_config();
-//     let forum_sudo = OriginType::Signed(FORUM_SUDO_ID);
+//     let forum_sudo = OriginType::Signed(config.forum_sudo);
 
 //     build_test_externalities(config).execute_with(|| {
 //         let category_id = create_root_category(forum_sudo.clone());
@@ -766,7 +823,7 @@ fn delete_then_undelete_category_successfully() {
 // #[test]
 // fn cannot_undelete_not_deleted_category() {
 //     let config = default_genesis_config();
-//     let forum_sudo = OriginType::Signed(FORUM_SUDO_ID);
+//     let forum_sudo = OriginType::Signed(config.forum_sudo);
 
 //     build_test_externalities(config).execute_with(|| {
 //         let category_id = create_root_category(forum_sudo.clone());
@@ -786,7 +843,7 @@ fn delete_then_undelete_category_successfully() {
 #[test]
 fn cannot_create_subcategory_in_archived_category() {
     let config = default_genesis_config();
-    let forum_sudo = OriginType::Signed(FORUM_SUDO_ID);
+    let forum_sudo = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let category_id = create_root_category(forum_sudo.clone());
@@ -802,7 +859,7 @@ fn cannot_create_subcategory_in_archived_category() {
 #[test]
 fn cannot_create_subcategory_in_deleted_category() {
     let config = default_genesis_config();
-    let forum_sudo = OriginType::Signed(FORUM_SUDO_ID);
+    let forum_sudo = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let category_id = create_root_category(forum_sudo.clone());
@@ -818,7 +875,7 @@ fn cannot_create_subcategory_in_deleted_category() {
 #[test]
 fn cannot_create_thread_in_archived_category() {
     let config = default_genesis_config();
-    let forum_sudo = OriginType::Signed(FORUM_SUDO_ID);
+    let forum_sudo = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let category_id = create_root_category(forum_sudo.clone());
@@ -834,7 +891,7 @@ fn cannot_create_thread_in_archived_category() {
 #[test]
 fn cannot_create_thread_in_deleted_category() {
     let config = default_genesis_config();
-    let forum_sudo = OriginType::Signed(FORUM_SUDO_ID);
+    let forum_sudo = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let category_id = create_root_category(forum_sudo.clone());
@@ -850,7 +907,7 @@ fn cannot_create_thread_in_deleted_category() {
 #[test]
 fn cannot_create_post_in_thread_of_archived_category() {
     let config = default_genesis_config();
-    let forum_sudo = OriginType::Signed(FORUM_SUDO_ID);
+    let forum_sudo = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let category_id = create_root_category(forum_sudo.clone());
@@ -868,7 +925,7 @@ fn cannot_create_post_in_thread_of_archived_category() {
 #[test]
 fn cannot_create_post_in_thread_of_deleted_category() {
     let config = default_genesis_config();
-    let forum_sudo = OriginType::Signed(FORUM_SUDO_ID);
+    let forum_sudo = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let category_id = create_root_category(forum_sudo.clone());
@@ -886,7 +943,7 @@ fn cannot_create_post_in_thread_of_deleted_category() {
 #[test]
 fn cannot_create_post_in_moderated_thread() {
     let config = default_genesis_config();
-    let forum_sudo = OriginType::Signed(FORUM_SUDO_ID);
+    let forum_sudo = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let (_, _, thread_id) = create_root_category_and_thread(forum_sudo.clone());
@@ -906,7 +963,7 @@ fn cannot_create_post_in_moderated_thread() {
 #[test]
 fn cannot_edit_post_in_moderated_thread() {
     let config = default_genesis_config();
-    let forum_sudo = OriginType::Signed(FORUM_SUDO_ID);
+    let forum_sudo = OriginType::Signed(config.forum_sudo);
 
     build_test_externalities(config).execute_with(|| {
         let (member_origin, _, thread_id, post_id) =

+ 1 - 1
runtime-modules/hiring/src/lib.rs

@@ -154,7 +154,7 @@ decl_module! {
                         hiring::ActiveOpeningStage::Deactivated {
                             cause: hiring::OpeningDeactivationCause::ReviewPeriodExpired,
                             deactivated_at_block: now,
-                            started_accepting_applicants_at_block: started_accepting_applicants_at_block,
+                            started_accepting_applicants_at_block,
                             started_review_period_at_block: Some(started_review_period_at_block),
                     });
 

+ 0 - 6
runtime-modules/proposals/codex/Cargo.toml

@@ -24,7 +24,6 @@ std = [
     'membership/std',
     'governance/std',
     'mint/std',
-    'roles/std',
     'common/std',
     'content_working_group/std',
 ]
@@ -133,11 +132,6 @@ default_features = false
 package = 'substrate-content-working-group-module'
 path = '../../content-working-group'
 
-[dependencies.roles]
-default_features = false
-package = 'substrate-roles-module'
-path = '../../roles'
-
 [dev-dependencies.hiring]
 default_features = false
 package = 'substrate-hiring-module'

+ 0 - 284
runtime-modules/proposals/codex/src/lib.rs

@@ -19,9 +19,7 @@
 //! - [create_set_content_working_group_mint_capacity_proposal](./struct.Module.html#method.create_set_content_working_group_mint_capacity_proposal)
 //! - [create_spending_proposal](./struct.Module.html#method.create_spending_proposal)
 //! - [create_set_lead_proposal](./struct.Module.html#method.create_set_lead_proposal)
-//! - [create_evict_storage_provider_proposal](./struct.Module.html#method.create_evict_storage_provider_proposal)
 //! - [create_set_validator_count_proposal](./struct.Module.html#method.create_set_validator_count_proposal)
-//! - [create_set_storage_role_parameters_proposal](./struct.Module.html#method.create_set_storage_role_parameters_proposal)
 //!
 //! ### Proposal implementations of this module
 //! - execute_text_proposal - prints the proposal to the log
@@ -59,7 +57,6 @@ mod tests;
 use common::origin_validator::ActorOriginValidator;
 use governance::election_params::ElectionParameters;
 use proposal_engine::ProposalParameters;
-use roles::actors::RoleParameters;
 use rstd::clone::Clone;
 use rstd::prelude::*;
 use rstd::str::from_utf8;
@@ -79,44 +76,6 @@ const CONTENT_WORKING_GROUP_MINT_CAPACITY_MAX_VALUE: u32 = 1_000_000;
 const MAX_SPENDING_PROPOSAL_VALUE: u32 = 2_000_000_u32;
 // Max validator count for the 'set validator count' proposal
 const MAX_VALIDATOR_COUNT: u32 = 100;
-// min_actors min value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_MIN_ACTORS_MAX_VALUE: u32 = 2;
-// max_actors min value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_MAX_ACTORS_MIN_VALUE: u32 = 2;
-// max_actors max value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_MAX_ACTORS_MAX_VALUE: u32 = 100;
-// reward_period min value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_REWARD_PERIOD_MIN_VALUE: u32 = 600;
-// reward_period max value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_REWARD_PERIOD_MAX_VALUE: u32 = 3600;
-// bonding_period min value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_BONDING_PERIOD_MIN_VALUE: u32 = 600;
-// bonding_period max value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_BONDING_PERIOD_MAX_VALUE: u32 = 28800;
-// unbonding_period min value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_UNBONDING_PERIOD_MIN_VALUE: u32 = 600;
-// unbonding_period max value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_UNBONDING_PERIOD_MAX_VALUE: u32 = 28800;
-// min_service_period min value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_MIN_SERVICE_PERIOD_MIN_VALUE: u32 = 600;
-// min_service_period max value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_MIN_SERVICE_PERIOD_MAX_VALUE: u32 = 28800;
-// startup_grace_period min value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_STARTUP_GRACE_PERIOD_MIN_VALUE: u32 = 600;
-// startup_grace_period max value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_STARTUP_GRACE_PERIOD_MAX_VALUE: u32 = 28800;
-// min_stake min value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_MIN_STAKE_MIN_VALUE: u32 = 0;
-// min_stake max value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_MIN_STAKE_MAX_VALUE: u32 = 10_000_000;
-// entry_request_fee min value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_ENTRY_REQUEST_FEE_MIN_VALUE: u32 = 0;
-// entry_request_fee max value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_ENTRY_REQUEST_FEE_MAX_VALUE: u32 = 100_000;
-// reward min value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_REWARD_MIN_VALUE: u32 = 0;
-// reward max value for the 'set storage role parameters' proposal
-const ROLE_PARAMETERS_REWARD_MAX_VALUE: u32 = 100_000;
 // council_size min value for the 'set election parameters' proposal
 const ELECTION_PARAMETERS_COUNCIL_SIZE_MIN_VALUE: u32 = 4;
 // council_size max value for the 'set election parameters' proposal
@@ -158,7 +117,6 @@ pub trait Trait:
     + membership::members::Trait
     + governance::election::Trait
     + content_working_group::Trait
-    + roles::actors::Trait
     + staking::Trait
 {
     /// Defines max allowed text proposal length.
@@ -225,27 +183,6 @@ decl_error! {
         /// Require root origin in extrinsics
         RequireRootOrigin,
 
-        /// Invalid storage role parameter - min_actors
-        InvalidStorageRoleParameterMinActors,
-
-        /// Invalid storage role parameter - max_actors
-        InvalidStorageRoleParameterMaxActors,
-
-        /// Invalid storage role parameter - reward_period
-        InvalidStorageRoleParameterRewardPeriod,
-
-        /// Invalid storage role parameter - bonding_period
-        InvalidStorageRoleParameterBondingPeriod,
-
-        /// Invalid storage role parameter - unbonding_period
-        InvalidStorageRoleParameterUnbondingPeriod,
-
-        /// Invalid storage role parameter - min_service_period
-        InvalidStorageRoleParameterMinServicePeriod,
-
-        /// Invalid storage role parameter - startup_grace_period
-        InvalidStorageRoleParameterStartupGracePeriod,
-
         /// Invalid council election parameter - council_size
         InvalidCouncilElectionParameterCouncilSize,
 
@@ -270,15 +207,6 @@ decl_error! {
         /// Invalid council election parameter - announcing_period
         InvalidCouncilElectionParameterAnnouncingPeriod,
 
-        /// Invalid council election parameter - min_stake
-        InvalidStorageRoleParameterMinStake,
-
-        /// Invalid council election parameter - reward
-        InvalidStorageRoleParameterReward,
-
-        /// Invalid council election parameter - entry_request_fee
-        InvalidStorageRoleParameterEntryRequestFee,
-
         /// Invalid working group mint capacity parameter
         InvalidStorageWorkingGroupMintCapacity,
 
@@ -385,22 +313,6 @@ decl_storage! {
 
         /// Grace period for the 'spending' proposal
         pub SpendingProposalGracePeriod get(spending_proposal_grace_period) config(): T::BlockNumber;
-
-        /// Voting period for the 'evict storage provider' proposal
-        pub EvictStorageProviderProposalVotingPeriod get(evict_storage_provider_proposal_voting_period)
-            config(): T::BlockNumber;
-
-        /// Grace period for the 'evict storage provider' proposal
-        pub EvictStorageProviderProposalGracePeriod get(evict_storage_provider_proposal_grace_period)
-            config(): T::BlockNumber;
-
-        /// Voting period for the 'set storage role parameters' proposal
-        pub SetStorageRoleParametersProposalVotingPeriod get(set_storage_role_parameters_proposal_voting_period)
-            config(): T::BlockNumber;
-
-        /// Grace period for the 'set storage role parameters' proposal
-        pub SetStorageRoleParametersProposalGracePeriod get(set_storage_role_parameters_proposal_grace_period)
-            config(): T::BlockNumber;
     }
 }
 
@@ -607,33 +519,6 @@ decl_module! {
             )?;
         }
 
-        /// Create 'Evict storage provider' proposal type.
-        /// This proposal uses `remove_actor()` extrinsic from the `roles::actors`  module.
-        pub fn create_evict_storage_provider_proposal(
-            origin,
-            member_id: MemberId<T>,
-            title: Vec<u8>,
-            description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
-            actor_account: T::AccountId,
-        ) {
-            let proposal_parameters =
-                proposal_types::parameters::evict_storage_provider_proposal::<T>();
-            let proposal_details = ProposalDetails::EvictStorageProvider(actor_account);
-            let proposal_code = T::ProposalEncoder::encode_proposal(proposal_details.clone());
-
-            Self::create_proposal(
-                origin,
-                member_id,
-                title,
-                description,
-                stake_balance,
-                proposal_code,
-                proposal_parameters,
-                proposal_details,
-            )?;
-        }
-
         /// Create 'Evict storage provider' proposal type.
         /// This proposal uses `set_validator_count()` extrinsic from the Substrate `staking`  module.
         pub fn create_set_validator_count_proposal(
@@ -671,35 +556,6 @@ decl_module! {
             )?;
         }
 
-        /// Create 'Set storage roles parameters' proposal type.
-        /// This proposal uses `set_role_parameters()` extrinsic from the Substrate `roles::actors`  module.
-        pub fn create_set_storage_role_parameters_proposal(
-            origin,
-            member_id: MemberId<T>,
-            title: Vec<u8>,
-            description: Vec<u8>,
-            stake_balance: Option<BalanceOf<T>>,
-            role_parameters: RoleParameters<BalanceOfGovernanceCurrency<T>, T::BlockNumber>
-        ) {
-            Self::ensure_storage_role_parameters_valid(&role_parameters)?;
-
-            let proposal_parameters =
-                proposal_types::parameters::set_storage_role_parameters_proposal::<T>();
-            let proposal_details =  ProposalDetails::SetStorageRoleParameters(role_parameters);
-            let proposal_code = T::ProposalEncoder::encode_proposal(proposal_details.clone());
-
-            Self::create_proposal(
-                origin,
-                member_id,
-                title,
-                description,
-                stake_balance,
-                proposal_code,
-                proposal_parameters,
-                proposal_details,
-            )?;
-        }
-
 // *************** Extrinsic to execute
 
         /// Text proposal extrinsic. Should be used as callable object to pass to the `engine` module.
@@ -800,134 +656,6 @@ impl<T: Trait> Module<T> {
         Ok(())
     }
 
-    // validates storage role parameters for the 'Set storage role parameters' proposal
-    fn ensure_storage_role_parameters_valid(
-        role_parameters: &RoleParameters<BalanceOfGovernanceCurrency<T>, T::BlockNumber>,
-    ) -> Result<(), Error> {
-        ensure!(
-            role_parameters.min_actors < ROLE_PARAMETERS_MIN_ACTORS_MAX_VALUE,
-            Error::InvalidStorageRoleParameterMinActors
-        );
-
-        ensure!(
-            role_parameters.max_actors >= ROLE_PARAMETERS_MAX_ACTORS_MIN_VALUE,
-            Error::InvalidStorageRoleParameterMaxActors
-        );
-
-        ensure!(
-            role_parameters.max_actors < ROLE_PARAMETERS_MAX_ACTORS_MAX_VALUE,
-            Error::InvalidStorageRoleParameterMaxActors
-        );
-
-        ensure!(
-            role_parameters.reward_period
-                >= T::BlockNumber::from(ROLE_PARAMETERS_REWARD_PERIOD_MIN_VALUE),
-            Error::InvalidStorageRoleParameterRewardPeriod
-        );
-
-        ensure!(
-            role_parameters.reward_period
-                <= T::BlockNumber::from(ROLE_PARAMETERS_REWARD_PERIOD_MAX_VALUE),
-            Error::InvalidStorageRoleParameterRewardPeriod
-        );
-
-        ensure!(
-            role_parameters.bonding_period
-                >= T::BlockNumber::from(ROLE_PARAMETERS_BONDING_PERIOD_MIN_VALUE),
-            Error::InvalidStorageRoleParameterBondingPeriod
-        );
-
-        ensure!(
-            role_parameters.bonding_period
-                <= T::BlockNumber::from(ROLE_PARAMETERS_BONDING_PERIOD_MAX_VALUE),
-            Error::InvalidStorageRoleParameterBondingPeriod
-        );
-
-        ensure!(
-            role_parameters.unbonding_period
-                >= T::BlockNumber::from(ROLE_PARAMETERS_UNBONDING_PERIOD_MIN_VALUE),
-            Error::InvalidStorageRoleParameterUnbondingPeriod
-        );
-
-        ensure!(
-            role_parameters.unbonding_period
-                <= T::BlockNumber::from(ROLE_PARAMETERS_UNBONDING_PERIOD_MAX_VALUE),
-            Error::InvalidStorageRoleParameterUnbondingPeriod
-        );
-
-        ensure!(
-            role_parameters.min_service_period
-                >= T::BlockNumber::from(ROLE_PARAMETERS_MIN_SERVICE_PERIOD_MIN_VALUE),
-            Error::InvalidStorageRoleParameterMinServicePeriod
-        );
-
-        ensure!(
-            role_parameters.min_service_period
-                <= T::BlockNumber::from(ROLE_PARAMETERS_MIN_SERVICE_PERIOD_MAX_VALUE),
-            Error::InvalidStorageRoleParameterMinServicePeriod
-        );
-
-        ensure!(
-            role_parameters.startup_grace_period
-                >= T::BlockNumber::from(ROLE_PARAMETERS_STARTUP_GRACE_PERIOD_MIN_VALUE),
-            Error::InvalidStorageRoleParameterStartupGracePeriod
-        );
-
-        ensure!(
-            role_parameters.startup_grace_period
-                <= T::BlockNumber::from(ROLE_PARAMETERS_STARTUP_GRACE_PERIOD_MAX_VALUE),
-            Error::InvalidStorageRoleParameterStartupGracePeriod
-        );
-
-        ensure!(
-            role_parameters.min_stake
-                > <BalanceOfGovernanceCurrency<T>>::from(ROLE_PARAMETERS_MIN_STAKE_MIN_VALUE),
-            Error::InvalidStorageRoleParameterMinStake
-        );
-
-        ensure!(
-            role_parameters.min_stake
-                <= <BalanceOfGovernanceCurrency<T>>::from(ROLE_PARAMETERS_MIN_STAKE_MAX_VALUE),
-            Error::InvalidStorageRoleParameterMinStake
-        );
-
-        ensure!(
-            role_parameters.entry_request_fee
-                > <BalanceOfGovernanceCurrency<T>>::from(
-                    ROLE_PARAMETERS_ENTRY_REQUEST_FEE_MIN_VALUE
-                ),
-            Error::InvalidStorageRoleParameterEntryRequestFee
-        );
-
-        ensure!(
-            role_parameters.entry_request_fee
-                <= <BalanceOfGovernanceCurrency<T>>::from(
-                    ROLE_PARAMETERS_ENTRY_REQUEST_FEE_MAX_VALUE
-                ),
-            Error::InvalidStorageRoleParameterEntryRequestFee
-        );
-
-        ensure!(
-            role_parameters.reward
-                > <BalanceOfGovernanceCurrency<T>>::from(ROLE_PARAMETERS_REWARD_MIN_VALUE),
-            Error::InvalidStorageRoleParameterReward
-        );
-
-        ensure!(
-            role_parameters.reward
-                < <BalanceOfGovernanceCurrency<T>>::from(ROLE_PARAMETERS_REWARD_MAX_VALUE),
-            Error::InvalidStorageRoleParameterReward
-        );
-
-        Ok(())
-    }
-
-    /*
-    entry_request_fee [tJOY]	>0	<1%	NA
-    * Not enforced by runtime. Should not be displayed in the UI, or at least grayed out.
-    ** Should not be displayed in the UI, or at least grayed out.
-        */
-
     // validates council election parameters for the 'Set election parameters' proposal
     pub(crate) fn ensure_council_election_parameters_valid(
         election_parameters: &ElectionParameters<BalanceOfGovernanceCurrency<T>, T::BlockNumber>,
@@ -1074,17 +802,5 @@ impl<T: Trait> Module<T> {
         <SpendingProposalGracePeriod<T>>::put(T::BlockNumber::from(
             p.spending_proposal_grace_period,
         ));
-        <EvictStorageProviderProposalVotingPeriod<T>>::put(T::BlockNumber::from(
-            p.evict_storage_provider_proposal_voting_period,
-        ));
-        <EvictStorageProviderProposalGracePeriod<T>>::put(T::BlockNumber::from(
-            p.evict_storage_provider_proposal_grace_period,
-        ));
-        <SetStorageRoleParametersProposalVotingPeriod<T>>::put(T::BlockNumber::from(
-            p.set_storage_role_parameters_proposal_voting_period,
-        ));
-        <SetStorageRoleParametersProposalGracePeriod<T>>::put(T::BlockNumber::from(
-            p.set_storage_role_parameters_proposal_grace_period,
-        ));
     }
 }

+ 43 - 17
runtime-modules/proposals/codex/src/proposal_types/mod.rs

@@ -8,7 +8,6 @@ use rstd::vec::Vec;
 use serde::{Deserialize, Serialize};
 
 use crate::ElectionParameters;
-use roles::actors::RoleParameters;
 
 /// Encodes proposal using its details information.
 pub trait ProposalEncoder<T: crate::Trait> {
@@ -47,12 +46,16 @@ pub enum ProposalDetails<MintedBalance, CurrencyBalance, BlockNumber, AccountId,
     /// Balance for the `set content working group mint capacity` proposal
     SetContentWorkingGroupMintCapacity(MintedBalance),
 
+    /// ********** Deprecated during the Nicaea release.
+    /// It is kept only for backward compatibility in the Pioneer. **********
     /// AccountId for the `evict storage provider` proposal
     EvictStorageProvider(AccountId),
 
     /// Validator count for the `set validator count` proposal
     SetValidatorCount(u32),
 
+    /// ********** Deprecated during the Nicaea release.
+    /// It is kept only for backward compatibility in the Pioneer. **********
     /// Role parameters for the `set storage role parameters` proposal
     SetStorageRoleParameters(RoleParameters<CurrencyBalance, BlockNumber>),
 }
@@ -65,6 +68,45 @@ impl<MintedBalance, CurrencyBalance, BlockNumber, AccountId, MemberId> Default
     }
 }
 
+/// ********** Deprecated during the Nicaea release.
+/// It is kept only for backward compatibility in the Pioneer. **********
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, Debug)]
+pub struct RoleParameters<Balance, BlockNumber> {
+    /// Minimum balance required to stake to enter a role.
+    pub min_stake: Balance,
+
+    /// Minimum actors to maintain - if role is unstaking
+    /// and remaining actors would be less that this value - prevent or punish for unstaking.
+    pub min_actors: u32,
+
+    /// The maximum number of spots available to fill for a role.
+    pub max_actors: u32,
+
+    /// Fixed amount of tokens paid to actors' primary account.
+    pub reward: Balance,
+
+    /// Payouts are made at this block interval.
+    pub reward_period: BlockNumber,
+
+    /// Minimum amount of time before being able to unstake.
+    pub bonding_period: BlockNumber,
+
+    /// How long tokens remain locked for after unstaking.
+    pub unbonding_period: BlockNumber,
+
+    /// Minimum period required to be in service. unbonding before this time is highly penalized
+    pub min_service_period: BlockNumber,
+
+    /// "Startup" time allowed for roles that need to sync their infrastructure
+    /// with other providers before they are considered in service and punishable for
+    /// not delivering required level of service.
+    pub startup_grace_period: BlockNumber,
+
+    /// Small fee burned to make a request to enter role.
+    pub entry_request_fee: Balance,
+}
+
 /// Contains proposal config parameters. Default values are used by migration and genesis config.
 pub struct ProposalsConfigParameters {
     /// 'Set validator count' proposal voting period
@@ -108,18 +150,6 @@ pub struct ProposalsConfigParameters {
 
     /// 'Spending' proposal grace period
     pub spending_proposal_grace_period: u32,
-
-    /// 'Evict storage provider' proposal voting period
-    pub evict_storage_provider_proposal_voting_period: u32,
-
-    /// 'Evict storage provider' proposal grace period
-    pub evict_storage_provider_proposal_grace_period: u32,
-
-    /// 'Set storage role parameters' proposal voting period
-    pub set_storage_role_parameters_proposal_voting_period: u32,
-
-    /// 'Set storage role parameters' proposal grace period
-    pub set_storage_role_parameters_proposal_grace_period: u32,
 }
 
 impl Default for ProposalsConfigParameters {
@@ -139,10 +169,6 @@ impl Default for ProposalsConfigParameters {
             set_lead_proposal_grace_period: 0u32,
             spending_proposal_voting_period: 72000u32,
             spending_proposal_grace_period: 14400u32,
-            evict_storage_provider_proposal_voting_period: 43200u32,
-            evict_storage_provider_proposal_grace_period: 0u32,
-            set_storage_role_parameters_proposal_voting_period: 43200u32,
-            set_storage_role_parameters_proposal_grace_period: 14400u32,
         }
     }
 }

+ 0 - 28
runtime-modules/proposals/codex/src/proposal_types/parameters.rs

@@ -97,31 +97,3 @@ pub(crate) fn set_lead_proposal<T: crate::Trait>(
         required_stake: Some(<BalanceOf<T>>::from(50000u32)),
     }
 }
-
-// Proposal parameters for the 'Evict storage provider' proposal
-pub(crate) fn evict_storage_provider_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
-    ProposalParameters {
-        voting_period: <Module<T>>::evict_storage_provider_proposal_voting_period(),
-        grace_period: <Module<T>>::evict_storage_provider_proposal_grace_period(),
-        approval_quorum_percentage: 50,
-        approval_threshold_percentage: 75,
-        slashing_quorum_percentage: 60,
-        slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(25000u32)),
-    }
-}
-
-// Proposal parameters for the 'Set storage role parameters' proposal
-pub(crate) fn set_storage_role_parameters_proposal<T: crate::Trait>(
-) -> ProposalParameters<T::BlockNumber, BalanceOf<T>> {
-    ProposalParameters {
-        voting_period: <Module<T>>::set_storage_role_parameters_proposal_voting_period(),
-        grace_period: <Module<T>>::set_storage_role_parameters_proposal_grace_period(),
-        approval_quorum_percentage: 66,
-        approval_threshold_percentage: 80,
-        slashing_quorum_percentage: 60,
-        slashing_threshold_percentage: 80,
-        required_stake: Some(<BalanceOf<T>>::from(100_000_u32)),
-    }
-}

+ 0 - 9
runtime-modules/proposals/codex/src/tests/mock.rs

@@ -193,15 +193,6 @@ impl hiring::Trait for Test {
     type StakeHandlerProvider = hiring::Module<Self>;
 }
 
-impl roles::actors::Trait for Test {
-    type Event = ();
-    type OnActorRemoved = ();
-}
-
-impl roles::actors::ActorRemoved<Test> for () {
-    fn actor_removed(_: &u64) {}
-}
-
 srml_staking_reward_curve::build! {
     const I_NPOS: PiecewiseLinear<'static> = curve!(
         min_inflation: 0_025_000,

+ 0 - 287
runtime-modules/proposals/codex/src/tests/mod.rs

@@ -8,7 +8,6 @@ use system::RawOrigin;
 use crate::*;
 use crate::{BalanceOf, Error, ProposalDetails};
 use proposal_engine::ProposalParameters;
-use roles::actors::RoleParameters;
 use srml_support::dispatch::DispatchResult;
 
 use crate::proposal_types::ProposalsConfigParameters;
@@ -707,59 +706,6 @@ fn create_set_lead_proposal_common_checks_succeed() {
     });
 }
 
-#[test]
-fn create_evict_storage_provider_proposal_common_checks_succeed() {
-    initial_test_ext().execute_with(|| {
-        increase_total_balance_issuance(500000);
-
-        let proposal_fixture = ProposalTestFixture {
-            insufficient_rights_call: || {
-                ProposalCodex::create_evict_storage_provider_proposal(
-                    RawOrigin::None.into(),
-                    1,
-                    b"title".to_vec(),
-                    b"body".to_vec(),
-                    None,
-                    1,
-                )
-            },
-            empty_stake_call: || {
-                ProposalCodex::create_evict_storage_provider_proposal(
-                    RawOrigin::Signed(1).into(),
-                    1,
-                    b"title".to_vec(),
-                    b"body".to_vec(),
-                    None,
-                    1,
-                )
-            },
-            invalid_stake_call: || {
-                ProposalCodex::create_evict_storage_provider_proposal(
-                    RawOrigin::Signed(1).into(),
-                    1,
-                    b"title".to_vec(),
-                    b"body".to_vec(),
-                    Some(<BalanceOf<Test>>::from(5000u32)),
-                    1,
-                )
-            },
-            successful_call: || {
-                ProposalCodex::create_evict_storage_provider_proposal(
-                    RawOrigin::Signed(1).into(),
-                    1,
-                    b"title".to_vec(),
-                    b"body".to_vec(),
-                    Some(<BalanceOf<Test>>::from(25000u32)),
-                    1,
-                )
-            },
-            proposal_parameters: crate::proposal_types::parameters::evict_storage_provider_proposal::<Test>(),
-            proposal_details: ProposalDetails::EvictStorageProvider(1),
-        };
-        proposal_fixture.check_all();
-    });
-}
-
 #[test]
 fn create_set_validator_count_proposal_common_checks_succeed() {
     initial_test_ext().execute_with(|| {
@@ -844,223 +790,6 @@ fn create_set_validator_count_proposal_failed_with_invalid_validator_count() {
     });
 }
 
-#[test]
-fn create_set_storage_role_parameters_proposal_common_checks_succeed() {
-    initial_test_ext().execute_with(|| {
-        increase_total_balance_issuance_using_account_id(1, 500000);
-        let role_parameters = RoleParameters {
-            min_actors: 1,
-            ..RoleParameters::default()
-        };
-        let proposal_fixture = ProposalTestFixture {
-            insufficient_rights_call: || {
-                ProposalCodex::create_set_storage_role_parameters_proposal(
-                    RawOrigin::None.into(),
-                    1,
-                    b"title".to_vec(),
-                    b"body".to_vec(),
-                    None,
-                    role_parameters.clone(),
-                )
-            },
-            empty_stake_call: || {
-                ProposalCodex::create_set_storage_role_parameters_proposal(
-                    RawOrigin::Signed(1).into(),
-                    1,
-                    b"title".to_vec(),
-                    b"body".to_vec(),
-                    None,
-                    role_parameters.clone(),
-                )
-            },
-            invalid_stake_call: || {
-                ProposalCodex::create_set_storage_role_parameters_proposal(
-                    RawOrigin::Signed(1).into(),
-                    1,
-                    b"title".to_vec(),
-                    b"body".to_vec(),
-                    Some(<BalanceOf<Test>>::from(5000u32)),
-                    role_parameters.clone(),
-                )
-            },
-            successful_call: || {
-                ProposalCodex::create_set_storage_role_parameters_proposal(
-                    RawOrigin::Signed(1).into(),
-                    1,
-                    b"title".to_vec(),
-                    b"body".to_vec(),
-                    Some(<BalanceOf<Test>>::from(100_000_u32)),
-                    role_parameters.clone(),
-                )
-            },
-            proposal_parameters:
-                crate::proposal_types::parameters::set_storage_role_parameters_proposal::<Test>(),
-            proposal_details: ProposalDetails::SetStorageRoleParameters(role_parameters),
-        };
-        proposal_fixture.check_all();
-    });
-}
-
-fn assert_failed_set_storage_parameters_call(
-    role_parameters: RoleParameters<u64, u64>,
-    error: Error,
-) {
-    assert_eq!(
-        ProposalCodex::create_set_storage_role_parameters_proposal(
-            RawOrigin::Signed(1).into(),
-            1,
-            b"title".to_vec(),
-            b"body".to_vec(),
-            Some(<BalanceOf<Test>>::from(100_000_u32)),
-            role_parameters,
-        ),
-        Err(error)
-    );
-}
-
-#[test]
-fn create_set_storage_role_parameters_proposal_fails_with_invalid_parameters() {
-    initial_test_ext().execute_with(|| {
-        increase_total_balance_issuance_using_account_id(1, 500000);
-
-        let working_role_parameters = RoleParameters {
-            min_actors: 1,
-            ..RoleParameters::default()
-        };
-        let mut role_parameters = working_role_parameters.clone();
-        role_parameters.min_actors = 2;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterMinActors,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.max_actors = 1;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterMaxActors,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.max_actors = 100;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterMaxActors,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.reward_period = 599;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterRewardPeriod,
-        );
-
-        role_parameters.reward_period = 28801;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterRewardPeriod,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.bonding_period = 599;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterBondingPeriod,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.bonding_period = 28801;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterBondingPeriod,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.unbonding_period = 599;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterUnbondingPeriod,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.unbonding_period = 28801;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterUnbondingPeriod,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.min_service_period = 599;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterMinServicePeriod,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.min_service_period = 28801;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterMinServicePeriod,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.startup_grace_period = 599;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterStartupGracePeriod,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.startup_grace_period = 28801;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterStartupGracePeriod,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.min_stake = 0;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterMinStake,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.min_stake = 10000001;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterMinStake,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.entry_request_fee = 0;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterEntryRequestFee,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.entry_request_fee = 100001;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterEntryRequestFee,
-        );
-
-        role_parameters = working_role_parameters.clone();
-        role_parameters.reward = 0;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterReward,
-        );
-
-        role_parameters = working_role_parameters;
-        role_parameters.reward = 100_000;
-        assert_failed_set_storage_parameters_call(
-            role_parameters,
-            Error::InvalidStorageRoleParameterReward,
-        );
-    });
-}
-
 #[test]
 fn set_default_proposal_parameters_succeeded() {
     initial_test_ext().execute_with(|| {
@@ -1127,21 +856,5 @@ fn set_default_proposal_parameters_succeeded() {
             <SpendingProposalGracePeriod<Test>>::get(),
             p.spending_proposal_grace_period as u64
         );
-        assert_eq!(
-            <EvictStorageProviderProposalVotingPeriod<Test>>::get(),
-            p.evict_storage_provider_proposal_voting_period as u64
-        );
-        assert_eq!(
-            <EvictStorageProviderProposalGracePeriod<Test>>::get(),
-            p.evict_storage_provider_proposal_grace_period as u64
-        );
-        assert_eq!(
-            <SetStorageRoleParametersProposalVotingPeriod<Test>>::get(),
-            p.set_storage_role_parameters_proposal_voting_period as u64
-        );
-        assert_eq!(
-            <SetStorageRoleParametersProposalGracePeriod<Test>>::get(),
-            p.set_storage_role_parameters_proposal_grace_period as u64
-        );
     });
 }

+ 0 - 88
runtime-modules/roles/Cargo.toml

@@ -1,88 +0,0 @@
-[package]
-name = 'substrate-roles-module'
-version = '1.0.1'
-authors = ['Joystream contributors']
-edition = '2018'
-
-[features]
-default = ['std']
-std = [
-	'sr-primitives/std',
-	'srml-support/std',
-	'system/std',
-	'rstd/std',
-	'codec/std',
-	'serde',
-	'common/std',
-	'membership/std',
-]
-
-
-[dependencies.sr-primitives]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'sr-primitives'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dependencies.srml-support]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'srml-support'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dependencies.system]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'srml-system'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dependencies.rstd]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'sr-std'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dependencies.codec]
-default-features = false
-features = ['derive']
-package = 'parity-scale-codec'
-version = '1.0.0'
-
-[dependencies.serde]
-features = ['derive']
-optional = true
-version = '1.0.101'
-
-[dependencies.membership]
-default_features = false
-package = 'substrate-membership-module'
-path = '../membership'
-
-[dependencies.common]
-default_features = false
-package = 'substrate-common-module'
-path = '../common'
-
-[dev-dependencies.runtime-io]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'sr-io'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dev-dependencies.balances]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'srml-balances'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dev-dependencies.timestamp]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'srml-timestamp'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
-
-[dev-dependencies.primitives]
-default_features = false
-git = 'https://github.com/paritytech/substrate.git'
-package = 'substrate-primitives'
-rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'

+ 0 - 425
runtime-modules/roles/src/actors.rs

@@ -1,425 +0,0 @@
-// Clippy linter warning
-#![allow(clippy::redundant_closure_call)] // disable it because of the substrate lib design
-                                          // example:  pub Parameters get(parameters) build(|config: &GenesisConfig| {..}
-
-use codec::{Decode, Encode};
-use common::currency::{BalanceOf, GovernanceCurrency};
-use rstd::prelude::*;
-use sr_primitives::traits::{Bounded, Zero};
-use srml_support::traits::{
-    Currency, LockIdentifier, LockableCurrency, WithdrawReason, WithdrawReasons,
-};
-use srml_support::{decl_event, decl_module, decl_storage, ensure};
-use system::{self, ensure_root, ensure_signed};
-
-#[cfg(feature = "std")]
-use serde::{Deserialize, Serialize};
-
-pub use membership::members::Role;
-
-const STAKING_ID: LockIdentifier = *b"role_stk";
-
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, Debug)]
-pub struct RoleParameters<Balance, BlockNumber> {
-    // minium balance required to stake to enter a role
-    pub min_stake: Balance,
-
-    // minimum actors to maintain - if role is unstaking
-    // and remaining actors would be less that this value - prevent or punish for unstaking
-    pub min_actors: u32,
-
-    // the maximum number of spots available to fill for a role
-    pub max_actors: u32,
-
-    // fixed amount of tokens paid to actors' primary account
-    pub reward: Balance,
-
-    // payouts are made at this block interval
-    pub reward_period: BlockNumber,
-
-    // minimum amount of time before being able to unstake
-    pub bonding_period: BlockNumber,
-
-    // how long tokens remain locked for after unstaking
-    pub unbonding_period: BlockNumber,
-
-    // minimum period required to be in service. unbonding before this time is highly penalized
-    pub min_service_period: BlockNumber,
-
-    // "startup" time allowed for roles that need to sync their infrastructure
-    // with other providers before they are considered in service and punishable for
-    // not delivering required level of service.
-    pub startup_grace_period: BlockNumber,
-
-    // small fee burned to make a request to enter role
-    pub entry_request_fee: Balance,
-}
-
-impl<Balance: From<u32>, BlockNumber: From<u32>> Default for RoleParameters<Balance, BlockNumber> {
-    fn default() -> Self {
-        Self {
-            min_stake: Balance::from(3000),
-            max_actors: 10,
-            reward: Balance::from(10),
-            reward_period: BlockNumber::from(600),
-            unbonding_period: BlockNumber::from(600),
-            entry_request_fee: Balance::from(50),
-
-            // not currently used
-            min_actors: 1,
-            bonding_period: BlockNumber::from(600),
-            min_service_period: BlockNumber::from(600),
-            startup_grace_period: BlockNumber::from(600),
-        }
-    }
-}
-
-#[derive(Encode, Decode, Clone)]
-pub struct Actor<T: Trait> {
-    pub member_id: MemberId<T>,
-    pub role: Role,
-    pub account: T::AccountId,
-    pub joined_at: T::BlockNumber,
-}
-
-pub trait ActorRemoved<T: Trait> {
-    fn actor_removed(actor: &T::AccountId);
-}
-
-pub trait Trait: system::Trait + GovernanceCurrency + membership::members::Trait {
-    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
-
-    type OnActorRemoved: ActorRemoved<Self>;
-}
-
-pub type MemberId<T> = <T as membership::members::Trait>::MemberId;
-// actor account, memberid, role, expires
-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 DEFAULT_REQUEST_LIFETIME: u32 = 300;
-pub const REQUEST_CLEARING_INTERVAL: u32 = 100;
-
-decl_storage! {
-    trait Store for Module<T: Trait> as Actors {
-        /// requirements to enter and maintain status in roles
-        pub Parameters get(parameters) build(|config: &GenesisConfig| {
-            if config.enable_storage_role {
-                let storage_params: RoleParameters<BalanceOf<T>, T::BlockNumber> = Default::default();
-                vec![(Role::StorageProvider, storage_params)]
-            } else {
-                vec![]
-            }
-        }): map Role => Option<RoleParameters<BalanceOf<T>, T::BlockNumber>>;
-
-        /// the roles members can enter into
-        pub AvailableRoles get(available_roles) build(|config: &GenesisConfig| {
-            if config.enable_storage_role {
-                vec![(Role::StorageProvider)]
-            } else {
-                vec![]
-            }
-        }): Vec<Role>;
-
-        /// Actors list
-        pub ActorAccountIds get(actor_account_ids) : Vec<T::AccountId>;
-
-        /// actor accounts mapped to their actor
-        pub ActorByAccountId get(actor_by_account_id) : map T::AccountId => Option<Actor<T>>;
-
-        /// actor accounts associated with a role
-        pub AccountIdsByRole get(account_ids_by_role) : map Role => Vec<T::AccountId>;
-
-        /// actor accounts associated with a member id
-        pub AccountIdsByMemberId get(account_ids_by_member_id) : map MemberId<T> => Vec<T::AccountId>;
-
-        /// First step before enter a role is registering intent with a new account/key.
-        /// This is done by sending a role_entry_request() from the new account.
-        /// The member must then send a stake() transaction to approve the request and enter the desired role.
-        /// The account making the request will be bonded and must have
-        /// sufficient balance to cover the minimum stake for the role.
-        /// Bonding only occurs after successful entry into a role.
-        pub RoleEntryRequests get(role_entry_requests) : Requests<T>;
-
-        /// Entry request expires after this number of blocks
-        pub RequestLifeTime get(request_life_time) config(request_life_time) : u32 = DEFAULT_REQUEST_LIFETIME;
-    }
-    add_extra_genesis {
-        config(enable_storage_role): bool;
-    }
-}
-
-decl_event! {
-    pub enum Event<T> where
-      <T as system::Trait>::AccountId {
-        EntryRequested(AccountId, Role),
-        Staked(AccountId, Role),
-        Unstaked(AccountId, Role),
-    }
-}
-
-impl<T: Trait> Module<T> {
-    fn is_role_available(role: Role) -> bool {
-        Self::available_roles().into_iter().any(|r| role == r)
-    }
-
-    fn ensure_actor(role_key: &T::AccountId) -> Result<Actor<T>, &'static str> {
-        Self::actor_by_account_id(role_key).ok_or("not role key")
-    }
-
-    fn ensure_role_parameters(
-        role: Role,
-    ) -> Result<RoleParameters<BalanceOf<T>, T::BlockNumber>, &'static str> {
-        Self::parameters(role).ok_or("no parameters for role")
-    }
-
-    // Mutating
-
-    fn remove_actor_from_service(actor_account: T::AccountId, role: Role, member_id: MemberId<T>) {
-        let accounts: Vec<T::AccountId> = Self::account_ids_by_role(role)
-            .into_iter()
-            .filter(|account| *account != actor_account)
-            .collect();
-        <AccountIdsByRole<T>>::insert(role, accounts);
-
-        let accounts: Vec<T::AccountId> = Self::account_ids_by_member_id(&member_id)
-            .into_iter()
-            .filter(|account| *account != actor_account)
-            .collect();
-        <AccountIdsByMemberId<T>>::insert(&member_id, accounts);
-
-        let accounts: Vec<T::AccountId> = Self::actor_account_ids()
-            .into_iter()
-            .filter(|account| *account != actor_account)
-            .collect();
-        <ActorAccountIds<T>>::put(accounts);
-
-        <ActorByAccountId<T>>::remove(&actor_account);
-
-        T::OnActorRemoved::actor_removed(&actor_account);
-    }
-
-    fn apply_unstake(
-        actor_account: T::AccountId,
-        role: Role,
-        member_id: MemberId<T>,
-        unbonding_period: T::BlockNumber,
-        stake: BalanceOf<T>,
-    ) {
-        // simple unstaking ...only applying unbonding period
-        Self::update_lock(
-            &actor_account,
-            stake,
-            <system::Module<T>>::block_number() + unbonding_period,
-        );
-
-        Self::remove_actor_from_service(actor_account, role, member_id);
-    }
-
-    // Locks account and only allows paying for transaction fees. Account cannot
-    // transfer or reserve funds.
-    fn update_lock(account: &T::AccountId, stake: BalanceOf<T>, until: T::BlockNumber) {
-        T::Currency::set_lock(
-            STAKING_ID,
-            account,
-            stake,
-            until,
-            WithdrawReasons::all() & !(WithdrawReason::TransactionPayment | WithdrawReason::Fee),
-        );
-    }
-
-    pub fn is_role_account(account_id: &T::AccountId) -> bool {
-        <ActorByAccountId<T>>::exists(account_id)
-    }
-
-    pub fn account_has_role(account_id: &T::AccountId, role: Role) -> bool {
-        Self::actor_by_account_id(account_id).map_or(false, |actor| actor.role == role)
-    }
-}
-
-decl_module! {
-    pub struct Module<T: Trait> for enum Call where origin: T::Origin {
-        fn deposit_event() = default;
-
-        fn on_initialize(now: T::BlockNumber) {
-            // clear expired requests
-            if now % T::BlockNumber::from(REQUEST_CLEARING_INTERVAL) == T::BlockNumber::zero() {
-                let requests: Requests<T> = Self::role_entry_requests()
-                    .into_iter()
-                    .filter(|request| request.3 > now)
-                    .collect();
-
-                <RoleEntryRequests<T>>::put(requests);
-            }
-        }
-
-        fn on_finalize(now: T::BlockNumber) {
-
-            // payout rewards to actors
-            for role in Self::available_roles().iter() {
-                if let Some(params) = Self::parameters(role) {
-                    if !(now % params.reward_period == T::BlockNumber::zero()) { continue }
-                    let accounts = Self::account_ids_by_role(role);
-                    for actor in accounts.into_iter().map(Self::actor_by_account_id) {
-                        if let Some(actor) = actor {
-                            if now > actor.joined_at + params.reward_period {
-                                // reward can top up balance if it is below minimum stake requirement
-                                // this guarantees overtime that actor always covers the minimum stake and
-                                // has enough balance to pay for tx fees
-                                let balance = T::Currency::free_balance(&actor.account);
-                                if balance < params.min_stake {
-                                    let _ = T::Currency::deposit_into_existing(&actor.account, params.reward);
-                                } else {
-                                    // otherwise it should go the the member's root account
-                                    if let Some(profile) = <membership::members::Module<T>>::member_profile(&actor.member_id) {
-                                        let _ = T::Currency::deposit_into_existing(&profile.root_account, params.reward);
-                                    }
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-        }
-
-        pub fn role_entry_request(origin, role: Role, member_id: MemberId<T>) {
-            let sender = ensure_signed(origin)?;
-
-            ensure!(!Self::is_role_account(&sender), "account already used");
-
-            ensure!(Self::is_role_available(role), "inactive role");
-
-            let role_parameters = Self::ensure_role_parameters(role)?;
-
-            <membership::members::Module<T>>::ensure_profile(member_id)?;
-
-            // pay (burn) entry fee - spam filter
-            let fee = role_parameters.entry_request_fee;
-            ensure!(T::Currency::can_slash(&sender, fee), "cannot pay role entry request fee");
-            let _ = T::Currency::slash(&sender, fee);
-
-            <RoleEntryRequests<T>>::mutate(|requests| {
-                let expires = <system::Module<T>>::block_number()+ T::BlockNumber::from(Self::request_life_time());
-                requests.push((sender.clone(), member_id, role, expires));
-            });
-            Self::deposit_event(RawEvent::EntryRequested(sender, role));
-        }
-
-        /// Member activating entry request
-        pub fn stake(origin, role: Role, actor_account: T::AccountId) {
-            let sender = ensure_signed(origin)?;
-            ensure!(<membership::members::Module<T>>::is_member_account(&sender), "members only can accept storage entry request");
-
-            // get member ids from requests that are controller by origin
-            let ids = Self::role_entry_requests()
-                .iter()
-                .filter(|request| request.0 == actor_account && request.2 == role)
-                .map(|request| request.1)
-                .filter(|member_id|
-                    <membership::members::Module<T>>::ensure_profile(*member_id)
-                        .ok()
-                        .map_or(false, |profile| profile.root_account == sender || profile.controller_account == sender)
-                )
-                .collect::<Vec<_>>();
-
-            ensure!(!ids.is_empty(), "no role entry request matches");
-
-            // take first matching id
-            let member_id = ids[0];
-
-            ensure!(!Self::is_role_account(&actor_account), "account already used");
-
-            // make sure role is still available
-            ensure!(Self::is_role_available(role), "inactive role");
-            let role_parameters = Self::ensure_role_parameters(role)?;
-
-            let accounts_in_role = Self::account_ids_by_role(role);
-
-            // ensure there is an empty slot for the role
-            ensure!(accounts_in_role.len() < role_parameters.max_actors as usize, "role slots full");
-
-            // ensure the actor account has enough balance
-            ensure!(T::Currency::free_balance(&actor_account) >= role_parameters.min_stake, "not enough balance to stake");
-
-            <AccountIdsByRole<T>>::mutate(role, |accounts| accounts.push(actor_account.clone()));
-            <AccountIdsByMemberId<T>>::mutate(&member_id, |accounts| accounts.push(actor_account.clone()));
-
-            // Lock minimum stake, but allow spending for transaction fees
-            Self::update_lock(&actor_account, role_parameters.min_stake, T::BlockNumber::max_value());
-            <ActorByAccountId<T>>::insert(&actor_account, Actor {
-                member_id,
-                account: actor_account.clone(),
-                role,
-                joined_at: <system::Module<T>>::block_number()
-            });
-            <ActorAccountIds<T>>::mutate(|accounts| accounts.push(actor_account.clone()));
-
-            let requests: Requests<T> = Self::role_entry_requests()
-                .into_iter()
-                .filter(|request| request.0 != actor_account)
-                .collect();
-            <RoleEntryRequests<T>>::put(requests);
-
-            Self::deposit_event(RawEvent::Staked(actor_account, role));
-        }
-
-        pub fn unstake(origin, actor_account: T::AccountId) {
-            let sender = ensure_signed(origin)?;
-            let actor = Self::ensure_actor(&actor_account)?;
-
-            let profile = <membership::members::Module<T>>::ensure_profile(actor.member_id)?;
-            ensure!(profile.root_account == sender || profile.controller_account == sender, "only member can unstake storage provider");
-
-            let role_parameters = Self::ensure_role_parameters(actor.role)?;
-
-            Self::apply_unstake(actor.account.clone(), actor.role, actor.member_id, role_parameters.unbonding_period, role_parameters.min_stake);
-
-            Self::deposit_event(RawEvent::Unstaked(actor.account, actor.role));
-        }
-
-        pub fn set_role_parameters(origin, role: Role, params: RoleParameters<BalanceOf<T>, T::BlockNumber>) {
-            ensure_root(origin)?;
-            let new_stake = params.min_stake;
-            <Parameters<T>>::insert(role, params);
-            // Update locks for all actors in the role. The lock for each account is already until max_value
-            // It doesn't affect actors which are unbonding, they should have already been removed from AccountIdsByRole
-            let accounts = Self::account_ids_by_role(role);
-            for account in accounts.into_iter() {
-                Self::update_lock(&account, new_stake, T::BlockNumber::max_value());
-            }
-        }
-
-        pub fn set_available_roles(origin, roles: Vec<Role>) {
-            ensure_root(origin)?;
-            AvailableRoles::put(roles);
-        }
-
-        pub fn add_to_available_roles(origin, role: Role) {
-            ensure_root(origin)?;
-            if !Self::available_roles().into_iter().any(|r| r == role) {
-                AvailableRoles::mutate(|roles| roles.push(role));
-            }
-        }
-
-        pub fn remove_from_available_roles(origin, role: Role) {
-            ensure_root(origin)?;
-            // Should we eject actors in the role being removed?
-            let roles: Vec<Role> = Self::available_roles().into_iter().filter(|r| role != *r).collect();
-            AvailableRoles::put(roles);
-        }
-
-        pub fn remove_actor(origin, actor_account: T::AccountId) {
-            ensure_root(origin)?;
-            ensure!(<ActorByAccountId<T>>::exists(&actor_account), "error trying to remove non actor account");
-            let actor = Self::actor_by_account_id(&actor_account).unwrap();
-            let role_parameters = Self::ensure_role_parameters(actor.role)?;
-            Self::apply_unstake(actor_account, actor.role, actor.member_id, role_parameters.unbonding_period, role_parameters.min_stake);
-        }
-    }
-}

+ 0 - 8
runtime-modules/roles/src/lib.rs

@@ -1,8 +0,0 @@
-// Ensure we're `no_std` when compiling for Wasm.
-#![cfg_attr(not(feature = "std"), no_std)]
-
-pub mod actors;
-pub mod traits;
-
-mod mock;
-mod tests;

+ 0 - 130
runtime-modules/roles/src/mock.rs

@@ -1,130 +0,0 @@
-#![cfg(test)]
-
-pub use super::actors;
-pub use common::currency::GovernanceCurrency;
-pub use srml_support::traits::Currency;
-pub use system;
-
-pub use primitives::{Blake2Hasher, H256};
-pub use sr_primitives::{
-    testing::{Digest, DigestItem, Header, UintAuthorityId},
-    traits::{BlakeTwo256, Convert, IdentityLookup, OnFinalize},
-    weights::Weight,
-    BuildStorage, Perbill,
-};
-
-use srml_support::{impl_outer_origin, parameter_types};
-
-impl_outer_origin! {
-    pub enum Origin for Test {}
-}
-
-pub fn alice_id() -> u32 {
-    Members::member_ids_by_root_account_id(alice_account())[0]
-}
-pub fn alice_account() -> u64 {
-    1
-}
-
-// Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted.
-#[derive(Clone, PartialEq, Eq, Debug)]
-pub struct Test;
-parameter_types! {
-    pub const BlockHashCount: u64 = 250;
-    pub const MaximumBlockWeight: u32 = 1024;
-    pub const MaximumBlockLength: u32 = 2 * 1024;
-    pub const AvailableBlockRatio: Perbill = Perbill::one();
-    pub const MinimumPeriod: u64 = 5;
-}
-
-impl system::Trait for Test {
-    type Origin = Origin;
-    type Index = u64;
-    type BlockNumber = u64;
-    type Call = ();
-    type Hash = H256;
-    type Hashing = BlakeTwo256;
-    type AccountId = u64;
-    type Lookup = IdentityLookup<Self::AccountId>;
-    type Header = Header;
-    type Event = ();
-    type BlockHashCount = BlockHashCount;
-    type MaximumBlockWeight = MaximumBlockWeight;
-    type MaximumBlockLength = MaximumBlockLength;
-    type AvailableBlockRatio = AvailableBlockRatio;
-    type Version = ();
-}
-
-parameter_types! {
-    pub const ExistentialDeposit: u32 = 0;
-    pub const TransferFee: u32 = 0;
-    pub const CreationFee: u32 = 0;
-    pub const TransactionBaseFee: u32 = 1;
-    pub const TransactionByteFee: u32 = 0;
-    pub const InitialMembersBalance: u32 = 2000;
-}
-
-impl balances::Trait for Test {
-    /// The type for recording an account's balance.
-    type Balance = u64;
-    /// What to do if an account's free balance gets zeroed.
-    type OnFreeBalanceZero = ();
-    /// What to do if a new account is created.
-    type OnNewAccount = ();
-    /// The ubiquitous event type.
-    type Event = ();
-
-    type DustRemoval = ();
-    type TransferPayment = ();
-    type ExistentialDeposit = ExistentialDeposit;
-    type TransferFee = TransferFee;
-    type CreationFee = CreationFee;
-}
-
-impl GovernanceCurrency for Test {
-    type Currency = balances::Module<Self>;
-}
-
-impl timestamp::Trait for Test {
-    type Moment = u64;
-    type OnTimestampSet = ();
-    type MinimumPeriod = MinimumPeriod;
-}
-
-impl membership::members::Trait for Test {
-    type Event = ();
-    type MemberId = u32;
-    type SubscriptionId = u32;
-    type PaidTermId = u32;
-    type ActorId = u32;
-    type InitialMembersBalance = InitialMembersBalance;
-}
-
-impl actors::Trait for Test {
-    type Event = ();
-    type OnActorRemoved = ();
-}
-
-impl actors::ActorRemoved<Test> for () {
-    fn actor_removed(_: &u64) {}
-}
-
-pub fn initial_test_ext() -> runtime_io::TestExternalities {
-    let mut t = system::GenesisConfig::default()
-        .build_storage::<Test>()
-        .unwrap();
-
-    membership::members::GenesisConfig::<Test> {
-        default_paid_membership_fee: 0,
-        members: vec![(alice_account(), "alice".into(), "".into(), "".into())],
-    }
-    .assimilate_storage(&mut t)
-    .unwrap();
-
-    t.into()
-}
-
-pub type System = system::Module<Test>;
-pub type Balances = balances::Module<Test>;
-pub type Actors = actors::Module<Test>;
-pub type Members = membership::members::Module<Test>;

+ 0 - 204
runtime-modules/roles/src/tests.rs

@@ -1,204 +0,0 @@
-#![cfg(test)]
-
-use super::mock::*;
-
-use srml_support::*;
-
-fn init_storage_role() {
-    let roles: Vec<actors::Role> = vec![actors::Role::StorageProvider];
-    assert!(
-        Actors::set_available_roles(system::RawOrigin::Root.into(), roles).is_ok(),
-        ""
-    );
-}
-
-fn init_storage_parmeters() -> actors::RoleParameters<u64, u64> {
-    let params = actors::RoleParameters {
-        // minium balance required to stake to enter a role
-        min_stake: 100 as u64,
-        min_actors: 1 as u32,
-        max_actors: 2 as u32,
-        reward: 100 as u64,
-        reward_period: 100 as u64,
-        bonding_period: 100 as u64,
-        unbonding_period: 100 as u64,
-        min_service_period: 100 as u64,
-        startup_grace_period: 100 as u64,
-        entry_request_fee: 10 as u64,
-    };
-    assert!(
-        Actors::set_role_parameters(
-            system::RawOrigin::Root.into(),
-            actors::Role::StorageProvider,
-            params.clone()
-        )
-        .is_ok(),
-        ""
-    );
-    params
-}
-
-#[test]
-fn adding_roles() {
-    initial_test_ext().execute_with(|| {
-        init_storage_role();
-        assert_eq!(
-            Actors::available_roles(),
-            vec![actors::Role::StorageProvider]
-        );
-    });
-}
-
-#[test]
-fn adding_role_parameters() {
-    initial_test_ext().execute_with(|| {
-        init_storage_role();
-        let params = init_storage_parmeters();
-        assert_eq!(
-            Actors::parameters(actors::Role::StorageProvider),
-            Some(params)
-        );
-    });
-}
-
-#[test]
-fn make_entry_request() {
-    initial_test_ext().execute_with(|| {
-        init_storage_role();
-        let storage_params = init_storage_parmeters();
-
-        let actor_account = 5 as u64;
-
-        let starting_block = 1;
-        System::set_block_number(starting_block);
-
-        let requests = Actors::role_entry_requests();
-        assert_eq!(requests.len(), 0);
-
-        assert!(
-            Actors::role_entry_request(
-                Origin::signed(actor_account),
-                actors::Role::StorageProvider,
-                alice_id()
-            )
-            .is_err(),
-            ""
-        );
-
-        let surplus_balance = 100;
-        let _ = Balances::deposit_creating(
-            &actor_account,
-            storage_params.entry_request_fee + surplus_balance,
-        );
-
-        assert!(
-            Actors::role_entry_request(
-                Origin::signed(actor_account),
-                actors::Role::StorageProvider,
-                alice_id()
-            )
-            .is_ok(),
-            ""
-        );
-
-        assert_eq!(Balances::free_balance(&actor_account), surplus_balance);
-
-        let requests = Actors::role_entry_requests();
-        assert_eq!(requests.len(), 1);
-        let request = requests[0];
-        assert_eq!(request.0, actor_account);
-        assert_eq!(request.1, alice_id());
-        assert_eq!(request.2, actors::Role::StorageProvider);
-        assert_eq!(
-            request.3,
-            starting_block
-                + <Test as system::Trait>::BlockNumber::from(Actors::request_life_time())
-        );
-    });
-}
-
-#[test]
-fn staking() {
-    initial_test_ext().execute_with(|| {
-        init_storage_role();
-        let storage_params = init_storage_parmeters();
-        let actor_account = 5;
-
-        let request: actors::Request<Test> = (
-            actor_account,
-            alice_id(),
-            actors::Role::StorageProvider,
-            1000,
-        );
-
-        <actors::RoleEntryRequests<Test>>::put(vec![request]);
-
-        let _ = Balances::deposit_creating(&actor_account, storage_params.min_stake);
-
-        assert!(Actors::stake(
-            Origin::signed(alice_account()),
-            actors::Role::StorageProvider,
-            actor_account
-        )
-        .is_ok());
-
-        let ids = Actors::actor_account_ids();
-        assert_eq!(ids, vec![actor_account]);
-
-        let actor = Actors::actor_by_account_id(actor_account);
-        assert!(actor.is_some());
-
-        let accounts_in_role = Actors::account_ids_by_role(actors::Role::StorageProvider);
-        assert_eq!(accounts_in_role, vec![actor_account]);
-
-        let account_ids_for_member = Actors::account_ids_by_member_id(alice_id());
-        assert_eq!(account_ids_for_member, vec![actor_account]);
-
-        let num_of_locks = Balances::locks(&actor_account).len();
-        assert_eq!(num_of_locks, 1);
-    });
-}
-
-#[test]
-fn unstaking() {
-    initial_test_ext().execute_with(|| {
-        init_storage_role();
-        let storage_params = init_storage_parmeters();
-        let actor_account = 5;
-
-        assert!(Actors::unstake(Origin::signed(alice_account()), actor_account).is_err());
-
-        let actor: actors::Actor<Test> = actors::Actor {
-            role: actors::Role::StorageProvider,
-            member_id: alice_id(),
-            account: actor_account,
-            joined_at: 1,
-        };
-        <actors::ActorAccountIds<Test>>::put(vec![actor_account]);
-        <actors::ActorByAccountId<Test>>::insert(&actor_account, actor);
-        <actors::AccountIdsByRole<Test>>::insert(
-            actors::Role::StorageProvider,
-            vec![actor_account],
-        );
-        <actors::AccountIdsByMemberId<Test>>::insert(alice_id(), vec![actor_account]);
-        let current_block = 500;
-
-        System::set_block_number(current_block);
-        assert!(Actors::unstake(Origin::signed(alice_account()), actor_account).is_ok());
-
-        assert_eq!(Actors::actor_account_ids().len(), 0);
-
-        let actor = Actors::actor_by_account_id(actor_account);
-        assert!(actor.is_none());
-
-        let accounts_in_role = Actors::account_ids_by_role(actors::Role::StorageProvider);
-        assert_eq!(accounts_in_role.len(), 0);
-
-        let account_ids_for_member = Actors::account_ids_by_member_id(alice_id());
-        assert_eq!(account_ids_for_member.len(), 0);
-
-        let lock = Balances::locks(&actor_account)[0].clone();
-        // assuming this is our lock
-        assert_eq!(lock.until, current_block + storage_params.unbonding_period);
-    });
-}

+ 0 - 25
runtime-modules/roles/src/traits.rs

@@ -1,25 +0,0 @@
-use crate::actors;
-
-// Roles
-pub trait Roles<T: system::Trait> {
-    fn is_role_account(account_id: &T::AccountId) -> bool;
-
-    fn account_has_role(account_id: &T::AccountId, role: actors::Role) -> bool;
-
-    // If available, return a random account ID for the given role.
-    fn random_account_for_role(role: actors::Role) -> Result<T::AccountId, &'static str>;
-}
-
-impl<T: system::Trait> Roles<T> for () {
-    fn is_role_account(_who: &T::AccountId) -> bool {
-        false
-    }
-
-    fn account_has_role(_account_id: &T::AccountId, _role: actors::Role) -> bool {
-        false
-    }
-
-    fn random_account_for_role(_role: actors::Role) -> Result<T::AccountId, &'static str> {
-        Err("not implemented")
-    }
-}

+ 4 - 4
runtime-modules/service-discovery/Cargo.toml

@@ -14,7 +14,7 @@ std = [
 	'serde',
     'codec/std',
     'primitives/std',
-    'bureaucracy/std',
+    'working-group/std',
 ]
 
 [dependencies.sr-primitives]
@@ -69,10 +69,10 @@ git = 'https://github.com/paritytech/substrate.git'
 package = 'sr-io'
 rev = 'c37bb08535c49a12320af7facfd555ce05cce2e8'
 
-[dependencies.bureaucracy]
+[dependencies.working-group]
 default_features = false
-package = 'substrate-bureaucracy-module'
-path = '../bureaucracy'
+package = 'substrate-working-group-module'
+path = '../working-group'
 
 [dev-dependencies.balances]
 default_features = false

+ 11 - 8
runtime-modules/service-discovery/src/lib.rs

@@ -5,7 +5,7 @@
 //!
 //! ## Comments
 //!
-//! Service discovery module uses bureaucracy module to authorize actions. It is generally used by
+//! Service discovery module uses working group module to authorize actions. It is generally used by
 //! the Colossus service.
 //!
 //! ## Supported extrinsics
@@ -48,11 +48,14 @@ pub type IPNSIdentity = Vec<u8>;
 /// HTTP Url string to a discovery service endpoint
 pub type Url = Vec<u8>;
 
-// Alias for storage working group bureaucracy
-pub(crate) type StorageBureaucracy<T> = bureaucracy::Module<T, bureaucracy::Instance2>;
+// The storage working group instance alias.
+pub(crate) type StorageWorkingGroupInstance = working_group::Instance2;
 
-/// Storage provider is a worker from the bureaucracy module.
-pub type StorageProviderId<T> = bureaucracy::WorkerId<T>;
+// Alias for storage working group.
+pub(crate) type StorageWorkingGroup<T> = working_group::Module<T, StorageWorkingGroupInstance>;
+
+/// Storage provider is a worker from the  working_group module.
+pub type StorageProviderId<T> = working_group::WorkerId<T>;
 
 pub(crate) const MINIMUM_LIFETIME: u32 = 600; // 1hr assuming 6s block times
 pub(crate) const DEFAULT_LIFETIME: u32 = MINIMUM_LIFETIME * 24; // 24hr
@@ -68,7 +71,7 @@ pub struct AccountInfo<BlockNumber> {
 }
 
 /// The _Service discovery_ main _Trait_.
-pub trait Trait: system::Trait + bureaucracy::Trait<bureaucracy::Instance2> {
+pub trait Trait: system::Trait + working_group::Trait<StorageWorkingGroupInstance> {
     /// _Service discovery_ event type.
     type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
 }
@@ -119,7 +122,7 @@ decl_module! {
             storage_provider_id: StorageProviderId<T>,
             id: Vec<u8>,
         ) {
-            <StorageBureaucracy<T>>::ensure_worker_signed(origin, &storage_provider_id)?;
+            <StorageWorkingGroup<T>>::ensure_worker_signed(origin, &storage_provider_id)?;
 
             // TODO: ensure id is a valid base58 encoded IPNS identity
 
@@ -138,7 +141,7 @@ decl_module! {
         /// Deletes the AccountInfo with the IPNS identity for the storage provider.
         /// Requires signed storage provider credentials.
         pub fn unset_ipns_id(origin, storage_provider_id: StorageProviderId<T>) {
-            <StorageBureaucracy<T>>::ensure_worker_signed(origin, &storage_provider_id)?;
+            <StorageWorkingGroup<T>>::ensure_worker_signed(origin, &storage_provider_id)?;
 
             // == MUTATION SAFE ==
 

+ 11 - 8
runtime-modules/service-discovery/src/mock.rs

@@ -11,10 +11,13 @@ pub use sr_primitives::{
 
 use srml_support::{impl_outer_event, impl_outer_origin, parameter_types};
 
-mod bureaucracy_mod {
-    pub use bureaucracy::Event;
-    pub use bureaucracy::Instance2;
-    pub use bureaucracy::Trait;
+// The storage working group instance alias.
+pub type StorageWorkingGroupInstance = working_group::Instance2;
+
+mod working_group_mod {
+    pub use super::StorageWorkingGroupInstance;
+    pub use working_group::Event;
+    pub use working_group::Trait;
 }
 
 mod membership_mod {
@@ -34,7 +37,7 @@ impl_outer_event! {
         discovery<T>,
         balances<T>,
         membership_mod<T>,
-        bureaucracy_mod Instance2 <T>,
+         working_group_mod StorageWorkingGroupInstance <T>,
     }
 }
 
@@ -127,7 +130,7 @@ impl recurringrewards::Trait for Test {
     type RewardRelationshipId = u64;
 }
 
-impl bureaucracy::Trait<bureaucracy::Instance2> for Test {
+impl working_group::Trait<StorageWorkingGroupInstance> for Test {
     type Event = MetaEvent;
 }
 
@@ -153,14 +156,14 @@ pub(crate) fn hire_storage_provider() -> (u64, u64) {
     let storage_provider_id = 1;
     let role_account_id = 1;
 
-    let storage_provider = bureaucracy::Worker {
+    let storage_provider = working_group::Worker {
         member_id: 1,
         role_account: role_account_id,
         reward_relationship: None,
         role_stake_profile: None,
     };
 
-    <bureaucracy::WorkerById<Test, bureaucracy::Instance2>>::insert(
+    <working_group::WorkerById<Test, StorageWorkingGroupInstance>>::insert(
         storage_provider_id,
         storage_provider,
     );

+ 4 - 4
runtime-modules/storage/Cargo.toml

@@ -17,7 +17,7 @@ std = [
 	'primitives/std',
 	'common/std',
 	'membership/std',
-	'bureaucracy/std',
+	'working-group/std',
 ]
 
 
@@ -78,10 +78,10 @@ default_features = false
 package = 'substrate-common-module'
 path = '../common'
 
-[dependencies.bureaucracy]
+[dependencies.working-group]
 default_features = false
-package = 'substrate-bureaucracy-module'
-path = '../bureaucracy'
+package = 'substrate-working-group-module'
+path = '../working-group'
 
 [dev-dependencies.runtime-io]
 default_features = false

+ 8 - 8
runtime-modules/storage/src/data_directory.rs

@@ -4,7 +4,7 @@
 //!
 //! ## Comments
 //!
-//! Data object type registry module uses bureaucracy module to authorize actions.
+//! Data object type registry module uses  working group module to authorize actions.
 //!
 //! ## Supported extrinsics
 //!
@@ -32,7 +32,7 @@ pub(crate) use common::BlockAndTime;
 
 use crate::data_object_type_registry;
 use crate::data_object_type_registry::IsActiveDataObjectType;
-use crate::{MemberId, StorageBureaucracy, StorageProviderId};
+use crate::{MemberId, StorageProviderId, StorageWorkingGroup, StorageWorkingGroupInstance};
 
 /// The _Data directory_ main _Trait_.
 pub trait Trait:
@@ -40,7 +40,7 @@ pub trait Trait:
     + system::Trait
     + data_object_type_registry::Trait
     + membership::members::Trait
-    + bureaucracy::Trait<bureaucracy::Instance2>
+    + working_group::Trait<StorageWorkingGroupInstance>
 {
     /// _Data directory_ event type.
     type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
@@ -88,10 +88,10 @@ impl From<system::Error> for Error {
     }
 }
 
-impl From<bureaucracy::Error> for Error {
-    fn from(error: bureaucracy::Error) -> Self {
+impl From<working_group::Error> for Error {
+    fn from(error: working_group::Error) -> Self {
         match error {
-            bureaucracy::Error::Other(msg) => Error::Other(msg),
+            working_group::Error::Other(msg) => Error::Other(msg),
             _ => Error::Other(error.into()),
         }
     }
@@ -238,7 +238,7 @@ decl_module! {
             storage_provider_id: StorageProviderId<T>,
             content_id: T::ContentId
         ) {
-            <StorageBureaucracy<T>>::ensure_worker_signed(origin, &storage_provider_id)?;
+            <StorageWorkingGroup<T>>::ensure_worker_signed(origin, &storage_provider_id)?;
 
             // == MUTATION SAFE ==
 
@@ -256,7 +256,7 @@ decl_module! {
             storage_provider_id: StorageProviderId<T>,
             content_id: T::ContentId
         ) {
-            <StorageBureaucracy<T>>::ensure_worker_signed(origin, &storage_provider_id)?;
+            <StorageWorkingGroup<T>>::ensure_worker_signed(origin, &storage_provider_id)?;
 
             // == MUTATION SAFE ==
 

+ 9 - 9
runtime-modules/storage/src/data_object_storage_registry.rs

@@ -4,7 +4,7 @@
 //!
 //! ## Comments
 //!
-//! Data object storage registry module uses bureaucracy module to authorize actions.
+//! Data object storage registry module uses  working group module to authorize actions.
 //! Only registered storage providers can call extrinsics.
 //!
 //! ## Supported extrinsics
@@ -16,7 +16,7 @@
 
 // Clippy linter requirement.
 // Disable it because of the substrate lib design. Example:
-//  pub NextRelationshipId get(next_relationship_id) build(|config: &GenesisConfig<T>|
+// pub NextRelationshipId get(next_relationship_id) build(|config: &GenesisConfig<T>|
 #![allow(clippy::redundant_closure_call)]
 
 // Do not delete! Cannot be uncommented by default, because of Parity decl_module! issue.
@@ -28,7 +28,7 @@ use sr_primitives::traits::{MaybeSerialize, Member, SimpleArithmetic};
 use srml_support::{decl_error, decl_event, decl_module, decl_storage, ensure, Parameter};
 
 use crate::data_directory::{self, ContentIdExists};
-use crate::{StorageBureaucracy, StorageProviderId};
+use crate::{StorageProviderId, StorageWorkingGroup, StorageWorkingGroupInstance};
 
 const DEFAULT_FIRST_RELATIONSHIP_ID: u32 = 1;
 
@@ -37,7 +37,7 @@ pub trait Trait:
     timestamp::Trait
     + system::Trait
     + data_directory::Trait
-    + bureaucracy::Trait<bureaucracy::Instance2>
+    + working_group::Trait<StorageWorkingGroupInstance>
 {
     /// _Data object storage registry_ event type.
     type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
@@ -83,10 +83,10 @@ impl From<system::Error> for Error {
     }
 }
 
-impl From<bureaucracy::Error> for Error {
-    fn from(error: bureaucracy::Error) -> Self {
+impl From<working_group::Error> for Error {
+    fn from(error: working_group::Error) -> Self {
         match error {
-            bureaucracy::Error::Other(msg) => Error::Other(msg),
+            working_group::Error::Other(msg) => Error::Other(msg),
             _ => Error::Other(error.into()),
         }
     }
@@ -158,7 +158,7 @@ decl_module! {
         /// in the storage working group.
         pub fn add_relationship(origin, storage_provider_id: StorageProviderId<T>, cid: T::ContentId) {
             // Origin should match storage provider.
-            <StorageBureaucracy<T>>::ensure_worker_signed(origin, &storage_provider_id)?;
+            <StorageWorkingGroup<T>>::ensure_worker_signed(origin, &storage_provider_id)?;
 
             // Content ID must exist
             ensure!(T::ContentIdExists::has_content(&cid), Error::CidNotFound);
@@ -221,7 +221,7 @@ impl<T: Trait> Module<T> {
         id: T::DataObjectStorageRelationshipId,
         ready: bool,
     ) -> Result<(), Error> {
-        <StorageBureaucracy<T>>::ensure_worker_signed(origin, &storage_provider_id)?;
+        <StorageWorkingGroup<T>>::ensure_worker_signed(origin, &storage_provider_id)?;
 
         // For that, we need to fetch the identified DOSR
         let mut dosr =

+ 10 - 10
runtime-modules/storage/src/data_object_type_registry.rs

@@ -3,7 +3,7 @@
 //!
 //! ## Comments
 //!
-//! Data object type registry module uses bureaucracy module to authorize actions. Only leader can
+//! Data object type registry module uses  working group module to authorize actions. Only leader can
 //! call extrinsics.
 //!
 //! ## Supported extrinsics
@@ -22,7 +22,7 @@
 // Do not delete! Cannot be uncommented by default, because of Parity decl_module! issue.
 //#![warn(missing_docs)]
 
-use crate::StorageBureaucracy;
+use crate::{StorageWorkingGroup, StorageWorkingGroupInstance};
 use codec::{Codec, Decode, Encode};
 use rstd::prelude::*;
 use sr_primitives::traits::{MaybeSerialize, Member, SimpleArithmetic};
@@ -32,7 +32,7 @@ const DEFAULT_TYPE_DESCRIPTION: &str = "Default data object type for audio and v
 const DEFAULT_FIRST_DATA_OBJECT_TYPE_ID: u32 = 1;
 
 /// The _Data object type registry_ main _Trait_.
-pub trait Trait: system::Trait + bureaucracy::Trait<bureaucracy::Instance2> {
+pub trait Trait: system::Trait + working_group::Trait<StorageWorkingGroupInstance> {
     /// _Data object type registry_ event type.
     type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
 
@@ -68,10 +68,10 @@ impl From<system::Error> for Error {
     }
 }
 
-impl From<bureaucracy::Error> for Error {
-    fn from(error: bureaucracy::Error) -> Self {
+impl From<working_group::Error> for Error {
+    fn from(error: working_group::Error) -> Self {
         match error {
-            bureaucracy::Error::Other(msg) => Error::Other(msg),
+            working_group::Error::Other(msg) => Error::Other(msg),
             _ => Error::Other(error.into()),
         }
     }
@@ -149,7 +149,7 @@ decl_module! {
 
         /// Registers the new data object type. Requires leader privileges.
         pub fn register_data_object_type(origin, data_object_type: DataObjectType) {
-            <StorageBureaucracy<T>>::ensure_origin_is_active_leader(origin)?;
+            <StorageWorkingGroup<T>>::ensure_origin_is_active_leader(origin)?;
 
             let new_do_type_id = Self::next_data_object_type_id();
             let do_type: DataObjectType = DataObjectType {
@@ -169,7 +169,7 @@ decl_module! {
 
         /// Updates existing data object type. Requires leader privileges.
         pub fn update_data_object_type(origin, id: T::DataObjectTypeId, data_object_type: DataObjectType) {
-            <StorageBureaucracy<T>>::ensure_origin_is_active_leader(origin)?;
+            <StorageWorkingGroup<T>>::ensure_origin_is_active_leader(origin)?;
 
             let mut do_type = Self::ensure_data_object_type(id)?;
 
@@ -187,7 +187,7 @@ decl_module! {
 
         /// Activates existing data object type. Requires leader privileges.
         pub fn activate_data_object_type(origin, id: T::DataObjectTypeId) {
-            <StorageBureaucracy<T>>::ensure_origin_is_active_leader(origin)?;
+            <StorageWorkingGroup<T>>::ensure_origin_is_active_leader(origin)?;
 
             let mut do_type = Self::ensure_data_object_type(id)?;
 
@@ -204,7 +204,7 @@ decl_module! {
 
         /// Deactivates existing data object type. Requires leader privileges.
         pub fn deactivate_data_object_type(origin, id: T::DataObjectTypeId) {
-            <StorageBureaucracy<T>>::ensure_origin_is_active_leader(origin)?;
+            <StorageWorkingGroup<T>>::ensure_origin_is_active_leader(origin)?;
 
             let mut do_type = Self::ensure_data_object_type(id)?;
 

+ 7 - 4
runtime-modules/storage/src/lib.rs

@@ -7,11 +7,14 @@ pub mod data_object_type_registry;
 
 mod tests;
 
-// Alias for storage working group bureaucracy
-pub(crate) type StorageBureaucracy<T> = bureaucracy::Module<T, bureaucracy::Instance2>;
+// The storage working group instance alias.
+pub type StorageWorkingGroupInstance = working_group::Instance2;
+
+// Alias for storage working group
+pub(crate) type StorageWorkingGroup<T> = working_group::Module<T, StorageWorkingGroupInstance>;
 
 // Alias for the member id.
 pub(crate) type MemberId<T> = <T as membership::members::Trait>::MemberId;
 
-/// Storage provider is a worker from the bureaucracy module.
-pub type StorageProviderId<T> = bureaucracy::WorkerId<T>;
+/// Storage provider is a worker from the working group module.
+pub type StorageProviderId<T> = working_group::WorkerId<T>;

+ 3 - 3
runtime-modules/storage/src/tests/data_object_storage_registry.rs

@@ -22,7 +22,7 @@ fn add_relationship_fails_with_invalid_authorization() {
             storage_provider_id,
             TEST_MOCK_EXISTING_CID,
         );
-        assert_eq!(res, Err(bureaucracy::Error::WorkerDoesNotExist.into()));
+        assert_eq!(res, Err(working_group::Error::WorkerDoesNotExist.into()));
     });
 }
 
@@ -44,7 +44,7 @@ fn set_relationship_ready_fails_with_invalid_authorization() {
             invalid_storage_provider_id,
             TEST_MOCK_EXISTING_CID,
         );
-        assert_eq!(res, Err(bureaucracy::Error::WorkerDoesNotExist.into()));
+        assert_eq!(res, Err(working_group::Error::WorkerDoesNotExist.into()));
     });
 }
 
@@ -66,7 +66,7 @@ fn unset_relationship_ready_fails_with_invalid_authorization() {
             invalid_storage_provider_id,
             TEST_MOCK_EXISTING_CID,
         );
-        assert_eq!(res, Err(bureaucracy::Error::WorkerDoesNotExist.into()));
+        assert_eq!(res, Err(working_group::Error::WorkerDoesNotExist.into()));
     });
 }
 

+ 5 - 5
runtime-modules/storage/src/tests/data_object_type_registry.rs

@@ -1,7 +1,7 @@
 #![cfg(test)]
 
 use super::mock::*;
-use crate::StorageBureaucracy;
+use crate::StorageWorkingGroup;
 use system::{self, EventRecord, Phase, RawOrigin};
 
 const DEFAULT_LEADER_ACCOUNT_ID: u64 = 1;
@@ -10,7 +10,7 @@ const DEFAULT_LEADER_MEMBER_ID: u64 = 1;
 struct SetLeadFixture;
 impl SetLeadFixture {
     fn set_default_lead() {
-        let set_lead_result = <StorageBureaucracy<Test>>::set_lead(
+        let set_lead_result = <StorageWorkingGroup<Test>>::set_lead(
             RawOrigin::Root.into(),
             DEFAULT_LEADER_MEMBER_ID,
             DEFAULT_LEADER_ACCOUNT_ID,
@@ -81,7 +81,7 @@ fn activate_data_object_type_fails_with_invalid_lead() {
             RawOrigin::Signed(invalid_leader_account_id).into(),
             dot_id,
         );
-        assert_eq!(res, Err(bureaucracy::Error::IsNotLeadAccount.into()));
+        assert_eq!(res, Err(working_group::Error::IsNotLeadAccount.into()));
     });
 }
 
@@ -108,7 +108,7 @@ fn deactivate_data_object_type_fails_with_invalid_lead() {
             RawOrigin::Signed(invalid_leader_account_id).into(),
             dot_id,
         );
-        assert_eq!(res, Err(bureaucracy::Error::IsNotLeadAccount.into()));
+        assert_eq!(res, Err(working_group::Error::IsNotLeadAccount.into()));
     });
 }
 
@@ -140,7 +140,7 @@ fn update_data_object_type_fails_with_invalid_lead() {
             dot_id,
             updated1,
         );
-        assert_eq!(res, Err(bureaucracy::Error::IsNotLeadAccount.into()));
+        assert_eq!(res, Err(working_group::Error::IsNotLeadAccount.into()));
     });
 }
 

+ 8 - 7
runtime-modules/storage/src/tests/mock.rs

@@ -15,11 +15,12 @@ pub use sr_primitives::{
 
 use crate::data_directory::ContentIdExists;
 use crate::data_object_type_registry::IsActiveDataObjectType;
+pub use crate::StorageWorkingGroupInstance;
 use srml_support::{impl_outer_event, impl_outer_origin, parameter_types, StorageLinkedMap};
 
-mod bureaucracy_mod {
-    pub use bureaucracy::Event;
-    pub use bureaucracy::Instance2;
+mod working_group_mod {
+    pub use super::StorageWorkingGroupInstance;
+    pub use working_group::Event;
 }
 
 impl_outer_origin! {
@@ -33,7 +34,7 @@ impl_outer_event! {
         data_object_storage_registry<T>,
         balances<T>,
         members<T>,
-        bureaucracy_mod Instance2 <T>,
+        working_group_mod StorageWorkingGroupInstance <T>,
     }
 }
 
@@ -145,7 +146,7 @@ impl GovernanceCurrency for Test {
     type Currency = balances::Module<Self>;
 }
 
-impl bureaucracy::Trait<bureaucracy::Instance2> for Test {
+impl working_group::Trait<StorageWorkingGroupInstance> for Test {
     type Event = MetaEvent;
 }
 
@@ -301,14 +302,14 @@ pub(crate) fn hire_storage_provider() -> (u64, u32) {
     let storage_provider_id = 1;
     let role_account_id = 1;
 
-    let storage_provider = bureaucracy::Worker {
+    let storage_provider = working_group::Worker {
         member_id: 1,
         role_account: role_account_id,
         reward_relationship: None,
         role_stake_profile: None,
     };
 
-    <bureaucracy::WorkerById<Test, bureaucracy::Instance2>>::insert(
+    <working_group::WorkerById<Test, StorageWorkingGroupInstance>>::insert(
         storage_provider_id,
         storage_provider,
     );

+ 1 - 1
runtime-modules/bureaucracy/Cargo.toml → runtime-modules/working-group/Cargo.toml

@@ -1,5 +1,5 @@
 [package]
-name = 'substrate-bureaucracy-module'
+name = 'substrate-working-group-module'
 version = '1.0.0'
 authors = ['Joystream contributors']
 edition = '2018'

+ 18 - 2
runtime-modules/bureaucracy/src/errors.rs → runtime-modules/working-group/src/errors.rs

@@ -224,11 +224,17 @@ decl_error! {
         /// Cannot decrease stake while slashes ongoing.
         StakingErrorCannotDecreaseWhileSlashesOngoing,
 
-        /// Insufficient stake to decrease,
+        /// Insufficient stake to decrease.
         StakingErrorInsufficientStake,
 
-        /// Slash amount should be greater than zero,
+        /// Slash amount should be greater than zero.
         StakingErrorSlashAmountShouldBeGreaterThanZero,
+
+        /// Cannot find mint in the minting module.
+        CannotFindMint,
+
+        /// Require root origin in extrinsics.
+        RequireRootOrigin,
     }
 }
 
@@ -236,6 +242,7 @@ impl From<system::Error> for Error {
     fn from(error: system::Error) -> Self {
         match error {
             system::Error::Other(msg) => Error::Other(msg),
+            system::Error::RequireRootOrigin => Error::RequireRootOrigin,
             _ => Error::Other(error.into()),
         }
     }
@@ -571,3 +578,12 @@ impl rstd::convert::From<WrappedError<stake::StakeActionError<stake::ImmediateSl
         }
     }
 }
+
+impl rstd::convert::From<WrappedError<minting::GeneralError>> for Error {
+    fn from(wrapper: WrappedError<minting::GeneralError>) -> Self {
+        match wrapper.error {
+            minting::GeneralError::MintNotFound => Error::CannotFindMint,
+            minting::GeneralError::NextAdjustmentInPast => Error::Other("NextAdjustmentInPast"),
+        }
+    }
+}

+ 110 - 49
runtime-modules/bureaucracy/src/lib.rs → runtime-modules/working-group/src/lib.rs

@@ -1,12 +1,12 @@
-//! # Bureaucracy module
-//! Bureaucracy module for the Joystream platform. Version 1.
+//! # Working group module
+//! Working group module for the Joystream platform. Version 1.
 //! Contains abstract working group workflow.
 //!
 //! ## Overview
 //!
-//! The bureaucracy module provides working group workflow to use in different modules.
-//! Exact working group (eg.: forum working group) should create an instance of the Bureaucracy module.
-//! Bureacracy module contains extrinsics for the hiring workflow and the roles lifecycle.
+//! The working group module provides working group workflow to use in different modules.
+//! Exact working group (eg.: forum working group) should create an instance of the Working group module.
+//! The Working group module contains extrinsics for the hiring workflow and the roles lifecycle.
 //!
 //! ## Supported extrinsics
 //! ### Hiring flow
@@ -28,6 +28,7 @@
 //! - [set_lead](./struct.Module.html#method.set_lead) - Set lead.
 //! - [unset_lead](./struct.Module.html#method.unset_lead) - Unset lead.
 //! - [unstake](./struct.Module.html#method.unstake) - Unstake.
+//! - [set_mint_capacity](./struct.Module.html#method.set_mint_capacity) -  Sets the capacity to enable working group budget.
 //!
 //! ### Worker stakes
 //!
@@ -52,10 +53,10 @@ use rstd::collections::btree_map::BTreeMap;
 use rstd::collections::btree_set::BTreeSet;
 use rstd::prelude::*;
 use rstd::vec::Vec;
-use sr_primitives::traits::{EnsureOrigin, One, Zero};
+use sr_primitives::traits::{One, Zero};
 use srml_support::traits::{Currency, ExistenceRequirement, WithdrawReasons};
 use srml_support::{decl_event, decl_module, decl_storage, ensure};
-use system::{ensure_root, ensure_signed, RawOrigin};
+use system::{ensure_root, ensure_signed};
 
 use crate::types::WorkerExitInitiationOrigin;
 use common::constraints::InputValidationLengthConstraint;
@@ -67,8 +68,6 @@ pub use types::{
     WorkerRoleStakeProfile,
 };
 
-//TODO: initialize a mint!
-
 /// Alias for the _Lead_ type
 pub type LeadOf<T> = Lead<MemberId<T>, <T as system::Trait>::AccountId>;
 
@@ -145,7 +144,7 @@ type WorkerOf<T> = Worker<
     MemberId<T>,
 >;
 
-/// The _Bureaucracy_ main _Trait_
+/// The _Working group_ main _Trait_
 pub trait Trait<I: Instance>:
     system::Trait
     + membership::members::Trait
@@ -154,12 +153,12 @@ pub trait Trait<I: Instance>:
     + stake::Trait
     + recurringrewards::Trait
 {
-    /// _Bureaucracy_ event type.
+    /// _Working group_ event type.
     type Event: From<Event<Self, I>> + Into<<Self as system::Trait>::Event>;
 }
 
 decl_event!(
-    /// _Bureaucracy_ events
+    /// _Working group_ events
     pub enum Event<T, I>
     where
         MemberId = MemberId<T>,
@@ -170,6 +169,8 @@ decl_event!(
         WorkerApplicationId = WorkerApplicationId<T>,
         WorkerApplicationIdToWorkerIdMap = WorkerApplicationIdToWorkerIdMap<T>,
         RationaleText = Vec<u8>,
+        MintBalanceOf = minting::BalanceOf<T>,
+        <T as minting::Trait>::MintId,
     {
         /// Emits on setting the leader.
         /// Params:
@@ -258,11 +259,17 @@ decl_event!(
         /// Params:
         /// - worker id.
         WorkerStakeSlashed(WorkerId),
+
+        /// Emits on changing working group mint capacity.
+        /// Params:
+        /// - mint id.
+        /// - new mint balance.
+        MintCapacityChanged(MintId, MintBalanceOf),
     }
 );
 
 decl_storage! {
-    trait Store for Module<T: Trait<I>, I: Instance> as Bureaucracy {
+    trait Store for Module<T: Trait<I>, I: Instance> as WorkingGroup {
         /// The mint currently funding the rewards for this module.
         pub Mint get(mint) : <T as minting::Trait>::MintId;
 
@@ -296,10 +303,24 @@ decl_storage! {
         /// Worker exit rationale text length limits.
         pub WorkerExitRationaleText get(worker_exit_rationale_text) : InputValidationLengthConstraint;
     }
+        add_extra_genesis {
+        config(phantom): rstd::marker::PhantomData<I>;
+        config(storage_working_group_mint_capacity): minting::BalanceOf<T>;
+        config(opening_human_readable_text_constraint): InputValidationLengthConstraint;
+        config(worker_application_human_readable_text_constraint): InputValidationLengthConstraint;
+        config(worker_exit_rationale_text_constraint): InputValidationLengthConstraint;
+        build(|config: &GenesisConfig<T, I>| {
+            Module::<T, I>::initialize_working_group(
+                config.opening_human_readable_text_constraint,
+                config.worker_application_human_readable_text_constraint,
+                config.worker_exit_rationale_text_constraint,
+                config.storage_working_group_mint_capacity)
+        });
+    }
 }
 
 decl_module! {
-    /// _Bureaucracy_ substrate module.
+    /// _Working group_ substrate module.
     pub struct Module<T: Trait<I>, I: Instance> for enum Call where origin: T::Origin {
         /// Default deposit_event() handler
         fn deposit_event() = default;
@@ -336,9 +357,7 @@ decl_module! {
 
             let lead = Self::ensure_lead_is_set()?;
 
-            //
             // == MUTATION SAFE ==
-            //
 
             // Update current lead
             <CurrentLead<T, I>>::kill();
@@ -726,6 +745,24 @@ decl_module! {
             // Ensure worker opening exists
             let (worker_opening, _) = Self::ensure_worker_opening_exists(&worker_opening_id)?;
 
+            // Ensure a mint exists if lead is providing a reward for positions being filled
+            let create_reward_settings = if let Some(policy) = reward_policy {
+                // A reward will need to be created so ensure our configured mint exists
+                let mint_id = Self::mint();
+
+                // Technically this is a bug-check and should not be here.
+                ensure!(<minting::Mints<T>>::exists(mint_id), Error::FillWorkerOpeningMintDoesNotExist);
+
+                // Make sure valid parameters are selected for next payment at block number
+                ensure!(policy.next_payment_at_block > <system::Module<T>>::block_number(),
+                    Error::FillWorkerOpeningInvalidNextPaymentBlock);
+
+                // The verified reward settings to use
+                Some((mint_id, policy))
+            } else {
+                None
+            };
+
             // Make iterator over successful worker application
             let successful_iter = successful_worker_application_ids
                                     .iter()
@@ -764,22 +801,6 @@ decl_module! {
                 )
             )?;
 
-            let create_reward_settings = if let Some(policy) = reward_policy {
-                // A reward will need to be created so ensure our configured mint exists
-                let mint_id = Self::mint();
-
-                ensure!(<minting::Mints<T>>::exists(mint_id), Error::FillWorkerOpeningMintDoesNotExist);
-
-                // Make sure valid parameters are selected for next payment at block number
-                ensure!(policy.next_payment_at_block > <system::Module<T>>::block_number(),
-                    Error::FillWorkerOpeningInvalidNextPaymentBlock);
-
-                // The verified reward settings to use
-                Some((mint_id, policy))
-            } else {
-                None
-            };
-
             //
             // == MUTATION SAFE ==
             //
@@ -938,29 +959,41 @@ decl_module! {
 
             Self::deposit_event(RawEvent::WorkerStakeIncreased(worker_id));
         }
-    }
-}
 
-impl<Origin, T, I> EnsureOrigin<Origin> for Module<T, I>
-where
-    Origin: Into<Result<RawOrigin<T::AccountId>, Origin>> + From<RawOrigin<T::AccountId>>,
-    T: Trait<I>,
-    I: Instance,
-{
-    type Success = ();
+        /// Sets the capacity to enable working group budget.
+        pub fn set_mint_capacity(
+            origin,
+            new_capacity: minting::BalanceOf<T>
+        ) {
+            ensure_root(origin)?;
+
+            let mint_id = Self::mint();
+
+            // Technically this is a bug-check and should not be here.
+            ensure!(<minting::Mints<T>>::exists(mint_id), Error::CannotFindMint);
+
+            // Mint must exist - it is set at genesis or migration.
+            let mint = <minting::Module<T>>::mints(mint_id);
 
-    fn try_origin(o: Origin) -> Result<Self::Success, Origin> {
-        o.into().and_then(|o| match o {
-            RawOrigin::Signed(account_id) => {
-                Self::ensure_is_lead_account(account_id).map_err(|_| RawOrigin::None.into())
+            let current_capacity = mint.capacity();
+
+            //
+            // == MUTATION SAFE ==
+            //
+
+            if new_capacity != current_capacity {
+                ensure_on_wrapped_error!(
+                    <minting::Module<T>>::set_mint_capacity(mint_id, new_capacity)
+                )?;
+
+                Self::deposit_event(RawEvent::MintCapacityChanged(mint_id, new_capacity));
             }
-            _ => Err(RawOrigin::None.into()),
-        })
+        }
     }
 }
 
 impl<T: Trait<I>, I: Instance> Module<T, I> {
-    /// Checks that provided lead account id belongs to the current bureaucracy leader
+    /// Checks that provided lead account id belongs to the current working group leader
     pub fn ensure_is_lead_account(lead_account_id: T::AccountId) -> Result<(), Error> {
         let lead = <CurrentLead<T, I>>::get();
 
@@ -1190,7 +1223,7 @@ impl<T: Trait<I>, I: Instance> Module<T, I> {
 
         // Unstake if stake profile exists
         if let Some(ref stake_profile) = worker.role_stake_profile {
-            // Determine unstaknig period based on who initiated deactivation
+            // Determine unstaking period based on who initiated deactivation
             let unstaking_period = match exit_initiation_origin {
                 WorkerExitInitiationOrigin::Lead => stake_profile.termination_unstaking_period,
                 WorkerExitInitiationOrigin::Worker => stake_profile.exit_unstaking_period,
@@ -1229,4 +1262,32 @@ impl<T: Trait<I>, I: Instance> Module<T, I> {
             )
             .map_err(|e| e.into())
     }
+
+    fn initialize_working_group(
+        opening_human_readable_text_constraint: InputValidationLengthConstraint,
+        worker_application_human_readable_text_constraint: InputValidationLengthConstraint,
+        worker_exit_rationale_text_constraint: InputValidationLengthConstraint,
+        working_group_mint_capacity: minting::BalanceOf<T>,
+    ) {
+        // Create a mint.
+        let mint_id_result = <minting::Module<T>>::add_mint(working_group_mint_capacity, None);
+
+        if let Ok(mint_id) = mint_id_result {
+            <Mint<T, I>>::put(mint_id);
+        } else {
+            panic!("Failed to create a mint for the working group");
+        }
+
+        // Create constraints
+        <OpeningHumanReadableText<I>>::put(opening_human_readable_text_constraint);
+        <WorkerApplicationHumanReadableText<I>>::put(
+            worker_application_human_readable_text_constraint,
+        );
+        <WorkerExitRationaleText<I>>::put(worker_exit_rationale_text_constraint);
+    }
+}
+
+/// Creates default text constraint.
+pub fn default_text_constraint() -> InputValidationLengthConstraint {
+    InputValidationLengthConstraint::new(1, 1024)
 }

+ 53 - 47
runtime-modules/bureaucracy/src/tests/fixtures.rs → runtime-modules/working-group/src/tests/fixtures.rs

@@ -1,10 +1,12 @@
-use super::mock::{Balances, Bureaucracy1, Membership, System, Test, TestEvent};
+use super::mock::{
+    Balances, Membership, System, Test, TestEvent, TestWorkingGroup, TestWorkingGroupInstance,
+};
 use crate::types::{
     OpeningPolicyCommitment, RewardPolicy, Worker, WorkerApplication, WorkerOpening,
     WorkerRoleStakeProfile,
 };
 use crate::Error;
-use crate::{Instance1, RawEvent};
+use crate::RawEvent;
 use common::constraints::InputValidationLengthConstraint;
 use srml_support::{StorageLinkedMap, StorageValue};
 use std::collections::BTreeSet;
@@ -39,7 +41,7 @@ impl IncreaseWorkerStakeFixture {
         let stake_id = 0;
         let old_stake = <stake::Module<Test>>::stakes(stake_id);
         let old_balance = Balances::free_balance(&self.account_id);
-        let actual_result = Bureaucracy1::increase_worker_stake(
+        let actual_result = TestWorkingGroup::increase_worker_stake(
             self.origin.clone().into(),
             self.worker_id,
             self.balance,
@@ -92,9 +94,9 @@ impl TerminateWorkerRoleFixture {
     }
 
     pub fn call_and_assert(&self, expected_result: Result<(), Error>) {
-        <crate::WorkerExitRationaleText<Instance1>>::put(self.constraint.clone());
+        <crate::WorkerExitRationaleText<TestWorkingGroupInstance>>::put(self.constraint.clone());
 
-        let actual_result = Bureaucracy1::terminate_worker_role(
+        let actual_result = TestWorkingGroup::terminate_worker_role(
             self.origin.clone().into(),
             self.worker_id,
             self.text.clone(),
@@ -103,9 +105,9 @@ impl TerminateWorkerRoleFixture {
 
         if actual_result.is_ok() {
             if actual_result.is_ok() {
-                assert!(!<crate::WorkerById<Test, crate::Instance1>>::exists(
-                    self.worker_id
-                ));
+                assert!(
+                    !<crate::WorkerById<Test, TestWorkingGroupInstance>>::exists(self.worker_id)
+                );
             }
         }
     }
@@ -129,7 +131,7 @@ impl LeaveWorkerRoleFixture {
 
     pub fn call_and_assert(&self, expected_result: Result<(), Error>) {
         let rationale_text = b"rationale_text".to_vec();
-        let actual_result = Bureaucracy1::leave_worker_role(
+        let actual_result = TestWorkingGroup::leave_worker_role(
             self.origin.clone().into(),
             self.worker_id,
             rationale_text.clone(),
@@ -137,9 +139,7 @@ impl LeaveWorkerRoleFixture {
         assert_eq!(actual_result, expected_result);
 
         if actual_result.is_ok() {
-            assert!(!<crate::WorkerById<Test, crate::Instance1>>::exists(
-                self.worker_id
-            ));
+            assert!(!<crate::WorkerById<Test, TestWorkingGroupInstance>>::exists(self.worker_id));
         }
     }
 }
@@ -164,7 +164,7 @@ impl UpdateWorkerRewardAccountFixture {
 
     pub fn call_and_assert(&self, expected_result: Result<(), Error>) {
         assert_eq!(
-            Bureaucracy1::update_worker_reward_account(
+            TestWorkingGroup::update_worker_reward_account(
                 self.origin.clone().into(),
                 self.worker_id,
                 self.new_role_account_id
@@ -193,7 +193,7 @@ impl UpdateWorkerRoleAccountFixture {
     }
 
     pub fn call_and_assert(&self, expected_result: Result<(), Error>) {
-        let actual_result = Bureaucracy1::update_worker_role_account(
+        let actual_result = TestWorkingGroup::update_worker_role_account(
             self.origin.clone().into(),
             self.worker_id,
             self.new_role_account_id,
@@ -201,7 +201,7 @@ impl UpdateWorkerRoleAccountFixture {
         assert_eq!(actual_result, expected_result);
 
         if actual_result.is_ok() {
-            let worker = Bureaucracy1::worker_by_id(self.worker_id);
+            let worker = TestWorkingGroup::worker_by_id(self.worker_id);
 
             assert_eq!(worker.role_account, self.new_role_account_id);
         }
@@ -211,16 +211,16 @@ impl UpdateWorkerRoleAccountFixture {
 pub struct UnsetLeadFixture;
 impl UnsetLeadFixture {
     pub fn unset_lead() {
-        assert_eq!(Bureaucracy1::unset_lead(RawOrigin::Root.into()), Ok(()));
+        assert_eq!(TestWorkingGroup::unset_lead(RawOrigin::Root.into()), Ok(()));
     }
 
     pub fn call_and_assert(origin: RawOrigin<u64>, expected_result: Result<(), Error>) {
-        assert_eq!(Bureaucracy1::unset_lead(origin.into()), expected_result);
+        assert_eq!(TestWorkingGroup::unset_lead(origin.into()), expected_result);
     }
 }
 
 pub fn set_mint_id(mint_id: u64) {
-    <crate::Mint<Test, crate::Instance1>>::put(mint_id);
+    <crate::Mint<Test, TestWorkingGroupInstance>>::put(mint_id);
 }
 
 pub fn create_mint() -> u64 {
@@ -260,8 +260,8 @@ impl FillWorkerOpeningFixture {
     }
 
     pub fn call_and_assert(&self, expected_result: Result<(), Error>) -> u64 {
-        let saved_worker_next_id = Bureaucracy1::next_worker_id();
-        let actual_result = Bureaucracy1::fill_worker_opening(
+        let saved_worker_next_id = TestWorkingGroup::next_worker_id();
+        let actual_result = TestWorkingGroup::fill_worker_opening(
             self.origin.clone().into(),
             self.opening_id,
             self.successful_worker_application_ids.clone(),
@@ -270,10 +270,10 @@ impl FillWorkerOpeningFixture {
         assert_eq!(actual_result.clone(), expected_result);
 
         if actual_result.is_ok() {
-            assert_eq!(Bureaucracy1::next_worker_id(), saved_worker_next_id + 1);
+            assert_eq!(TestWorkingGroup::next_worker_id(), saved_worker_next_id + 1);
             let worker_id = saved_worker_next_id;
 
-            let opening = Bureaucracy1::worker_opening_by_id(self.opening_id);
+            let opening = TestWorkingGroup::worker_opening_by_id(self.opening_id);
 
             let role_stake_profile = if opening
                 .policy_commitment
@@ -303,7 +303,7 @@ impl FillWorkerOpeningFixture {
                 role_stake_profile,
             };
 
-            let actual_worker = Bureaucracy1::worker_by_id(worker_id);
+            let actual_worker = TestWorkingGroup::worker_by_id(worker_id);
 
             assert_eq!(actual_worker, expected_worker);
         }
@@ -328,7 +328,7 @@ impl BeginReviewWorkerApplicationsFixture {
         BeginReviewWorkerApplicationsFixture { origin, ..self }
     }
     pub fn call_and_assert(&self, expected_result: Result<(), Error>) {
-        let actual_result = Bureaucracy1::begin_worker_applicant_review(
+        let actual_result = TestWorkingGroup::begin_worker_applicant_review(
             self.origin.clone().into(),
             self.opening_id,
         );
@@ -358,7 +358,7 @@ impl TerminateApplicationFixture {
         }
     }
     pub fn call_and_assert(&self, expected_result: Result<(), Error>) {
-        let actual_result = Bureaucracy1::terminate_worker_application(
+        let actual_result = TestWorkingGroup::terminate_worker_application(
             self.origin.clone().into(),
             self.worker_application_id,
         );
@@ -387,7 +387,7 @@ impl WithdrawApplicationFixture {
         }
     }
     pub fn call_and_assert(&self, expected_result: Result<(), Error>) {
-        let actual_result = Bureaucracy1::withdraw_worker_application(
+        let actual_result = TestWorkingGroup::withdraw_worker_application(
             self.origin.clone().into(),
             self.worker_application_id,
         );
@@ -460,13 +460,13 @@ impl ApplyOnWorkerOpeningFixture {
             role_account: 1,
             opt_role_stake_balance: None,
             opt_application_stake_balance: None,
-            human_readable_text: Vec::new(),
+            human_readable_text: b"human_text".to_vec(),
         }
     }
 
     pub fn call_and_assert(&self, expected_result: Result<(), Error>) -> u64 {
-        let saved_application_next_id = Bureaucracy1::next_worker_application_id();
-        let actual_result = Bureaucracy1::apply_on_worker_opening(
+        let saved_application_next_id = TestWorkingGroup::next_worker_application_id();
+        let actual_result = TestWorkingGroup::apply_on_worker_opening(
             self.origin.clone().into(),
             self.member_id,
             self.worker_opening_id,
@@ -479,12 +479,12 @@ impl ApplyOnWorkerOpeningFixture {
 
         if actual_result.is_ok() {
             assert_eq!(
-                Bureaucracy1::next_worker_application_id(),
+                TestWorkingGroup::next_worker_application_id(),
                 saved_application_next_id + 1
             );
             let application_id = saved_application_next_id;
 
-            let actual_application = Bureaucracy1::worker_application_by_id(application_id);
+            let actual_application = TestWorkingGroup::worker_application_by_id(application_id);
 
             let expected_application = WorkerApplication {
                 role_account: self.role_account,
@@ -495,7 +495,7 @@ impl ApplyOnWorkerOpeningFixture {
 
             assert_eq!(actual_application, expected_application);
 
-            let current_opening = Bureaucracy1::worker_opening_by_id(self.worker_opening_id);
+            let current_opening = TestWorkingGroup::worker_opening_by_id(self.worker_opening_id);
             assert!(current_opening
                 .worker_applications
                 .contains(&application_id));
@@ -519,8 +519,10 @@ impl AcceptWorkerApplicationsFixture {
     }
 
     pub fn call_and_assert(&self, expected_result: Result<(), Error>) {
-        let actual_result =
-            Bureaucracy1::accept_worker_applications(self.origin.clone().into(), self.opening_id);
+        let actual_result = TestWorkingGroup::accept_worker_applications(
+            self.origin.clone().into(),
+            self.opening_id,
+        );
         assert_eq!(actual_result, expected_result);
     }
 }
@@ -529,7 +531,7 @@ pub struct SetLeadFixture;
 impl SetLeadFixture {
     pub fn set_lead(lead_account_id: u64) {
         assert_eq!(
-            Bureaucracy1::set_lead(RawOrigin::Root.into(), 1, lead_account_id),
+            TestWorkingGroup::set_lead(RawOrigin::Root.into(), 1, lead_account_id),
             Ok(())
         );
     }
@@ -541,7 +543,7 @@ impl SetLeadFixture {
         expected_result: Result<(), Error>,
     ) {
         assert_eq!(
-            Bureaucracy1::set_lead(origin.into(), member_id, account_id),
+            TestWorkingGroup::set_lead(origin.into(), member_id, account_id),
             expected_result
         );
     }
@@ -560,7 +562,7 @@ impl Default for AddWorkerOpeningFixture {
             origin: RawOrigin::Signed(1),
             activate_at: hiring::ActivateOpeningAt::CurrentBlock,
             commitment: <OpeningPolicyCommitment<u64, u64>>::default(),
-            human_readable_text: Vec::new(),
+            human_readable_text: b"human_text".to_vec(),
         }
     }
 }
@@ -577,8 +579,8 @@ impl AddWorkerOpeningFixture {
     }
 
     pub fn call_and_assert(&self, expected_result: Result<(), Error>) -> u64 {
-        let saved_opening_next_id = Bureaucracy1::next_worker_opening_id();
-        let actual_result = Bureaucracy1::add_worker_opening(
+        let saved_opening_next_id = TestWorkingGroup::next_worker_opening_id();
+        let actual_result = TestWorkingGroup::add_worker_opening(
             self.origin.clone().into(),
             self.activate_at.clone(),
             self.commitment.clone(),
@@ -588,12 +590,12 @@ impl AddWorkerOpeningFixture {
 
         if actual_result.is_ok() {
             assert_eq!(
-                Bureaucracy1::next_worker_opening_id(),
+                TestWorkingGroup::next_worker_opening_id(),
                 saved_opening_next_id + 1
             );
             let opening_id = saved_opening_next_id;
 
-            let actual_opening = Bureaucracy1::worker_opening_by_id(opening_id);
+            let actual_opening = TestWorkingGroup::worker_opening_by_id(opening_id);
 
             let expected_opening = WorkerOpening::<u64, u64, u64, u64> {
                 opening_id,
@@ -635,13 +637,15 @@ impl EventFixture {
                 u64,
                 std::collections::BTreeMap<u64, u64>,
                 Vec<u8>,
-                crate::Instance1,
+                u64,
+                u64,
+                TestWorkingGroupInstance,
             >,
         >,
     ) {
         let converted_events = expected_raw_events
             .iter()
-            .map(|ev| TestEvent::bureaucracy_Instance1(ev.clone()))
+            .map(|ev| TestEvent::working_group_TestWorkingGroupInstance(ev.clone()))
             .collect::<Vec<TestEvent>>();
 
         Self::assert_global_events(converted_events)
@@ -669,10 +673,12 @@ impl EventFixture {
             u64,
             std::collections::BTreeMap<u64, u64>,
             Vec<u8>,
-            crate::Instance1,
+            u64,
+            u64,
+            TestWorkingGroupInstance,
         >,
     ) {
-        let converted_event = TestEvent::bureaucracy_Instance1(expected_raw_event);
+        let converted_event = TestEvent::working_group_TestWorkingGroupInstance(expected_raw_event);
 
         Self::assert_last_global_event(converted_event)
     }
@@ -717,7 +723,7 @@ impl DecreaseWorkerStakeFixture {
         let stake_id = 0;
         let old_balance = Balances::free_balance(&self.account_id);
         let old_stake = <stake::Module<Test>>::stakes(stake_id);
-        let actual_result = Bureaucracy1::decrease_worker_stake(
+        let actual_result = TestWorkingGroup::decrease_worker_stake(
             self.origin.clone().into(),
             self.worker_id,
             self.balance,
@@ -779,7 +785,7 @@ impl SlashWorkerStakeFixture {
         let stake_id = 0;
         let old_balance = Balances::free_balance(&self.account_id);
         let old_stake = <stake::Module<Test>>::stakes(stake_id);
-        let actual_result = Bureaucracy1::slash_worker_stake(
+        let actual_result = TestWorkingGroup::slash_worker_stake(
             self.origin.clone().into(),
             self.worker_id,
             self.balance,

+ 33 - 8
runtime-modules/bureaucracy/src/tests/mock.rs → runtime-modules/working-group/src/tests/mock.rs

@@ -1,3 +1,5 @@
+use crate::{Module, Trait};
+use common::constraints::InputValidationLengthConstraint;
 use primitives::H256;
 use sr_primitives::{
     testing::Header,
@@ -6,15 +8,13 @@ use sr_primitives::{
 };
 use srml_support::{impl_outer_event, impl_outer_origin, parameter_types};
 
-use crate::{Instance1, Module, Trait};
-
 impl_outer_origin! {
         pub enum Origin for Test {}
 }
 
-mod bureaucracy {
+mod working_group {
+    pub use super::TestWorkingGroupInstance;
     pub use crate::Event;
-    pub use crate::Instance1;
 }
 
 mod membership_mod {
@@ -24,7 +24,7 @@ mod membership_mod {
 impl_outer_event! {
     pub enum TestEvent for Test {
         balances<T>,
-        bureaucracy Instance1 <T>,
+        working_group TestWorkingGroupInstance <T>,
         membership_mod<T>,
     }
 }
@@ -124,17 +124,42 @@ impl recurringrewards::Trait for Test {
 pub type Balances = balances::Module<Test>;
 pub type System = system::Module<Test>;
 
-impl Trait<Instance1> for Test {
+impl Trait<TestWorkingGroupInstance> for Test {
     type Event = TestEvent;
 }
 
 pub type Membership = membership::members::Module<Test>;
-pub type Bureaucracy1 = Module<Test, Instance1>;
+
+pub type TestWorkingGroupInstance = crate::Instance1;
+pub type TestWorkingGroup = Module<Test, TestWorkingGroupInstance>;
+
+pub(crate) const WORKING_GROUP_MINT_CAPACITY: u64 = 40000;
+pub(crate) const WORKING_GROUP_CONSTRAINT_MIN: u16 = 1;
+pub(crate) const WORKING_GROUP_CONSTRAINT_DIFF: u16 = 40;
 
 pub fn build_test_externalities() -> runtime_io::TestExternalities {
-    let t = system::GenesisConfig::default()
+    let mut t = system::GenesisConfig::default()
         .build_storage::<Test>()
         .unwrap();
 
+    crate::GenesisConfig::<Test, TestWorkingGroupInstance> {
+        phantom: Default::default(),
+        storage_working_group_mint_capacity: WORKING_GROUP_MINT_CAPACITY,
+        opening_human_readable_text_constraint: InputValidationLengthConstraint::new(
+            WORKING_GROUP_CONSTRAINT_MIN,
+            WORKING_GROUP_CONSTRAINT_DIFF,
+        ),
+        worker_application_human_readable_text_constraint: InputValidationLengthConstraint::new(
+            WORKING_GROUP_CONSTRAINT_MIN,
+            WORKING_GROUP_CONSTRAINT_DIFF,
+        ),
+        worker_exit_rationale_text_constraint: InputValidationLengthConstraint::new(
+            WORKING_GROUP_CONSTRAINT_MIN,
+            WORKING_GROUP_CONSTRAINT_DIFF,
+        ),
+    }
+    .assimilate_storage(&mut t)
+    .unwrap();
+
     t.into()
 }

+ 126 - 50
runtime-modules/bureaucracy/src/tests/mod.rs → runtime-modules/working-group/src/tests/mod.rs

@@ -1,11 +1,13 @@
 mod fixtures;
 mod mock;
 
-use crate::tests::mock::Test;
 use crate::types::{OpeningPolicyCommitment, RewardPolicy};
-use crate::{Error, Instance1, Lead, RawEvent};
+use crate::{Error, Lead, RawEvent};
 use common::constraints::InputValidationLengthConstraint;
-use mock::{build_test_externalities, Bureaucracy1, TestEvent};
+use mock::{
+    build_test_externalities, Test, TestEvent, TestWorkingGroup, TestWorkingGroupInstance,
+    WORKING_GROUP_CONSTRAINT_DIFF, WORKING_GROUP_CONSTRAINT_MIN, WORKING_GROUP_MINT_CAPACITY,
+};
 use srml_support::{StorageLinkedMap, StorageValue};
 use std::collections::BTreeMap;
 use system::RawOrigin;
@@ -16,14 +18,14 @@ use fixtures::*;
 fn set_lead_succeeds() {
     build_test_externalities().execute_with(|| {
         // Ensure that lead is default
-        assert_eq!(Bureaucracy1::current_lead(), None);
+        assert_eq!(TestWorkingGroup::current_lead(), None);
 
         let lead_account_id = 1;
         let lead_member_id = 1;
 
         // Set lead
         assert_eq!(
-            Bureaucracy1::set_lead(RawOrigin::Root.into(), lead_member_id, lead_account_id),
+            TestWorkingGroup::set_lead(RawOrigin::Root.into(), lead_member_id, lead_account_id),
             Ok(())
         );
 
@@ -31,7 +33,7 @@ fn set_lead_succeeds() {
             member_id: lead_member_id,
             role_account_id: lead_account_id,
         };
-        assert_eq!(Bureaucracy1::current_lead(), Some(lead));
+        assert_eq!(TestWorkingGroup::current_lead(), Some(lead));
 
         EventFixture::assert_crate_events(vec![RawEvent::LeaderSet(
             lead_member_id,
@@ -71,10 +73,12 @@ fn add_worker_opening_fails_with_invalid_human_readable_text() {
     build_test_externalities().execute_with(|| {
         SetLeadFixture::set_lead(1);
 
-        <crate::OpeningHumanReadableText<Instance1>>::put(InputValidationLengthConstraint {
-            min: 1,
-            max_min_diff: 5,
-        });
+        <crate::OpeningHumanReadableText<TestWorkingGroupInstance>>::put(
+            InputValidationLengthConstraint {
+                min: 1,
+                max_min_diff: 5,
+            },
+        );
 
         let add_worker_opening_fixture = AddWorkerOpeningFixture::default().with_text(Vec::new());
 
@@ -190,11 +194,18 @@ fn apply_on_worker_opening_succeeds() {
         appy_on_worker_opening_fixture.call_and_assert(Ok(()));
 
         EventFixture::assert_global_events(vec![
-            TestEvent::bureaucracy_Instance1(RawEvent::LeaderSet(1, lead_account_id)),
+            TestEvent::working_group_TestWorkingGroupInstance(RawEvent::LeaderSet(
+                1,
+                lead_account_id,
+            )),
             TestEvent::membership_mod(membership::members::RawEvent::MemberRegistered(0, 0)),
             TestEvent::membership_mod(membership::members::RawEvent::MemberRegistered(1, 1)),
-            TestEvent::bureaucracy_Instance1(RawEvent::WorkerOpeningAdded(opening_id)),
-            TestEvent::bureaucracy_Instance1(RawEvent::AppliedOnWorkerOpening(opening_id, 0)),
+            TestEvent::working_group_TestWorkingGroupInstance(RawEvent::WorkerOpeningAdded(
+                opening_id,
+            )),
+            TestEvent::working_group_TestWorkingGroupInstance(RawEvent::AppliedOnWorkerOpening(
+                opening_id, 0,
+            )),
         ]);
     });
 }
@@ -308,7 +319,7 @@ fn apply_on_worker_opening_fails_with_invalid_text() {
 
         let opening_id = 0; // newly created opening
 
-        <crate::WorkerApplicationHumanReadableText<Instance1>>::put(
+        <crate::WorkerApplicationHumanReadableText<TestWorkingGroupInstance>>::put(
             InputValidationLengthConstraint {
                 min: 1,
                 max_min_diff: 5,
@@ -374,15 +385,22 @@ fn withdraw_worker_application_succeeds() {
         withdraw_application_fixture.call_and_assert(Ok(()));
 
         EventFixture::assert_global_events(vec![
-            TestEvent::bureaucracy_Instance1(RawEvent::LeaderSet(1, lead_account_id)),
+            TestEvent::working_group_TestWorkingGroupInstance(RawEvent::LeaderSet(
+                1,
+                lead_account_id,
+            )),
             TestEvent::membership_mod(membership::members::RawEvent::MemberRegistered(0, 0)),
             TestEvent::membership_mod(membership::members::RawEvent::MemberRegistered(1, 1)),
-            TestEvent::bureaucracy_Instance1(RawEvent::WorkerOpeningAdded(opening_id)),
-            TestEvent::bureaucracy_Instance1(RawEvent::AppliedOnWorkerOpening(
+            TestEvent::working_group_TestWorkingGroupInstance(RawEvent::WorkerOpeningAdded(
+                opening_id,
+            )),
+            TestEvent::working_group_TestWorkingGroupInstance(RawEvent::AppliedOnWorkerOpening(
                 opening_id,
                 application_id,
             )),
-            TestEvent::bureaucracy_Instance1(RawEvent::WorkerApplicationWithdrawn(application_id)),
+            TestEvent::working_group_TestWorkingGroupInstance(
+                RawEvent::WorkerApplicationWithdrawn(application_id),
+            ),
         ]);
     });
 }
@@ -501,15 +519,22 @@ fn terminate_worker_application_succeeds() {
         terminate_application_fixture.call_and_assert(Ok(()));
 
         EventFixture::assert_global_events(vec![
-            TestEvent::bureaucracy_Instance1(RawEvent::LeaderSet(1, lead_account_id)),
+            TestEvent::working_group_TestWorkingGroupInstance(RawEvent::LeaderSet(
+                1,
+                lead_account_id,
+            )),
             TestEvent::membership_mod(membership::members::RawEvent::MemberRegistered(0, 0)),
             TestEvent::membership_mod(membership::members::RawEvent::MemberRegistered(1, 1)),
-            TestEvent::bureaucracy_Instance1(RawEvent::WorkerOpeningAdded(opening_id)),
-            TestEvent::bureaucracy_Instance1(RawEvent::AppliedOnWorkerOpening(
+            TestEvent::working_group_TestWorkingGroupInstance(RawEvent::WorkerOpeningAdded(
+                opening_id,
+            )),
+            TestEvent::working_group_TestWorkingGroupInstance(RawEvent::AppliedOnWorkerOpening(
                 opening_id,
                 application_id,
             )),
-            TestEvent::bureaucracy_Instance1(RawEvent::WorkerApplicationTerminated(application_id)),
+            TestEvent::working_group_TestWorkingGroupInstance(
+                RawEvent::WorkerApplicationTerminated(application_id),
+            ),
         ]);
     });
 }
@@ -891,23 +916,12 @@ fn fill_worker_opening_fails_with_invalid_reward_policy() {
             FillWorkerOpeningFixture::default_for_ids(opening_id, vec![application_id])
                 .with_reward_policy(RewardPolicy {
                     amount_per_payout: 10000,
-                    next_payment_at_block: 100,
-                    payout_interval: None,
-                });
-
-        fill_worker_opening_fixture.call_and_assert(Err(Error::FillWorkerOpeningMintDoesNotExist));
-
-        set_mint_id(22);
-
-        let fill_worker_opening_fixture =
-            FillWorkerOpeningFixture::default_for_ids(opening_id, vec![application_id])
-                .with_reward_policy(RewardPolicy {
-                    amount_per_payout: 10000,
+                    // Invalid next payment at block zero
                     next_payment_at_block: 0,
                     payout_interval: None,
                 });
         fill_worker_opening_fixture
-            .call_and_assert(Err(Error::FullWorkerOpeningOpeningNotInReviewPeriodStage));
+            .call_and_assert(Err(Error::FillWorkerOpeningInvalidNextPaymentBlock));
     });
 }
 
@@ -923,11 +937,11 @@ fn unset_lead_succeeds() {
             member_id: lead_member_id,
             role_account_id: lead_account_id,
         };
-        assert_eq!(Bureaucracy1::current_lead(), Some(lead));
+        assert_eq!(TestWorkingGroup::current_lead(), Some(lead));
 
         UnsetLeadFixture::unset_lead();
 
-        assert_eq!(Bureaucracy1::current_lead(), None);
+        assert_eq!(TestWorkingGroup::current_lead(), None);
 
         EventFixture::assert_crate_events(vec![
             RawEvent::LeaderSet(lead_member_id, lead_account_id),
@@ -939,7 +953,7 @@ fn unset_lead_succeeds() {
 #[test]
 fn unset_lead_fails_with_invalid_origin() {
     build_test_externalities().execute_with(|| {
-        UnsetLeadFixture::call_and_assert(RawOrigin::None, Err(Error::Other("RequireRootOrigin")));
+        UnsetLeadFixture::call_and_assert(RawOrigin::None, Err(Error::RequireRootOrigin));
     });
 }
 
@@ -953,12 +967,7 @@ fn unset_lead_fails_with_no_lead() {
 #[test]
 fn set_lead_fails_with_invalid_origin() {
     build_test_externalities().execute_with(|| {
-        SetLeadFixture::call_and_assert(
-            RawOrigin::None,
-            1,
-            1,
-            Err(Error::Other("RequireRootOrigin")),
-        );
+        SetLeadFixture::call_and_assert(RawOrigin::None, 1, 1, Err(Error::RequireRootOrigin));
     });
 }
 
@@ -1200,10 +1209,10 @@ fn leave_worker_role_fails_with_invalid_recurring_reward_relationships() {
     build_test_externalities().execute_with(|| {
         let worker_id = fill_default_worker_position();
 
-        let mut worker = Bureaucracy1::worker_by_id(worker_id);
+        let mut worker = TestWorkingGroup::worker_by_id(worker_id);
         worker.reward_relationship = Some(2);
 
-        <crate::WorkerById<Test, crate::Instance1>>::insert(worker_id, worker);
+        <crate::WorkerById<Test, TestWorkingGroupInstance>>::insert(worker_id, worker);
 
         let leave_worker_role_fixture = LeaveWorkerRoleFixture::default_for_worker_id(worker_id);
 
@@ -1532,7 +1541,7 @@ fn slash_worker_stake_fails_with_not_set_lead() {
 #[test]
 fn get_all_worker_ids_succeeds() {
     build_test_externalities().execute_with(|| {
-        let worker_ids = Bureaucracy1::get_all_worker_ids();
+        let worker_ids = TestWorkingGroup::get_all_worker_ids();
         assert_eq!(worker_ids, Vec::new());
 
         let worker_id1 = fill_worker_position(None, None, true);
@@ -1541,12 +1550,79 @@ fn get_all_worker_ids_succeeds() {
         let mut expected_ids = vec![worker_id1, worker_id2];
         expected_ids.sort();
 
-        let mut worker_ids = Bureaucracy1::get_all_worker_ids();
+        let mut worker_ids = TestWorkingGroup::get_all_worker_ids();
         worker_ids.sort();
         assert_eq!(worker_ids, expected_ids);
 
-        <crate::WorkerById<Test, crate::Instance1>>::remove(worker_id1);
-        let worker_ids = Bureaucracy1::get_all_worker_ids();
+        <crate::WorkerById<Test, TestWorkingGroupInstance>>::remove(worker_id1);
+        let worker_ids = TestWorkingGroup::get_all_worker_ids();
         assert_eq!(worker_ids, vec![worker_id2]);
     });
 }
+
+#[test]
+fn set_working_group_mint_capacity_succeeds() {
+    build_test_externalities().execute_with(|| {
+        let mint_id = <minting::Module<Test>>::add_mint(0, None).unwrap();
+        <crate::Mint<Test, TestWorkingGroupInstance>>::put(mint_id);
+
+        let capacity = 15000;
+        let result = TestWorkingGroup::set_mint_capacity(RawOrigin::Root.into(), capacity);
+
+        assert_eq!(result, Ok(()));
+
+        let mint = <minting::Module<Test>>::mints(mint_id);
+        assert_eq!(mint.capacity(), capacity);
+    });
+}
+
+#[test]
+fn set_working_group_mint_capacity_fails_with_mint_not_found() {
+    build_test_externalities().execute_with(|| {
+        let capacity = 15000;
+
+        <crate::Mint<Test, TestWorkingGroupInstance>>::put(5); // random mint id
+        let result = TestWorkingGroup::set_mint_capacity(RawOrigin::Root.into(), capacity);
+
+        assert_eq!(result, Err(Error::CannotFindMint));
+    });
+}
+
+#[test]
+fn set_working_group_mint_capacity_fails_with_invalid_origin() {
+    build_test_externalities().execute_with(|| {
+        let capacity = 15000;
+        let result = TestWorkingGroup::set_mint_capacity(RawOrigin::None.into(), capacity);
+
+        assert_eq!(result, Err(Error::RequireRootOrigin));
+    });
+}
+
+#[test]
+fn ensure_setting_genesis_working_group_mint_succeeds() {
+    build_test_externalities().execute_with(|| {
+        let mint_id = TestWorkingGroup::mint();
+
+        assert!(minting::Mints::<Test>::exists(mint_id));
+
+        let mint = <minting::Module<Test>>::mints(mint_id);
+        assert_eq!(mint.capacity(), WORKING_GROUP_MINT_CAPACITY);
+    });
+}
+
+#[test]
+fn ensure_setting_genesis_constraints_succeeds() {
+    build_test_externalities().execute_with(|| {
+        let default_constraint = common::constraints::InputValidationLengthConstraint::new(
+            WORKING_GROUP_CONSTRAINT_MIN,
+            WORKING_GROUP_CONSTRAINT_DIFF,
+        );
+        let opening_text_constraint = TestWorkingGroup::opening_human_readable_text();
+        let worker_text_constraint = TestWorkingGroup::worker_application_human_readable_text();
+        let worker_exit_text_constraint = TestWorkingGroup::worker_exit_rationale_text();
+
+        assert_eq!(opening_text_constraint, default_constraint);
+        assert_eq!(worker_text_constraint, default_constraint);
+        assert_eq!(worker_exit_text_constraint, default_constraint);
+    });
+}

+ 0 - 0
runtime-modules/bureaucracy/src/types.rs → runtime-modules/working-group/src/types.rs


+ 4 - 11
runtime/Cargo.toml

@@ -56,13 +56,12 @@ std = [
     'governance/std',
     'membership/std',
     'memo/std',
-    'roles/std',
     'service_discovery/std',
     'storage/std',
     'proposals_engine/std',
     'proposals_discussion/std',
     'proposals_codex/std',
-    'bureaucracy/std',
+    'working-group/std',
 ]
 
 # [dependencies]
@@ -340,12 +339,6 @@ package = 'substrate-memo-module'
 path = '../runtime-modules/memo'
 version = '1.0.0'
 
-[dependencies.roles]
-default_features = false
-package = 'substrate-roles-module'
-path = '../runtime-modules/roles'
-version = '1.0.0'
-
 [dependencies.service_discovery]
 default_features = false
 package = 'substrate-service-discovery-module'
@@ -376,8 +369,8 @@ package = 'substrate-proposals-codex-module'
 path = '../runtime-modules/proposals/codex'
 version = '2.0.0'
 
-[dependencies.bureaucracy]
+[dependencies.working-group]
 default_features = false
-package = 'substrate-bureaucracy-module'
-path = '../runtime-modules/bureaucracy'
+package = 'substrate-working-group-module'
+path = '../runtime-modules/working-group'
 version = '1.0.0'

+ 13 - 8
runtime/src/integration/proposals/proposal_encoder.rs

@@ -1,9 +1,9 @@
 use crate::{Call, Runtime};
 use proposals_codex::{ProposalDetails, ProposalDetailsOf, ProposalEncoder};
-use roles::actors::Role;
 
 use codec::Encode;
 use rstd::vec::Vec;
+use srml_support::print;
 
 /// _ProposalEncoder_ implementation. It encodes extrinsics with proposal details parameters
 /// using Runtime Call and parity codec.
@@ -32,20 +32,25 @@ impl ProposalEncoder<Runtime> for ExtrinsicProposalEncoder {
                 Call::ContentWorkingGroup(content_working_group::Call::replace_lead(new_lead))
                     .encode()
             }
-            ProposalDetails::EvictStorageProvider(actor_account) => {
-                Call::Actors(roles::actors::Call::remove_actor(actor_account)).encode()
-            }
             ProposalDetails::SetValidatorCount(new_validator_count) => {
                 Call::Staking(staking::Call::set_validator_count(new_validator_count)).encode()
             }
-            ProposalDetails::SetStorageRoleParameters(role_parameters) => Call::Actors(
-                roles::actors::Call::set_role_parameters(Role::StorageProvider, role_parameters),
-            )
-            .encode(),
             ProposalDetails::RuntimeUpgrade(wasm_code) => Call::ProposalsCodex(
                 proposals_codex::Call::execute_runtime_upgrade_proposal(wasm_code),
             )
             .encode(),
+            // ********** Deprecated during the Nicaea release.
+            // It is kept only for backward compatibility in the Pioneer. **********
+            ProposalDetails::EvictStorageProvider(_) => {
+                print("Error: Calling deprecated EvictStorageProvider encoding option.");
+                Vec::new()
+            }
+            // ********** Deprecated during the Nicaea release.
+            // It is kept only for backward compatibility in the Pioneer. **********
+            ProposalDetails::SetStorageRoleParameters(_) => {
+                print("Error: Calling deprecated SetStorageRoleParameters encoding option.");
+                Vec::new()
+            }
         }
     }
 }

+ 1 - 1
runtime/src/integration/storage.rs

@@ -8,7 +8,7 @@ pub struct StorageProviderHelper;
 
 impl storage::data_directory::StorageProviderHelper<Runtime> for StorageProviderHelper {
     fn get_random_storage_provider() -> Result<ActorId, &'static str> {
-        let ids = crate::StorageBureaucracy::get_all_worker_ids();
+        let ids = crate::StorageWorkingGroup::get_all_worker_ids();
 
         let live_ids: Vec<ActorId> = ids
             .into_iter()

+ 22 - 36
runtime/src/lib.rs

@@ -62,6 +62,22 @@ pub use timestamp::Call as TimestampCall;
 use integration::proposals::{CouncilManager, ExtrinsicProposalEncoder, MembershipOriginValidator};
 pub use proposals_codex::ProposalsConfigParameters;
 
+pub use common;
+pub use forum;
+pub use working_group;
+
+pub use governance::election_params::ElectionParameters;
+use governance::{council, election};
+use membership::members;
+use storage::{data_directory, data_object_storage_registry, data_object_type_registry};
+pub use versioned_store;
+
+pub use content_working_group as content_wg;
+mod migration;
+
+/// Alias for ContentId, used in various places.
+pub type ContentId = primitives::H256;
+
 /// An index to a block.
 pub type BlockNumber = u32;
 
@@ -425,20 +441,6 @@ impl finality_tracker::Trait for Runtime {
     type ReportLatency = ReportLatency;
 }
 
-pub use forum;
-pub use governance::election_params::ElectionParameters;
-use governance::{council, election};
-use membership::members;
-use storage::{data_directory, data_object_storage_registry, data_object_type_registry};
-pub use versioned_store;
-
-pub use content_working_group as content_wg;
-mod migration;
-use roles::actors;
-
-/// Alias for ContentId, used in various places.
-pub type ContentId = primitives::H256;
-
 impl versioned_store::Trait for Runtime {
     type Event = Event;
 }
@@ -746,7 +748,6 @@ impl forum::ForumUserRegistry<AccountId> for ShimMembershipRegistry {
 impl forum::Trait for Runtime {
     type Event = Event;
     type MembershipRegistry = ShimMembershipRegistry;
-    type EnsureForumLeader = bureaucracy::Module<Runtime, bureaucracy::Instance1>;
     type ThreadId = ThreadId;
     type PostId = PostId;
 }
@@ -754,27 +755,13 @@ impl forum::Trait for Runtime {
 impl migration::Trait for Runtime {
     type Event = Event;
 }
+// The storage working group instance alias.
+pub type StorageWorkingGroupInstance = working_group::Instance2;
 
-// Forum bureaucracy
-impl bureaucracy::Trait<bureaucracy::Instance1> for Runtime {
+impl working_group::Trait<StorageWorkingGroupInstance> for Runtime {
     type Event = Event;
 }
 
-// Storage working group bureaucracy
-impl bureaucracy::Trait<bureaucracy::Instance2> for Runtime {
-    type Event = Event;
-}
-
-impl actors::Trait for Runtime {
-    type Event = Event;
-    type OnActorRemoved = ();
-}
-
-//TODO: SWG -  remove with roles module deletion
-impl actors::ActorRemoved<Runtime> for () {
-    fn actor_removed(_: &AccountId) {}
-}
-
 impl service_discovery::Trait for Runtime {
     type Event = Event;
 }
@@ -867,7 +854,6 @@ construct_runtime!(
         Memo: memo::{Module, Call, Storage, Event<T>},
         Members: members::{Module, Call, Storage, Event<T>, Config<T>},
         Forum: forum::{Module, Call, Storage, Event<T>, Config<T>},
-        Actors: actors::{Module, Call, Storage, Event<T>, Config},
         VersionedStore: versioned_store::{Module, Call, Storage, Event<T>, Config},
         VersionedStorePermissions: versioned_store_permissions::{Module, Call, Storage},
         Stake: stake::{Module, Call, Storage},
@@ -884,9 +870,9 @@ construct_runtime!(
         ProposalsEngine: proposals_engine::{Module, Call, Storage, Event<T>},
         ProposalsDiscussion: proposals_discussion::{Module, Call, Storage, Event<T>},
         ProposalsCodex: proposals_codex::{Module, Call, Storage, Error, Config<T>},
-        // --- Bureaucracy
-        ForumBureaucracy: bureaucracy::<Instance1>::{Module, Call, Storage, Event<T>},
-        StorageBureaucracy: bureaucracy::<Instance2>::{Module, Call, Storage, Event<T>},
+        // --- Working groups
+        // reserved for the future use: ForumWorkingGroup: working_group::<Instance1>::{Module, Call, Storage, Event<T>},
+        StorageWorkingGroup: working_group::<Instance2>::{Module, Call, Storage, Config<T>, Error, Event<T>},
     }
 );
 

+ 62 - 2
runtime/src/migration.rs

@@ -3,7 +3,7 @@
 
 use crate::VERSION;
 use rstd::prelude::*;
-// use sr_primitives::{print, traits::Zero};
+use sr_primitives::{print, traits::Zero};
 use srml_support::{debug, decl_event, decl_module, decl_storage};
 
 impl<T: Trait> Module<T> {
@@ -18,10 +18,21 @@ impl<T: Trait> Module<T> {
         // would be any new storage values that need an initial value which would not
         // have been initialized with config() or build() chainspec construction mechanism.
         // Other tasks like resetting values, migrating values etc.
+
+        Self::initialize_storage_working_group_mint();
+        Self::initialize_storage_working_group_text_constraints();
+        // temporary comment storage migration
+        //        Self::clear_storage_data();
     }
 }
 
-pub trait Trait: system::Trait {
+pub trait Trait:
+    system::Trait
+    + minting::Trait
+    + working_group::Trait<working_group::Instance2>
+    + storage::data_directory::Trait
+    + storage::data_object_storage_registry::Trait
+{
     type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
 }
 
@@ -63,3 +74,52 @@ decl_module! {
         }
     }
 }
+
+impl<T: Trait> Module<T> {
+    fn initialize_storage_working_group_mint() {
+        let mint_id_result = <minting::Module<T>>::add_mint(<minting::BalanceOf<T>>::zero(), None);
+
+        if let Ok(mint_id) = mint_id_result {
+            <working_group::Mint<T, working_group::Instance2>>::put(mint_id);
+        } else {
+            print("Failed to create a mint for the storage working group");
+        }
+    }
+
+    fn initialize_storage_working_group_text_constraints() {
+        <working_group::OpeningHumanReadableText<working_group::Instance2>>::put(
+            working_group::default_text_constraint(),
+        );
+        <working_group::WorkerApplicationHumanReadableText<working_group::Instance2>>::put(
+            working_group::default_text_constraint(),
+        );
+        <working_group::WorkerExitRationaleText<working_group::Instance2>>::put(
+            working_group::default_text_constraint(),
+        );
+    }
+
+    // fn clear_storage_data() {
+    //     // Clear storage data object registry data.
+    //     for id in <storage::data_directory::Module<T>>::known_content_ids() {
+    //         <storage::data_object_storage_registry::RelationshipsByContentId<T>>::remove(id);
+    //     }
+    //
+    //     let mut potential_id = <T as storage::data_object_storage_registry::Trait>::DataObjectStorageRelationshipId::zero();
+    //     while potential_id
+    //         < storage::data_object_storage_registry::Module::<T>::next_relationship_id()
+    //     {
+    //         <storage::data_object_storage_registry::Relationships<T>>::remove(&potential_id);
+    //
+    //         potential_id += <T as storage::data_object_storage_registry::Trait>::DataObjectStorageRelationshipId::one();
+    //     }
+    //
+    //     storage::data_object_storage_registry::NextRelationshipId::<T>::kill();
+    //
+    //     // Clear storage data directory data.
+    //     for id in <storage::data_directory::Module<T>>::known_content_ids() {
+    //         <storage::data_directory::DataObjectByContentId<T>>::remove(id);
+    //     }
+    //
+    //     <storage::data_directory::KnownContentIds<T>>::kill();
+    // }
+}

+ 1 - 98
runtime/src/tests/proposals_integration.rs

@@ -6,18 +6,16 @@ use crate::{BlockNumber, ElectionParameters, ProposalCancellationFee, Runtime};
 use codec::Encode;
 use governance::election::CouncilElected;
 use membership::members;
-use membership::role_types::Role;
 use proposals_engine::{
     ActiveStake, ApprovedProposalStatus, BalanceOf, Error, FinalizationData, Proposal,
     ProposalDecisionStatus, ProposalParameters, ProposalStatus, VoteKind, VotersParameters,
     VotingResults,
 };
-use roles::actors::RoleParameters;
 
 use sr_primitives::traits::{DispatchResult, OnFinalize, OnInitialize};
 use sr_primitives::AccountId32;
 use srml_support::traits::Currency;
-use srml_support::{StorageLinkedMap, StorageMap, StorageValue};
+use srml_support::{StorageLinkedMap, StorageValue};
 use system::RawOrigin;
 
 use super::initial_test_ext;
@@ -604,101 +602,6 @@ fn set_election_parameters_proposal_execution_succeeds() {
     });
 }
 
-#[test]
-fn evict_storage_provider_proposal_execution_succeeds() {
-    initial_test_ext().execute_with(|| {
-        let member_id = 1;
-        let account_id: [u8; 32] = [member_id; 32];
-
-        let target_member_id = 3;
-        let target_account: [u8; 32] = [target_member_id; 32];
-        let target_account_id: AccountId32 = target_account.into();
-
-        <roles::actors::Parameters<Runtime>>::insert(
-            Role::StorageProvider,
-            roles::actors::RoleParameters::default(),
-        );
-
-        <roles::actors::AccountIdsByRole<Runtime>>::insert(
-            Role::StorageProvider,
-            vec![target_account_id.clone()],
-        );
-
-        <roles::actors::ActorByAccountId<Runtime>>::insert(
-            target_account_id.clone(),
-            roles::actors::Actor {
-                member_id: target_member_id as u64,
-                role: Role::StorageProvider,
-                account: target_account_id,
-                joined_at: 1,
-            },
-        );
-
-        let codex_extrinsic_test_fixture = CodexProposalTestFixture {
-            member_id: member_id as u64,
-            successful_call: || {
-                ProposalCodex::create_evict_storage_provider_proposal(
-                    RawOrigin::Signed(account_id.clone().into()).into(),
-                    member_id as u64,
-                    b"title".to_vec(),
-                    b"body".to_vec(),
-                    Some(<BalanceOf<Runtime>>::from(25000u32)),
-                    target_account.into(),
-                )
-            },
-        };
-        codex_extrinsic_test_fixture.call_extrinsic_and_assert();
-
-        assert_eq!(
-            <roles::actors::AccountIdsByRole<Runtime>>::get(Role::StorageProvider),
-            Vec::new()
-        );
-    });
-}
-
-#[test]
-fn set_storage_role_parameters_proposal_execution_succeeds() {
-    initial_test_ext().execute_with(|| {
-        let member_id = 1;
-        let account_id: [u8; 32] = [member_id; 32];
-
-        let default_role_parameters = RoleParameters {
-            min_actors: 1,
-            ..RoleParameters::default()
-        };
-
-        <roles::actors::Parameters<Runtime>>::insert(
-            Role::StorageProvider,
-            default_role_parameters.clone(),
-        );
-
-        let target_role_parameters = RoleParameters {
-            startup_grace_period: 700,
-            ..default_role_parameters
-        };
-
-        let codex_extrinsic_test_fixture = CodexProposalTestFixture {
-            member_id: member_id as u64,
-            successful_call: || {
-                ProposalCodex::create_set_storage_role_parameters_proposal(
-                    RawOrigin::Signed(account_id.clone().into()).into(),
-                    member_id as u64,
-                    b"title".to_vec(),
-                    b"body".to_vec(),
-                    Some(<BalanceOf<Runtime>>::from(100_000_u32)),
-                    target_role_parameters.clone(),
-                )
-            },
-        };
-        codex_extrinsic_test_fixture.call_extrinsic_and_assert();
-
-        assert_eq!(
-            <roles::actors::Parameters<Runtime>>::get(Role::StorageProvider),
-            Some(target_role_parameters)
-        );
-    });
-}
-
 #[test]
 fn set_validator_count_proposal_execution_succeeds() {
     initial_test_ext().execute_with(|| {

+ 4 - 4
runtime/src/tests/storage_integration.rs

@@ -2,8 +2,8 @@ use super::initial_test_ext;
 use crate::integration::storage::StorageProviderHelper;
 use crate::Runtime;
 
-use bureaucracy::{Instance2, Worker};
 use srml_support::{StorageLinkedMap, StorageMap};
+use working_group::{Instance2, Worker};
 
 #[test]
 fn storage_provider_helper_succeeds() {
@@ -18,9 +18,9 @@ fn storage_provider_helper_succeeds() {
 		let worker_id2 = 7;
 		let worker_id3 = 19;
 
-		<bureaucracy::WorkerById<Runtime, Instance2>>::insert(worker_id1, Worker::default());
-		<bureaucracy::WorkerById<Runtime, Instance2>>::insert(worker_id2, Worker::default());
-		<bureaucracy::WorkerById<Runtime, Instance2>>::insert(worker_id3, Worker::default());
+		<working_group::WorkerById<Runtime, Instance2>>::insert(worker_id1, Worker::default());
+		<working_group::WorkerById<Runtime, Instance2>>::insert(worker_id2, Worker::default());
+		<working_group::WorkerById<Runtime, Instance2>>::insert(worker_id3, Worker::default());
 
 		// Still error - not registered in the service discovery.
 		let random_provider_result = <StorageProviderHelper as storage::data_directory::StorageProviderHelper<Runtime>>::get_random_storage_provider();