Browse Source

runtime: Delete old working group crate.

Shamil Gadelshin 4 years ago
parent
commit
7bbf8010f7

+ 0 - 44
runtime-modules/working-group/Cargo.toml

@@ -1,44 +0,0 @@
-[package]
-name = 'pallet-working-group'
-version = '3.1.0'
-authors = ['Joystream contributors']
-edition = '2018'
-
-[dependencies]
-serde = { version = "1.0.101", optional = true, features = ["derive"] }
-codec = { package = 'parity-scale-codec', version = '1.3.4', default-features = false, features = ['derive'] }
-sp-std = { package = 'sp-std', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'a200cdb93c6af5763b9c7bf313fa708764ac88ca'}
-frame-support = { package = 'frame-support', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'a200cdb93c6af5763b9c7bf313fa708764ac88ca'}
-frame-system = { package = 'frame-system', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'a200cdb93c6af5763b9c7bf313fa708764ac88ca'}
-sp-arithmetic = { package = 'sp-arithmetic', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'a200cdb93c6af5763b9c7bf313fa708764ac88ca'}
-sp-runtime = { package = 'sp-runtime', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'a200cdb93c6af5763b9c7bf313fa708764ac88ca'}
-membership = { package = 'pallet-membership', default-features = false, path = '../membership'}
-stake = { package = 'pallet-stake', default-features = false, path = '../stake'}
-hiring = { package = 'pallet-hiring', default-features = false, path = '../hiring'}
-minting = { package = 'pallet-token-mint', default-features = false, path = '../token-minting'}
-recurringrewards = { package = 'pallet-recurring-reward', default-features = false, path = '../recurring-reward'}
-common = { package = 'pallet-common', default-features = false, path = '../common'}
-
-[dev-dependencies]
-sp-io = { package = 'sp-io', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'a200cdb93c6af5763b9c7bf313fa708764ac88ca'}
-sp-core = { package = 'sp-core', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'a200cdb93c6af5763b9c7bf313fa708764ac88ca'}
-balances = { package = 'pallet-balances', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'a200cdb93c6af5763b9c7bf313fa708764ac88ca'}
-pallet-timestamp = { package = 'pallet-timestamp', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = 'a200cdb93c6af5763b9c7bf313fa708764ac88ca'}
-
-[features]
-default = ['std']
-std = [
-	'serde',
-	'codec/std',
-	'sp-std/std',
-	'frame-support/std',
-	'frame-system/std',
-	'sp-arithmetic/std',
-	'sp-runtime/std',
-	'membership/std',
-	'stake/std',
-	'hiring/std',
-	'minting/std',
-	'recurringrewards/std',
-	'common/std',
-]

+ 0 - 684
runtime-modules/working-group/src/errors.rs

@@ -1,684 +0,0 @@
-#![warn(missing_docs)]
-
-use crate::{Instance, Module, Trait};
-use frame_support::decl_error;
-
-decl_error! {
-    /// Discussion module predefined errors
-    pub enum Error for Module<T: Trait<I>, I: Instance>{
-        /// Provided stake balance cannot be zero.
-        StakeBalanceCannotBeZero,
-
-        /// Cannot get the worker stake profile.
-        NoWorkerStakeProfile,
-
-        /// Current lead is not set.
-        CurrentLeadNotSet,
-
-        /// There is leader already, cannot hire another one.
-        CannotHireLeaderWhenLeaderExists,
-
-        /// Cannot fill opening with multiple applications.
-        CannotHireMultipleLeaders,
-
-        /// Not a lead account.
-        IsNotLeadAccount,
-
-        /// Opening text too short.
-        OpeningTextTooShort,
-
-        /// Opening text too long.
-        OpeningTextTooLong,
-
-        /// Opening does not exist.
-        OpeningDoesNotExist,
-
-        /// Insufficient balance to apply.
-        InsufficientBalanceToApply,
-
-        /// Unsigned origin.
-        MembershipUnsignedOrigin,
-
-        /// Member id is invalid.
-        MembershipInvalidMemberId,
-
-        /// Signer does not match controller account.
-        ApplyOnWorkerOpeningSignerNotControllerAccount,
-
-        /// Origin must be controller or root account of member.
-        OriginIsNeitherMemberControllerOrRoot,
-
-        /// Member already has an active application on the opening.
-        MemberHasActiveApplicationOnOpening,
-
-        /// Worker application text too long.
-        WorkerApplicationTextTooLong,
-
-        /// Worker application text too short.
-        WorkerApplicationTextTooShort,
-
-        /// Insufficient balance to cover stake.
-        InsufficientBalanceToCoverStake,
-
-        /// Origin is not applicant.
-        OriginIsNotApplicant,
-
-        /// Worker application does not exist.
-        WorkerApplicationDoesNotExist,
-
-        /// Successful worker application does not exist.
-        SuccessfulWorkerApplicationDoesNotExist,
-
-        /// Reward policy has invalid next payment block number.
-        FillOpeningInvalidNextPaymentBlock,
-
-        /// Working group mint does not exist.
-        FillOpeningMintDoesNotExist,
-
-        ///Relationship must exist.
-        RelationshipMustExist,
-
-        /// Worker exit rationale text is too long.
-        WorkerExitRationaleTextTooLong,
-
-        /// Worker exit rationale text is too short.
-        WorkerExitRationaleTextTooShort,
-
-        /// Signer is not worker role account.
-        SignerIsNotWorkerRoleAccount,
-
-        /// Worker has no recurring reward.
-        WorkerHasNoReward,
-
-        /// Worker does not exist.
-        WorkerDoesNotExist,
-
-        /// Opening does not exist.
-        AcceptWorkerApplicationsOpeningDoesNotExist,
-
-        /// Opening Is Not in Waiting to begin.
-        AcceptWorkerApplicationsOpeningIsNotWaitingToBegin,
-
-        /// Opening does not exist.
-        BeginWorkerApplicantReviewOpeningDoesNotExist,
-
-        /// Opening Is Not in Waiting.
-        BeginWorkerApplicantReviewOpeningOpeningIsNotWaitingToBegin,
-
-        /// OpeningDoesNotExist.
-        FullWorkerOpeningOpeningDoesNotExist,
-
-        /// Opening not in review period stage.
-        FullWorkerOpeningOpeningNotInReviewPeriodStage,
-
-        /// Application stake unstaking period for successful applicants too short.
-        FullWorkerOpeningUnsuccessfulApplicationStakeUnstakingPeriodTooShort,
-
-        /// Application stake unstaking period for failed applicants too short.
-        FullWorkerOpeningSuccessfulApplicationStakeUnstakingPeriodTooShort,
-
-        /// Role stake unstaking period for successful applicants too short.
-        FullWorkerOpeningSuccessfulRoleStakeUnstakingPeriodTooShort,
-
-        /// Role stake unstaking period for failed applicants too short.
-        FullWorkerOpeningUnsuccessfulRoleStakeUnstakingPeriodTooShort,
-
-        /// Application stake unstaking period for successful applicants redundant.
-        FullWorkerOpeningSuccessfulApplicationStakeUnstakingPeriodRedundant,
-
-        /// Application stake unstaking period for failed applicants redundant.
-        FullWorkerOpeningUnsuccessfulApplicationStakeUnstakingPeriodRedundant,
-
-        /// Role stake unstaking period for successful applicants redundant.
-        FullWorkerOpeningSuccessfulRoleStakeUnstakingPeriodRedundant,
-
-        /// Role stake unstaking period for failed applicants redundant.
-        FullWorkerOpeningUnsuccessfulRoleStakeUnstakingPeriodRedundant,
-
-        /// Application does not exist.
-        FullWorkerOpeningApplicationDoesNotExist,
-
-        /// Application not in active stage.
-        FullWorkerOpeningApplicationNotActive,
-
-        /// Applications not for opening.
-        FillWorkerOpeningApplicationForWrongOpening,
-
-        /// Application does not exist.
-        WithdrawWorkerApplicationApplicationDoesNotExist,
-
-        /// Application is not active.
-        WithdrawWorkerApplicationApplicationNotActive,
-
-        /// Opening not accepting applications.
-        WithdrawWorkerApplicationOpeningNotAcceptingApplications,
-
-        /// UnstakingPeriodTooShort .... // <== SHOULD REALLY BE TWO SEPARATE, ONE FOR EACH STAKING PURPOSE
-        WithdrawWorkerApplicationUnstakingPeriodTooShort,
-
-        /// Redundant unstaking period provided
-        WithdrawWorkerApplicationRedundantUnstakingPeriod,
-
-        /// Opening does not activate in the future.
-        AddWorkerOpeningActivatesInThePast,
-
-        /// Role stake amount less than minimum currency balance.
-        AddWorkerOpeningRoleStakeLessThanMinimum,
-
-        /// Application stake amount less than minimum currency balance.
-        AddWorkerOpeningAppliicationStakeLessThanMinimum,
-
-        /// Opening does not exist.
-        AddWorkerOpeningOpeningDoesNotExist,
-
-        // <== SHOULD REALLY BE TWO SEPARATE, ONE FOR EACH STAKING PURPOSE
-        /// Stake provided when redundant.
-        AddWorkerOpeningStakeProvidedWhenRedundant,
-
-        // <== SHOULD REALLY BE TWO SEPARATE, ONE FOR EACH STAKING PURPOSE
-        /// Stake missing when required.
-        AddWorkerOpeningStakeMissingWhenRequired,
-
-        // <== SHOULD REALLY BE TWO SEPARATE, ONE FOR EACH STAKING PURPOSE
-        /// Stake amount too low.
-        AddWorkerOpeningStakeAmountTooLow,
-
-        /// Opening is not in accepting applications stage.
-        AddWorkerOpeningOpeningNotInAcceptingApplicationStage,
-
-        /// New application was crowded out.
-        AddWorkerOpeningNewApplicationWasCrowdedOut,
-
-        /// Application rationing has zero max active applicants.
-        AddWorkerOpeningZeroMaxApplicantCount,
-
-        /// Next payment is not in the future.
-        RecurringRewardsNextPaymentNotInFuture,
-
-        /// Recipient not found.
-        RecurringRewardsRecipientNotFound,
-
-        /// Recipient reward source not found.
-        RecurringRewardsRewardSourceNotFound,
-
-        /// Reward relationship not found.
-        RecurringRewardsRewardRelationshipNotFound,
-
-        /// Stake not found.
-        StakingErrorStakeNotFound,
-
-        /// Unstaking period should be greater than zero.
-        StakingErrorUnstakingPeriodShouldBeGreaterThanZero,
-
-        /// Already unstaking.
-        StakingErrorAlreadyUnstaking,
-
-        /// Not staked.
-        StakingErrorNotStaked,
-
-        /// Cannot unstake while slashes ongoing.
-        StakingErrorCannotUnstakeWhileSlashesOngoing,
-
-        /// Insufficient balance in source account.
-        StakingErrorInsufficientBalanceInSourceAccount,
-
-        /// Cannot change stake by zero.
-        StakingErrorCannotChangeStakeByZero,
-
-        /// Cannot increase stake while unstaking.
-        StakingErrorCannotIncreaseStakeWhileUnstaking,
-
-        /// Cannot decrease stake while slashes ongoing.
-        StakingErrorCannotDecreaseWhileSlashesOngoing,
-
-        /// Insufficient stake to decrease.
-        StakingErrorInsufficientStake,
-
-        /// Slash amount should be greater than zero.
-        StakingErrorSlashAmountShouldBeGreaterThanZero,
-
-        /// Cannot find mint in the minting module.
-        CannotFindMint,
-
-        /// Require root origin in extrinsics.
-        RequireRootOrigin,
-
-        /// Require signed origin in extrinsics.
-        RequireSignedOrigin,
-
-        /// Working group size limit exceeded.
-        MaxActiveWorkerNumberExceeded,
-
-        /// Add worker opening role stake cannot be zero.
-        AddWorkerOpeningRoleStakeCannotBeZero,
-
-        /// Add worker opening application stake cannot be zero.
-        AddWorkerOpeningApplicationStakeCannotBeZero,
-
-        /// Invalid OpeningPolicyCommitment parameter:
-        /// fill_opening_failed_applicant_application_stake_unstaking_period should be non-zero.
-        FillOpeningFailedApplicantApplicationStakeUnstakingPeriodIsZero,
-
-        /// Invalid OpeningPolicyCommitment parameter:
-        /// fill_opening_failed_applicant_role_stake_unstaking_period should be non-zero.
-        FillOpeningFailedApplicantRoleStakeUnstakingPeriodIsZero,
-
-        /// Invalid OpeningPolicyCommitment parameter:
-        /// fill_opening_successful_applicant_application_stake_unstaking_period should be non-zero.
-        FillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriodIsZero,
-
-        /// Invalid OpeningPolicyCommitment parameter:
-        /// exit_role_stake_unstaking_period should be non-zero.
-        ExitRoleStakeUnstakingPeriodIsZero,
-
-        /// Invalid OpeningPolicyCommitment parameter:
-        /// exit_role_application_stake_unstaking_period should be non-zero.
-        ExitRoleApplicationStakeUnstakingPeriodIsZero,
-
-        /// Invalid OpeningPolicyCommitment parameter:
-        /// terminate_role_stake_unstaking_period should be non-zero.
-        TerminateRoleStakeUnstakingPeriodIsZero,
-
-        /// Invalid OpeningPolicyCommitment parameter:
-        /// terminate_application_stake_unstaking_period should be non-zero.
-        TerminateApplicationStakeUnstakingPeriodIsZero,
-
-        /// Invalid OpeningPolicyCommitment parameter (role_staking_policy):
-        /// crowded_out_unstaking_period_length should be non-zero.
-        RoleStakingPolicyCrowdedOutUnstakingPeriodIsZero,
-
-        /// Invalid OpeningPolicyCommitment parameter (role_staking_policy):
-        /// review_period_expired_unstaking_period_length should be non-zero.
-        RoleStakingPolicyReviewPeriodUnstakingPeriodIsZero,
-
-        /// Invalid OpeningPolicyCommitment parameter (application_staking_policy):
-        /// crowded_out_unstaking_period_length should be non-zero.
-        ApplicationStakingPolicyCrowdedOutUnstakingPeriodIsZero,
-
-        /// Invalid OpeningPolicyCommitment parameter (application_staking_policy):
-        /// review_period_expired_unstaking_period_length should be non-zero.
-        ApplicationStakingPolicyReviewPeriodUnstakingPeriodIsZero,
-
-        /// Invalid OpeningPolicyCommitment parameter (application_rationing_policy):
-        /// max_active_applicants should be non-zero.
-        ApplicationRationingPolicyMaxActiveApplicantsIsZero,
-
-        /// Minting error: NextAdjustmentInPast
-        MintingErrorNextAdjustmentInPast,
-    }
-}
-
-/// Error wrapper for external module error conversions.
-pub struct WrappedError<E> {
-    /// Generic error.
-    pub error: E,
-}
-
-/// Helps with conversion of other modules errors.
-#[macro_export]
-macro_rules! ensure_on_wrapped_error {
-    ($call:expr) => {{
-        { $call }
-            .map_err(|err| crate::WrappedError { error: err })
-            .map_err(|err| {
-                let e: Error<T, I> = err.into();
-
-                e
-            })
-    }};
-}
-
-impl<T: Trait<I>, I: Instance>
-    sp_std::convert::From<WrappedError<hiring::BeginAcceptingApplicationsError>> for Error<T, I>
-{
-    fn from(wrapper: WrappedError<hiring::BeginAcceptingApplicationsError>) -> Self {
-        match wrapper.error {
-            hiring::BeginAcceptingApplicationsError::OpeningDoesNotExist => {
-                Error::AcceptWorkerApplicationsOpeningDoesNotExist
-            }
-            hiring::BeginAcceptingApplicationsError::OpeningIsNotInWaitingToBeginStage => {
-                Error::AcceptWorkerApplicationsOpeningIsNotWaitingToBegin
-            }
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance> sp_std::convert::From<WrappedError<hiring::AddOpeningError>>
-    for Error<T, I>
-{
-    fn from(wrapper: WrappedError<hiring::AddOpeningError>) -> Self {
-        match wrapper.error {
-            hiring::AddOpeningError::OpeningMustActivateInTheFuture => {
-                Error::AddWorkerOpeningActivatesInThePast
-            }
-            hiring::AddOpeningError::StakeAmountLessThanMinimumStakeBalance(purpose) => {
-                match purpose {
-                    hiring::StakePurpose::Role => Error::AddWorkerOpeningRoleStakeLessThanMinimum,
-                    hiring::StakePurpose::Application => {
-                        Error::AddWorkerOpeningAppliicationStakeLessThanMinimum
-                    }
-                }
-            }
-            hiring::AddOpeningError::ApplicationRationingZeroMaxApplicants => {
-                Error::AddWorkerOpeningZeroMaxApplicantCount
-            }
-            hiring::AddOpeningError::StakeAmountCannotBeZero(purpose) => match purpose {
-                hiring::StakePurpose::Role => Error::AddWorkerOpeningRoleStakeCannotBeZero,
-                hiring::StakePurpose::Application => {
-                    Error::AddWorkerOpeningApplicationStakeCannotBeZero
-                }
-            },
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance> sp_std::convert::From<WrappedError<hiring::BeginReviewError>>
-    for Error<T, I>
-{
-    fn from(wrapper: WrappedError<hiring::BeginReviewError>) -> Self {
-        match wrapper.error {
-            hiring::BeginReviewError::OpeningDoesNotExist => {
-                Error::BeginWorkerApplicantReviewOpeningDoesNotExist
-            }
-            hiring::BeginReviewError::OpeningNotInAcceptingApplicationsStage => {
-                Error::BeginWorkerApplicantReviewOpeningOpeningIsNotWaitingToBegin
-            }
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance> sp_std::convert::From<WrappedError<hiring::FillOpeningError<T>>>
-    for Error<T, I>
-{
-    fn from(wrapper: WrappedError<hiring::FillOpeningError<T>>) -> Self {
-        match wrapper.error {
-            hiring::FillOpeningError::<T>::OpeningDoesNotExist => {
-                Error::FullWorkerOpeningOpeningDoesNotExist
-            }
-            hiring::FillOpeningError::<T>::OpeningNotInReviewPeriodStage => {
-                Error::FullWorkerOpeningOpeningNotInReviewPeriodStage
-            }
-            hiring::FillOpeningError::<T>::UnstakingPeriodTooShort(
-                stake_purpose,
-                outcome_in_filled_opening,
-            ) => match stake_purpose {
-                hiring::StakePurpose::Application => match outcome_in_filled_opening {
-                    hiring::ApplicationOutcomeInFilledOpening::Success => {
-                        Error::FullWorkerOpeningSuccessfulApplicationStakeUnstakingPeriodTooShort
-                    }
-                    hiring::ApplicationOutcomeInFilledOpening::Failure => {
-                        Error::FullWorkerOpeningUnsuccessfulApplicationStakeUnstakingPeriodTooShort
-                    }
-                },
-                hiring::StakePurpose::Role => match outcome_in_filled_opening {
-                    hiring::ApplicationOutcomeInFilledOpening::Success => {
-                        Error::FullWorkerOpeningSuccessfulRoleStakeUnstakingPeriodTooShort
-                    }
-                    hiring::ApplicationOutcomeInFilledOpening::Failure => {
-                        Error::FullWorkerOpeningUnsuccessfulRoleStakeUnstakingPeriodTooShort
-                    }
-                },
-            },
-            hiring::FillOpeningError::<T>::RedundantUnstakingPeriodProvided(
-                stake_purpose,
-                outcome_in_filled_opening,
-            ) => match stake_purpose {
-                hiring::StakePurpose::Application => match outcome_in_filled_opening {
-                    hiring::ApplicationOutcomeInFilledOpening::Success => {
-                        Error::FullWorkerOpeningSuccessfulApplicationStakeUnstakingPeriodRedundant
-                    }
-                    hiring::ApplicationOutcomeInFilledOpening::Failure => {
-                        Error::FullWorkerOpeningUnsuccessfulApplicationStakeUnstakingPeriodRedundant
-                    }
-                },
-                hiring::StakePurpose::Role => match outcome_in_filled_opening {
-                    hiring::ApplicationOutcomeInFilledOpening::Success => {
-                        Error::FullWorkerOpeningSuccessfulRoleStakeUnstakingPeriodRedundant
-                    }
-                    hiring::ApplicationOutcomeInFilledOpening::Failure => {
-                        Error::FullWorkerOpeningUnsuccessfulRoleStakeUnstakingPeriodRedundant
-                    }
-                },
-            },
-            hiring::FillOpeningError::<T>::ApplicationDoesNotExist(_application_id) => {
-                Error::FullWorkerOpeningApplicationDoesNotExist
-            }
-            hiring::FillOpeningError::<T>::ApplicationNotInActiveStage(_application_id) => {
-                Error::FullWorkerOpeningApplicationNotActive
-            }
-            hiring::FillOpeningError::<T>::ApplicationForWrongOpening(_application_id) => {
-                Error::FillWorkerOpeningApplicationForWrongOpening
-            }
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance>
-    sp_std::convert::From<WrappedError<hiring::DeactivateApplicationError>> for Error<T, I>
-{
-    fn from(wrapper: WrappedError<hiring::DeactivateApplicationError>) -> Self {
-        match wrapper.error {
-            hiring::DeactivateApplicationError::ApplicationDoesNotExist => {
-                Error::WithdrawWorkerApplicationApplicationDoesNotExist
-            }
-            hiring::DeactivateApplicationError::ApplicationNotActive => {
-                Error::WithdrawWorkerApplicationApplicationNotActive
-            }
-            hiring::DeactivateApplicationError::OpeningNotAcceptingApplications => {
-                Error::WithdrawWorkerApplicationOpeningNotAcceptingApplications
-            }
-            hiring::DeactivateApplicationError::UnstakingPeriodTooShort(_stake_purpose) => {
-                Error::WithdrawWorkerApplicationUnstakingPeriodTooShort
-            }
-            hiring::DeactivateApplicationError::RedundantUnstakingPeriodProvided(
-                _stake_purpose,
-            ) => Error::WithdrawWorkerApplicationRedundantUnstakingPeriod,
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance> sp_std::convert::From<WrappedError<hiring::AddApplicationError>>
-    for Error<T, I>
-{
-    fn from(wrapper: WrappedError<hiring::AddApplicationError>) -> Self {
-        match wrapper.error {
-            hiring::AddApplicationError::OpeningDoesNotExist => {
-                Error::AddWorkerOpeningOpeningDoesNotExist
-            }
-            hiring::AddApplicationError::StakeProvidedWhenRedundant(_stake_purpose) => {
-                Error::AddWorkerOpeningStakeProvidedWhenRedundant
-            }
-            hiring::AddApplicationError::StakeMissingWhenRequired(_stake_purpose) => {
-                Error::AddWorkerOpeningStakeMissingWhenRequired
-            }
-            hiring::AddApplicationError::StakeAmountTooLow(_stake_purpose) => {
-                Error::AddWorkerOpeningStakeAmountTooLow
-            }
-            hiring::AddApplicationError::OpeningNotInAcceptingApplicationsStage => {
-                Error::AddWorkerOpeningOpeningNotInAcceptingApplicationStage
-            }
-            hiring::AddApplicationError::NewApplicationWasCrowdedOut => {
-                Error::AddWorkerOpeningNewApplicationWasCrowdedOut
-            }
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance>
-    sp_std::convert::From<WrappedError<membership::MemberControllerAccountDidNotSign>>
-    for Error<T, I>
-{
-    fn from(wrapper: WrappedError<membership::MemberControllerAccountDidNotSign>) -> Self {
-        match wrapper.error {
-            membership::MemberControllerAccountDidNotSign::UnsignedOrigin => {
-                Error::MembershipUnsignedOrigin
-            }
-            membership::MemberControllerAccountDidNotSign::MemberIdInvalid => {
-                Error::MembershipInvalidMemberId
-            }
-            membership::MemberControllerAccountDidNotSign::SignerControllerAccountMismatch => {
-                Error::ApplyOnWorkerOpeningSignerNotControllerAccount
-            }
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance> sp_std::convert::From<WrappedError<recurringrewards::RewardsError>>
-    for Error<T, I>
-{
-    fn from(wrapper: WrappedError<recurringrewards::RewardsError>) -> Self {
-        match wrapper.error {
-            recurringrewards::RewardsError::NextPaymentNotInFuture => {
-                Error::RecurringRewardsNextPaymentNotInFuture
-            }
-            recurringrewards::RewardsError::RecipientNotFound => {
-                Error::RecurringRewardsRecipientNotFound
-            }
-            recurringrewards::RewardsError::RewardSourceNotFound => {
-                Error::RecurringRewardsRewardSourceNotFound
-            }
-            recurringrewards::RewardsError::RewardRelationshipNotFound => {
-                Error::RecurringRewardsRewardRelationshipNotFound
-            }
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance>
-    sp_std::convert::From<WrappedError<stake::StakeActionError<stake::InitiateUnstakingError>>>
-    for Error<T, I>
-{
-    fn from(wrapper: WrappedError<stake::StakeActionError<stake::InitiateUnstakingError>>) -> Self {
-        match wrapper.error {
-            stake::StakeActionError::StakeNotFound => Error::StakingErrorStakeNotFound,
-            stake::StakeActionError::Error(initiate_unstaking_error) => {
-                match initiate_unstaking_error {
-                    stake::InitiateUnstakingError::UnstakingPeriodShouldBeGreaterThanZero => {
-                        Error::StakingErrorUnstakingPeriodShouldBeGreaterThanZero
-                    }
-                    stake::InitiateUnstakingError::UnstakingError(unstaking_error) => {
-                        match unstaking_error {
-                            stake::UnstakingError::AlreadyUnstaking => {
-                                Error::StakingErrorAlreadyUnstaking
-                            }
-                            stake::UnstakingError::NotStaked => Error::StakingErrorNotStaked,
-                            stake::UnstakingError::CannotUnstakeWhileSlashesOngoing => {
-                                Error::StakingErrorCannotUnstakeWhileSlashesOngoing
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance>
-    sp_std::convert::From<
-        WrappedError<stake::StakeActionError<stake::IncreasingStakeFromAccountError>>,
-    > for Error<T, I>
-{
-    fn from(
-        wrapper: WrappedError<stake::StakeActionError<stake::IncreasingStakeFromAccountError>>,
-    ) -> Self {
-        match wrapper.error {
-            stake::StakeActionError::StakeNotFound => Error::StakingErrorStakeNotFound,
-            stake::StakeActionError::Error(increase_stake_error_from_account) => {
-                match increase_stake_error_from_account {
-                    stake::IncreasingStakeFromAccountError::InsufficientBalanceInSourceAccount => {
-                        Error::StakingErrorInsufficientBalanceInSourceAccount
-                    }
-                    stake::IncreasingStakeFromAccountError::IncreasingStakeError(
-                        increasing_stake_error,
-                    ) => match increasing_stake_error {
-                        stake::IncreasingStakeError::NotStaked => Error::StakingErrorNotStaked,
-                        stake::IncreasingStakeError::CannotChangeStakeByZero => {
-                            Error::StakingErrorCannotChangeStakeByZero
-                        }
-                        stake::IncreasingStakeError::CannotIncreaseStakeWhileUnstaking => {
-                            Error::StakingErrorCannotIncreaseStakeWhileUnstaking
-                        }
-                    },
-                }
-            }
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance>
-    sp_std::convert::From<WrappedError<stake::StakeActionError<stake::IncreasingStakeError>>>
-    for Error<T, I>
-{
-    fn from(wrapper: WrappedError<stake::StakeActionError<stake::IncreasingStakeError>>) -> Self {
-        match wrapper.error {
-            stake::StakeActionError::StakeNotFound => Error::StakingErrorStakeNotFound,
-            stake::StakeActionError::Error(increasing_stake_error) => {
-                match increasing_stake_error {
-                    stake::IncreasingStakeError::NotStaked => Error::StakingErrorNotStaked,
-                    stake::IncreasingStakeError::CannotChangeStakeByZero => {
-                        Error::StakingErrorCannotChangeStakeByZero
-                    }
-                    stake::IncreasingStakeError::CannotIncreaseStakeWhileUnstaking => {
-                        Error::StakingErrorCannotIncreaseStakeWhileUnstaking
-                    }
-                }
-            }
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance>
-    sp_std::convert::From<WrappedError<stake::StakeActionError<stake::DecreasingStakeError>>>
-    for Error<T, I>
-{
-    fn from(wrapper: WrappedError<stake::StakeActionError<stake::DecreasingStakeError>>) -> Self {
-        match wrapper.error {
-            stake::StakeActionError::StakeNotFound => Error::StakingErrorStakeNotFound,
-            stake::StakeActionError::Error(decreasing_stake_error) => {
-                match decreasing_stake_error {
-                    stake::DecreasingStakeError::NotStaked => Error::StakingErrorNotStaked,
-                    stake::DecreasingStakeError::CannotChangeStakeByZero => {
-                        Error::StakingErrorCannotChangeStakeByZero
-                    }
-                    stake::DecreasingStakeError::CannotDecreaseStakeWhileUnstaking => {
-                        Error::StakingErrorCannotIncreaseStakeWhileUnstaking
-                    }
-                    stake::DecreasingStakeError::CannotDecreaseStakeWhileOngoingSlahes => {
-                        Error::StakingErrorCannotDecreaseWhileSlashesOngoing
-                    }
-                    stake::DecreasingStakeError::InsufficientStake => {
-                        Error::StakingErrorInsufficientStake
-                    }
-                }
-            }
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance>
-    sp_std::convert::From<WrappedError<stake::StakeActionError<stake::ImmediateSlashingError>>>
-    for Error<T, I>
-{
-    fn from(wrapper: WrappedError<stake::StakeActionError<stake::ImmediateSlashingError>>) -> Self {
-        match wrapper.error {
-            stake::StakeActionError::StakeNotFound => Error::StakingErrorStakeNotFound,
-            stake::StakeActionError::Error(slashing_error) => match slashing_error {
-                stake::ImmediateSlashingError::NotStaked => Error::StakingErrorNotStaked,
-                stake::ImmediateSlashingError::SlashAmountShouldBeGreaterThanZero => {
-                    Error::StakingErrorSlashAmountShouldBeGreaterThanZero
-                }
-            },
-        }
-    }
-}
-
-impl<T: Trait<I>, I: Instance> sp_std::convert::From<WrappedError<minting::GeneralError>>
-    for Error<T, I>
-{
-    fn from(wrapper: WrappedError<minting::GeneralError>) -> Self {
-        match wrapper.error {
-            minting::GeneralError::MintNotFound => Error::CannotFindMint,
-            minting::GeneralError::NextAdjustmentInPast => Error::MintingErrorNextAdjustmentInPast,
-        }
-    }
-}

+ 0 - 1630
runtime-modules/working-group/src/lib.rs

@@ -1,1630 +0,0 @@
-//! # Working group module
-//! Working group module for the Joystream platform.
-//! Contains abstract working group workflow.
-//!
-//! ## Overview
-//!
-//! The working group module provides working group workflow to use in different modules.
-//! It contains extrinsics for the hiring workers, their roles lifecycle and stake management.
-//! There is a possibility to hire a special worker - the leader of the working group.
-//! Some module operations like 'increase_stake' can be invoked by the worker, others
-//! like 'terminate_role' can be invoked by the leader only. The leader himself can be hired and
-//! managed only by the council via proposals.
-//!
-//! Exact working group (eg.: forum working group) should create an instance of the Working group module.
-//!
-//! ## Supported extrinsics
-//! ### Hiring flow
-//!
-//! - [add_opening](./struct.Module.html#method.add_opening) - Add an opening for a worker/lead role.
-//! - [accept_applications](./struct.Module.html#method.accept_applications)- Begin accepting worker/lead applications.
-//! - [begin_applicant_review](./struct.Module.html#method.begin_applicant_review) - Begin reviewing worker/lead applications.
-//! - [fill_opening](./struct.Module.html#method.fill_opening) - Fill opening for worker/lead.
-//! - [withdraw_application](./struct.Module.html#method.withdraw_application) - Withdraw the worker/lead application.
-//! - [terminate_application](./struct.Module.html#method.terminate_application) - Terminate the worker/lead application.
-//! - [apply_on_opening](./struct.Module.html#method.apply_on_opening) - Apply on a worker/lead opening.
-//!
-//! ### Roles lifecycle
-//!
-//! - [update_role_account](./struct.Module.html#method.update_role_account) -  Update the role account of the worker/lead.
-//! - [update_reward_account](./struct.Module.html#method.update_reward_account) -  Update the reward account of the worker/lead.
-//! - [update_reward_amount](./struct.Module.html#method.update_reward_amount) -  Update the reward amount of the worker/lead.
-//! - [leave_role](./struct.Module.html#method.leave_role) - Leave the role by the active worker/lead.
-//! - [terminate_role](./struct.Module.html#method.terminate_role) - Terminate the worker/lead role.
-//! - [set_mint_capacity](./struct.Module.html#method.set_mint_capacity) -  Sets the capacity to enable working group budget.
-//!
-//! ### Stakes
-//!
-//! - [slash_stake](./struct.Module.html#method.slash_stake) - Slashes the worker/lead stake.
-//! - [decrease_stake](./struct.Module.html#method.decrease_stake) - Decreases the worker/lead stake and returns the remainder to the worker _role_account_.
-//! - [increase_stake](./struct.Module.html#method.increase_stake) - Increases the worker/lead stake.
-//!
-
-// Ensure we're `no_std` when compiling for Wasm.
-#![cfg_attr(not(feature = "std"), no_std)]
-
-// Do not delete! Cannot be uncommented by default, because of Parity decl_module! issue.
-//#![warn(missing_docs)]
-
-#[cfg(test)]
-mod tests;
-mod types;
-#[macro_use]
-mod errors;
-
-use frame_support::dispatch::{DispatchError, DispatchResult};
-use frame_support::storage::IterableStorageMap;
-use frame_support::traits::{Currency, ExistenceRequirement, Get, Imbalance, WithdrawReasons};
-use frame_support::{decl_event, decl_module, decl_storage, ensure, print, StorageValue};
-use frame_system::{ensure_root, ensure_signed};
-use sp_arithmetic::traits::{Bounded, One, Zero};
-use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};
-use sp_std::vec;
-use sp_std::vec::Vec;
-
-use crate::types::ExitInitiationOrigin;
-use common::constraints::InputValidationLengthConstraint;
-use errors::WrappedError;
-
-pub use errors::Error;
-pub use types::{
-    Application, Opening, OpeningPolicyCommitment, OpeningType, RewardPolicy, RoleStakeProfile,
-    Worker,
-};
-
-/// Stake identifier in staking module
-pub type StakeId<T> = <T as stake::Trait>::StakeId;
-
-/// Member identifier in membership::member module
-pub type MemberId<T> = <T as membership::Trait>::MemberId;
-
-/// Workaround for BTreeSet type
-pub type ApplicationIdSet<T> = BTreeSet<ApplicationId<T>>;
-
-/// Type for the identifier for an opening for a worker/lead.
-pub type OpeningId<T> = <T as hiring::Trait>::OpeningId;
-
-/// Type for the identifier for an application as a worker/lead.
-pub type ApplicationId<T> = <T as hiring::Trait>::ApplicationId;
-
-/// Balance type of runtime
-pub type BalanceOf<T> =
-    <<T as stake::Trait>::Currency as Currency<<T as frame_system::Trait>::AccountId>>::Balance;
-
-/// Balance type of runtime reward
-pub type BalanceOfMint<T> =
-    <<T as minting::Trait>::Currency as Currency<<T as frame_system::Trait>::AccountId>>::Balance;
-
-/// Balance type of runtime
-pub type CurrencyOf<T> = <T as stake::Trait>::Currency;
-
-/// Negative imbalance of runtime.
-pub type NegativeImbalance<T> = <<T as stake::Trait>::Currency as Currency<
-    <T as frame_system::Trait>::AccountId,
->>::NegativeImbalance;
-
-/// Alias for the worker application id to the worker id dictionary
-pub type ApplicationIdToWorkerIdMap<T> = BTreeMap<ApplicationId<T>, WorkerId<T>>;
-
-/// Type identifier for worker role, which must be same as membership actor identifier
-pub type WorkerId<T> = <T as membership::Trait>::ActorId;
-
-/// Alias for the application id from the hiring module.
-pub type HiringApplicationId<T> = <T as hiring::Trait>::ApplicationId;
-
-// Type simplification
-type OpeningInfo<T> = (
-    OpeningOf<T>,
-    hiring::Opening<BalanceOf<T>, <T as frame_system::Trait>::BlockNumber, HiringApplicationId<T>>,
-);
-
-// Type simplification
-type ApplicationInfo<T> = (ApplicationOf<T>, ApplicationId<T>, OpeningOf<T>);
-
-// Type simplification
-type RewardSettings<T> = (
-    <T as minting::Trait>::MintId,
-    RewardPolicy<BalanceOfMint<T>, <T as frame_system::Trait>::BlockNumber>,
-);
-
-// Type simplification
-type WorkerOf<T> = Worker<
-    <T as frame_system::Trait>::AccountId,
-    <T as recurringrewards::Trait>::RewardRelationshipId,
-    <T as stake::Trait>::StakeId,
-    <T as frame_system::Trait>::BlockNumber,
-    MemberId<T>,
->;
-
-// Type simplification
-type OpeningOf<T> = Opening<
-    <T as hiring::Trait>::OpeningId,
-    <T as frame_system::Trait>::BlockNumber,
-    BalanceOf<T>,
-    ApplicationId<T>,
->;
-
-// Type simplification
-type ApplicationOf<T> = Application<
-    <T as frame_system::Trait>::AccountId,
-    OpeningId<T>,
-    MemberId<T>,
-    HiringApplicationId<T>,
->;
-
-/// The _Working group_ main _Trait_
-pub trait Trait<I: Instance>:
-    frame_system::Trait
-    + membership::Trait
-    + hiring::Trait
-    + minting::Trait
-    + stake::Trait
-    + recurringrewards::Trait
-{
-    /// _Working group_ event type.
-    type Event: From<Event<Self, I>> + Into<<Self as frame_system::Trait>::Event>;
-
-    /// Defines max workers number in the working group.
-    type MaxWorkerNumberLimit: Get<u32>;
-}
-
-decl_event!(
-    /// _Working group_ events
-    pub enum Event<T, I>
-    where
-        WorkerId = WorkerId<T>,
-        <T as frame_system::Trait>::AccountId,
-        OpeningId = OpeningId<T>,
-        ApplicationId = ApplicationId<T>,
-        ApplicationIdToWorkerIdMap = ApplicationIdToWorkerIdMap<T>,
-        RationaleText = Vec<u8>,
-        MintBalanceOf = minting::BalanceOf<T>,
-        <T as minting::Trait>::MintId,
-    {
-        /// Emits on setting the leader.
-        /// Params:
-        /// - Worker id.
-        LeaderSet(WorkerId),
-
-        /// Emits on un-setting the leader.
-        /// Params:
-        LeaderUnset(),
-
-        /// Emits on terminating the worker.
-        /// Params:
-        /// - worker id.
-        /// - termination rationale text
-        TerminatedWorker(WorkerId, RationaleText),
-
-        /// Emits on terminating the leader.
-        /// Params:
-        /// - leader worker id.
-        /// - termination rationale text
-        TerminatedLeader(WorkerId, RationaleText),
-
-        /// Emits on exiting the worker.
-        /// Params:
-        /// - worker id.
-        /// - exit rationale text
-        WorkerExited(WorkerId, RationaleText),
-
-        /// Emits on updating the role account of the worker.
-        /// Params:
-        /// - Id of the worker.
-        /// - Role account id of the worker.
-        WorkerRoleAccountUpdated(WorkerId, AccountId),
-
-        /// Emits on updating the reward account of the worker.
-        /// Params:
-        /// - Member id of the worker.
-        /// - Reward account id of the worker.
-        WorkerRewardAccountUpdated(WorkerId, AccountId),
-
-        /// Emits on updating the reward amount of the worker.
-        /// Params:
-        /// - Id of the worker.
-        WorkerRewardAmountUpdated(WorkerId),
-
-        /// Emits on adding new worker opening.
-        /// Params:
-        /// - Opening id
-        OpeningAdded(OpeningId),
-
-        /// Emits on accepting application for the worker opening.
-        /// Params:
-        /// - Opening id
-        AcceptedApplications(OpeningId),
-
-        /// Emits on adding the application for the worker opening.
-        /// Params:
-        /// - Opening id
-        /// - Application id
-        AppliedOnOpening(OpeningId, ApplicationId),
-
-        /// Emits on withdrawing the application for the worker/lead opening.
-        /// Params:
-        /// - Worker application id
-        ApplicationWithdrawn(ApplicationId),
-
-        /// Emits on terminating the application for the worker/lead opening.
-        /// Params:
-        /// - Worker application id
-        ApplicationTerminated(ApplicationId),
-
-        /// Emits on beginning the application review for the worker/lead opening.
-        /// Params:
-        /// - Opening id
-        BeganApplicationReview(OpeningId),
-
-        /// Emits on filling the worker opening.
-        /// Params:
-        /// - Worker opening id
-        /// - Worker application id to the worker id dictionary
-        OpeningFilled(OpeningId, ApplicationIdToWorkerIdMap),
-
-        /// Emits on increasing the worker/lead stake.
-        /// Params:
-        /// - worker/lead id.
-        StakeIncreased(WorkerId),
-
-        /// Emits on decreasing the worker/lead stake.
-        /// Params:
-        /// - worker/lead id.
-        StakeDecreased(WorkerId),
-
-        /// Emits on slashing the worker/lead stake.
-        /// Params:
-        /// - worker/lead id.
-        StakeSlashed(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 WorkingGroup {
-        /// The mint currently funding the rewards for this module.
-        pub Mint get(fn mint) : <T as minting::Trait>::MintId;
-
-        /// The current lead.
-        pub CurrentLead get(fn current_lead) : Option<WorkerId<T>>;
-
-        /// Next identifier value for new worker opening.
-        pub NextOpeningId get(fn next_opening_id): OpeningId<T>;
-
-        /// Maps identifier to worker opening.
-        pub OpeningById get(fn opening_by_id): map hasher(blake2_128_concat)
-            OpeningId<T> => OpeningOf<T>;
-
-        /// Opening human readable text length limits
-        pub OpeningHumanReadableText get(fn opening_human_readable_text): InputValidationLengthConstraint;
-
-        /// Maps identifier to worker application on opening.
-        pub ApplicationById get(fn application_by_id) : map hasher(blake2_128_concat)
-            ApplicationId<T> => ApplicationOf<T>;
-
-        /// Next identifier value for new worker application.
-        pub NextApplicationId get(fn next_application_id) : ApplicationId<T>;
-
-        /// Worker application human readable text length limits
-        pub WorkerApplicationHumanReadableText get(fn application_human_readable_text) : InputValidationLengthConstraint;
-
-        /// Maps identifier to corresponding worker.
-        pub WorkerById get(fn worker_by_id) : map hasher(blake2_128_concat)
-            WorkerId<T> => WorkerOf<T>;
-
-        /// Count of active workers.
-        pub ActiveWorkerCount get(fn active_worker_count): u32;
-
-        /// Next identifier for new worker.
-        pub NextWorkerId get(fn next_worker_id) : WorkerId<T>;
-
-        /// Worker exit rationale text length limits.
-        pub WorkerExitRationaleText get(fn worker_exit_rationale_text) : InputValidationLengthConstraint;
-
-        /// Map member id by hiring application id.
-        /// Required by StakingEventsHandler callback call to refund the balance on unstaking.
-        pub MemberIdByHiringApplicationId get(fn member_id_by_hiring_application_id):
-            map hasher(blake2_128_concat) HiringApplicationId<T> =>  MemberId<T>;
-    }
-        add_extra_genesis {
-        config(phantom): sp_std::marker::PhantomData<I>;
-        config(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.working_group_mint_capacity)
-        });
-    }
-}
-
-decl_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;
-
-        /// Predefined errors
-        type Error = Error<T, I>;
-
-        /// Exports const -  max simultaneous active worker number.
-        const MaxWorkerNumberLimit: u32 = T::MaxWorkerNumberLimit::get();
-
-        // ****************** Roles lifecycle **********************
-
-        /// Update the associated role account of the active worker/lead.
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn update_role_account(
-            origin,
-            worker_id: WorkerId<T>,
-            new_role_account_id: T::AccountId
-        ) {
-            // Ensuring worker actually exists
-            let worker = Self::ensure_worker_exists(&worker_id)?;
-
-            // Ensure that origin is signed by member with given id.
-            ensure_on_wrapped_error!(
-                membership::Module::<T>::ensure_member_controller_account_signed(origin, &worker.member_id)
-            )?;
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            // Update role account
-            WorkerById::<T, I>::mutate(worker_id, |worker| {
-                worker.role_account_id = new_role_account_id.clone()
-            });
-
-            // Trigger event
-            Self::deposit_event(RawEvent::WorkerRoleAccountUpdated(worker_id, new_role_account_id));
-        }
-
-        /// Update the reward account associated with a set reward relationship for the active worker.
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn update_reward_account(
-            origin,
-            worker_id: WorkerId<T>,
-            new_reward_account_id: T::AccountId
-        ) {
-            // Ensure there is a signer which matches role account of worker corresponding to provided id.
-            let worker = Self::ensure_worker_signed(origin, &worker_id)?;
-
-            // Ensure the worker actually has a recurring reward
-            let relationship_id = Self::ensure_worker_has_recurring_reward(&worker)?;
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            // Update only the reward account.
-            ensure_on_wrapped_error!(
-                recurringrewards::Module::<T>::set_reward_relationship(
-                    relationship_id,
-                    Some(new_reward_account_id.clone()), // new_account
-                    None, // new_payout
-                    None, //new_next_payment_at
-                    None) //new_payout_interval
-            )?;
-
-            // Trigger event
-            Self::deposit_event(RawEvent::WorkerRewardAccountUpdated(worker_id, new_reward_account_id));
-        }
-
-        /// Update the reward amount associated with a set reward relationship for the active worker.
-        /// Require signed leader origin or the root (to update leader reward amount).
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn update_reward_amount(
-            origin,
-            worker_id: WorkerId<T>,
-            new_amount: BalanceOfMint<T>
-        ) {
-            // Ensure lead is set and is origin signer or it is the council.
-            Self::ensure_origin_for_leader(origin, worker_id)?;
-
-            // Ensuring worker actually exists
-            let worker = Self::ensure_worker_exists(&worker_id)?;
-
-            // Ensure the worker actually has a recurring reward
-            let relationship_id = Self::ensure_worker_has_recurring_reward(&worker)?;
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            // Update only the reward account.
-            ensure_on_wrapped_error!(
-                recurringrewards::Module::<T>::set_reward_relationship(
-                    relationship_id,
-                    None, // new_account
-                    Some(new_amount), // new_payout
-                    None, //new_next_payment_at
-                    None) //new_payout_interval
-            )?;
-
-            // Trigger event
-            Self::deposit_event(RawEvent::WorkerRewardAmountUpdated(worker_id));
-        }
-
-        /// Leave the role by the active worker.
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn leave_role(
-            origin,
-            worker_id: WorkerId<T>,
-            rationale_text: Vec<u8>
-        ) {
-            // Ensure there is a signer which matches role account of worker corresponding to provided id.
-            let active_worker = Self::ensure_worker_signed(origin, &worker_id)?;
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            Self::deactivate_worker(
-                &worker_id,
-                &active_worker,
-                &ExitInitiationOrigin::Worker,
-                &rationale_text
-            )?;
-        }
-
-        /// Terminate the active worker by the lead.
-        /// Require signed leader origin or the root (to terminate the leader role).
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn terminate_role(
-            origin,
-            worker_id: WorkerId<T>,
-            rationale_text: Vec<u8>,
-            slash_stake: bool,
-        ) {
-            // Ensure lead is set or it is the council terminating the leader.
-            let exit_origin = Self::ensure_origin_for_leader(origin.clone(), worker_id)?;
-
-            // Ensuring worker actually exists.
-            let worker = Self::ensure_worker_exists(&worker_id)?;
-
-            // Ensure rationale text is valid.
-            Self::ensure_worker_exit_rationale_text_is_valid(&rationale_text)?;
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            if slash_stake {
-                Self::slash_stake(origin, worker_id, BalanceOf::<T>::max_value())?;
-            }
-
-            Self::deactivate_worker(
-                &worker_id,
-                &worker,
-                &exit_origin,
-                &rationale_text
-            )?;
-        }
-
-        // ****************** Hiring flow **********************
-
-        /// Add an opening for a worker role.
-        /// Require signed leader origin or the root (to add opening for the leader position).
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn add_opening(
-            origin,
-            activate_at: hiring::ActivateOpeningAt<T::BlockNumber>,
-            commitment: OpeningPolicyCommitment<T::BlockNumber, BalanceOf<T>>,
-            human_readable_text: Vec<u8>,
-            opening_type: OpeningType,
-        ){
-            Self::ensure_origin_for_opening_type(origin, opening_type)?;
-
-            Self::ensure_opening_human_readable_text_is_valid(&human_readable_text)?;
-
-            Self::ensure_opening_policy_commitment_is_valid(&commitment)?;
-
-
-            // Add opening
-            // NB: This call can in principle fail, because the staking policies
-            // may not respect the minimum currency requirement.
-
-            let policy_commitment = commitment.clone();
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            let opening_id = ensure_on_wrapped_error!(
-                hiring::Module::<T>::add_opening(
-                    activate_at,
-                    commitment.max_review_period_length,
-                    commitment.application_rationing_policy,
-                    commitment.application_staking_policy,
-                    commitment.role_staking_policy,
-                    human_readable_text,
-            ))?;
-
-            let new_opening_id = NextOpeningId::<T, I>::get();
-
-            // Create and add worker opening.
-            let new_opening_by_id = Opening::<OpeningId<T>, T::BlockNumber, BalanceOf<T>, ApplicationId<T>> {
-                hiring_opening_id: opening_id,
-                applications: BTreeSet::new(),
-                policy_commitment,
-                opening_type,
-            };
-
-            OpeningById::<T, I>::insert(new_opening_id, new_opening_by_id);
-
-            // Update NextOpeningId
-            NextOpeningId::<T, I>::mutate(|id| *id += <OpeningId<T> as One>::one());
-
-            // Trigger event
-            Self::deposit_event(RawEvent::OpeningAdded(new_opening_id));
-        }
-
-        /// Begin accepting worker applications to an opening that is active.
-        /// Require signed leader origin or the root (to accept applications for the leader position).
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn accept_applications(origin, opening_id: OpeningId<T>)  {
-            // Ensure opening exists in this working group
-            // NB: Even though call to hiring module will have implicit check for
-            // existence of opening as well, this check is to make sure that the opening is for
-            // this working group, not something else.
-            let (opening, _opening) = Self::ensure_opening_exists(&opening_id)?;
-
-            Self::ensure_origin_for_opening_type(origin, opening.opening_type)?;
-
-            // Attempt to begin accepting applications
-            // NB: Combined ensure check and mutation in hiring module
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            ensure_on_wrapped_error!(
-                hiring::Module::<T>::begin_accepting_applications(opening.hiring_opening_id)
-            )?;
-
-
-            // Trigger event
-            Self::deposit_event(RawEvent::AcceptedApplications(opening_id));
-        }
-
-        /// Apply on a worker opening.
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn apply_on_opening(
-            origin,
-            member_id: T::MemberId,
-            opening_id: OpeningId<T>,
-            role_account_id: T::AccountId,
-            opt_role_stake_balance: Option<BalanceOf<T>>,
-            opt_application_stake_balance: Option<BalanceOf<T>>,
-            human_readable_text: Vec<u8>
-        ) {
-            // Ensure origin which will server as the source account for staked funds is signed
-            let source_account = ensure_signed(origin)?;
-
-            // In absence of a more general key delegation system which allows an account with some funds to
-            // grant another account permission to stake from its funds, the origin of this call must have the funds
-            // and cannot specify another arbitrary account as the source account.
-            // Ensure the source_account is either the controller or root account of member with given id
-            ensure!(
-                membership::Module::<T>::ensure_member_controller_account(&source_account, &member_id).is_ok() ||
-                membership::Module::<T>::ensure_member_root_account(&source_account, &member_id).is_ok(),
-                Error::<T, I>::OriginIsNeitherMemberControllerOrRoot
-            );
-
-            // Ensure worker opening exists
-            let (opening, _opening) = Self::ensure_opening_exists(&opening_id)?;
-
-            // Ensure that there is sufficient balance to cover stake proposed
-            Self::ensure_can_make_stake_imbalance(
-                vec![&opt_role_stake_balance, &opt_application_stake_balance],
-                &source_account
-            )
-            .map_err(|_| Error::<T, I>::InsufficientBalanceToApply)?;
-
-            // Ensure application text is valid
-            Self::ensure_application_text_is_valid(&human_readable_text)?;
-
-            // Ensure application can actually be added
-            ensure_on_wrapped_error!(
-                hiring::Module::<T>::ensure_can_add_application(
-                    opening.hiring_opening_id,
-                    opt_role_stake_balance,
-                    opt_application_stake_balance)
-            )?;
-
-            // Ensure member does not have an active application to this opening
-            Self::ensure_member_has_no_active_application_on_opening(
-                opening.applications,
-                member_id
-            )?;
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            // Make imbalances for staking
-            let opt_role_stake_imbalance = Self::make_stake_opt_imbalance(&opt_role_stake_balance, &source_account);
-            let opt_application_stake_imbalance = Self::make_stake_opt_imbalance(&opt_application_stake_balance, &source_account);
-
-            // Call hiring module to add application
-            let add_application = ensure_on_wrapped_error!(
-                    hiring::Module::<T>::add_application(
-                    opening.hiring_opening_id,
-                    opt_role_stake_imbalance,
-                    opt_application_stake_imbalance,
-                    human_readable_text
-                )
-            )?;
-
-            let hiring_application_id = add_application.application_id_added;
-
-            // Save member id to refund the stakes. This piece of date should outlive the 'worker'.
-            <MemberIdByHiringApplicationId<T, I>>::insert(hiring_application_id, member_id);
-
-            // Get id of new worker/lead application
-            let new_application_id = NextApplicationId::<T, I>::get();
-
-            // Make worker/lead application
-            let application = Application::new(&role_account_id, &opening_id, &member_id, &hiring_application_id);
-
-            // Store application
-            ApplicationById::<T, I>::insert(new_application_id, application);
-
-            // Update next application identifier value
-            NextApplicationId::<T, I>::mutate(|id| *id += <ApplicationId<T> as One>::one());
-
-            // Add application to set of application in worker opening
-            OpeningById::<T, I>::mutate(opening_id, |opening| {
-                opening.applications.insert(new_application_id);
-            });
-
-            // Trigger event
-            Self::deposit_event(RawEvent::AppliedOnOpening(opening_id, new_application_id));
-        }
-
-        /// Withdraw the worker application. Can be done by the worker only.
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn withdraw_application(
-            origin,
-            application_id: ApplicationId<T>
-        ) {
-            // Ensuring worker application actually exists
-            let (application, _, opening) = Self::ensure_application_exists(&application_id)?;
-
-            // Ensure that it is signed
-            let signer_account = ensure_signed(origin)?;
-
-            // Ensure that signer is applicant role account
-            ensure!(
-                signer_account == application.role_account_id,
-                Error::<T, I>::OriginIsNotApplicant
-            );
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            // Attempt to deactivate application
-            // NB: Combined ensure check and mutation in hiring module
-            ensure_on_wrapped_error!(
-                hiring::Module::<T>::deactive_application(
-                    application.hiring_application_id,
-                    opening.policy_commitment.exit_role_application_stake_unstaking_period,
-                    opening.policy_commitment.exit_role_stake_unstaking_period
-                )
-            )?;
-
-            // Trigger event
-            Self::deposit_event(RawEvent::ApplicationWithdrawn(application_id));
-        }
-
-        /// Terminate the worker application. Can be done by the lead only.
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn terminate_application(
-            origin,
-            application_id: ApplicationId<T>
-        ) {
-
-            // Ensure lead is set and is origin signer
-            Self::ensure_origin_is_active_leader(origin)?;
-
-            // Ensuring worker application actually exists
-            let (application, _, opening) = Self::ensure_application_exists(&application_id)?;
-
-            // Attempt to deactivate application.
-            // NB: Combined ensure check and mutation in hiring module.
-            ensure_on_wrapped_error!(
-                hiring::Module::<T>::deactive_application(
-                    application.hiring_application_id,
-                    opening.policy_commitment.terminate_application_stake_unstaking_period,
-                    opening.policy_commitment.terminate_role_stake_unstaking_period
-                )
-            )?;
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            // Trigger event
-            Self::deposit_event(RawEvent::ApplicationTerminated(application_id));
-        }
-
-        /// Begin reviewing, and therefore not accepting new applications.
-        /// Require signed leader origin or the root (to begin review applications for the leader position).
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn begin_applicant_review(origin, opening_id: OpeningId<T>) {
-            // Ensure opening exists
-            // NB: Even though call to hiring modul will have implicit check for
-            // existence of opening as well, this check is to make sure that the opening is for
-            // this working group, not something else.
-            let (opening, _opening) = Self::ensure_opening_exists(&opening_id)?;
-
-            Self::ensure_origin_for_opening_type(origin, opening.opening_type)?;
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            // Attempt to begin review of applications.
-            // NB: Combined ensure check and mutation in hiring module.
-            ensure_on_wrapped_error!(
-                hiring::Module::<T>::begin_review(opening.hiring_opening_id)
-                )?;
-
-            // Trigger event
-            Self::deposit_event(RawEvent::BeganApplicationReview(opening_id));
-        }
-
-        /// Fill opening for worker/lead.
-        /// Require signed leader origin or the root (to fill opening for the leader position).
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn fill_opening(
-            origin,
-            opening_id: OpeningId<T>,
-            successful_application_ids: ApplicationIdSet<T>,
-            reward_policy: Option<RewardPolicy<minting::BalanceOf<T>, T::BlockNumber>>
-        ) {
-            // Ensure worker opening exists
-            let (opening, _) = Self::ensure_opening_exists(&opening_id)?;
-
-            Self::ensure_origin_for_opening_type(origin, opening.opening_type)?;
-
-            let potential_worker_number =
-                Self::active_worker_count() + (successful_application_ids.len() as u32);
-
-            ensure!(
-                potential_worker_number <= T::MaxWorkerNumberLimit::get(),
-                Error::<T, I>::MaxActiveWorkerNumberExceeded
-            );
-
-            // Cannot hire a lead when another leader exists.
-            if matches!(opening.opening_type, OpeningType::Leader) {
-                ensure!(!<CurrentLead<T,I>>::exists(), Error::<T, I>::CannotHireLeaderWhenLeaderExists);
-            }
-
-            // 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();
-
-                // Make sure valid parameters are selected for next payment at block number
-                ensure!(policy.next_payment_at_block > <frame_system::Module<T>>::block_number(),
-                    Error::<T, I>::FillOpeningInvalidNextPaymentBlock);
-
-                // The verified reward settings to use
-                Some((mint_id, policy))
-            } else {
-                None
-            };
-
-            // Make iterator over successful worker application
-            let successful_iter = successful_application_ids
-                                    .iter()
-                                    // recover worker application from id
-                                    .map(|application_id| { Self::ensure_application_exists(application_id)})
-                                    // remove Err cases, i.e. non-existing applications
-                                    .filter_map(|result| result.ok());
-
-            // Count number of successful workers provided
-            let num_provided_successful_application_ids = successful_application_ids.len();
-
-            // Ensure all worker applications exist
-            let number_of_successful_applications = successful_iter
-                                                    .clone()
-                                                    .count();
-
-            ensure!(
-                number_of_successful_applications == num_provided_successful_application_ids,
-                Error::<T, I>::SuccessfulWorkerApplicationDoesNotExist
-            );
-
-            // Attempt to fill opening
-            let successful_application_ids = successful_iter
-                                            .clone()
-                                            .map(|(successful_application, _, _)| successful_application.hiring_application_id)
-                                            .collect::<BTreeSet<_>>();
-
-            // Check for a single application for a leader.
-            if matches!(opening.opening_type, OpeningType::Leader) {
-                ensure!(successful_application_ids.len() == 1, Error::<T, I>::CannotHireMultipleLeaders);
-            }
-
-            // NB: Combined ensure check and mutation in hiring module
-            ensure_on_wrapped_error!(
-                hiring::Module::<T>::fill_opening(
-                    opening.hiring_opening_id,
-                    successful_application_ids,
-                    opening.policy_commitment.fill_opening_successful_applicant_application_stake_unstaking_period,
-                    opening.policy_commitment.fill_opening_failed_applicant_application_stake_unstaking_period,
-                    opening.policy_commitment.fill_opening_failed_applicant_role_stake_unstaking_period
-                )
-            )?;
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            // Process successful applications
-            let application_id_to_worker_id = Self::fulfill_successful_applications(
-                &opening,
-                create_reward_settings,
-                successful_iter.collect()
-            );
-
-            // Trigger event
-            Self::deposit_event(RawEvent::OpeningFilled(opening_id, application_id_to_worker_id));
-        }
-
-        // ****************** Stakes **********************
-
-        /// Slashes the worker stake, demands a leader origin. No limits, no actions on zero stake.
-        /// If slashing balance greater than the existing stake - stake is slashed to zero.
-        /// Require signed leader origin or the root (to slash the leader stake).
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn slash_stake(origin, worker_id: WorkerId<T>, balance: BalanceOf<T>) {
-            // Ensure lead is set or it is the council slashing the leader.
-            Self::ensure_origin_for_leader(origin, worker_id)?;
-
-            // Ensuring worker actually exists.
-            let worker = Self::ensure_worker_exists(&worker_id)?;
-
-            ensure!(balance != <BalanceOf<T>>::zero(), Error::<T, I>::StakeBalanceCannotBeZero);
-
-            let stake_profile = worker.role_stake_profile.ok_or(Error::<T, I>::NoWorkerStakeProfile)?;
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            // This external module call both checks and mutates the state.
-            ensure_on_wrapped_error!(
-                <stake::Module<T>>::slash_immediate(
-                    &stake_profile.stake_id,
-                    balance,
-                    false
-                )
-            )?;
-
-            Self::deposit_event(RawEvent::StakeSlashed(worker_id));
-        }
-
-        /// Decreases the worker/lead stake and returns the remainder to the worker role_account_id.
-        /// Can be decreased to zero, no actions on zero stake.
-        /// Require signed leader origin or the root (to decrease the leader stake).
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn decrease_stake(origin, worker_id: WorkerId<T>, balance: BalanceOf<T>) {
-            // Ensure lead is set or it is the council decreasing the leader's stake.
-            Self::ensure_origin_for_leader(origin, worker_id)?;
-
-            let worker = Self::ensure_worker_exists(&worker_id)?;
-
-            ensure!(balance != <BalanceOf<T>>::zero(), Error::<T, I>::StakeBalanceCannotBeZero);
-
-            let stake_profile = worker.role_stake_profile.ok_or(Error::<T, I>::NoWorkerStakeProfile)?;
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            // This external module call both checks and mutates the state.
-            ensure_on_wrapped_error!(
-                <stake::Module<T>>::decrease_stake_to_account(
-                    &stake_profile.stake_id,
-                    &worker.role_account_id,
-                    balance
-                )
-            )?;
-
-            Self::deposit_event(RawEvent::StakeDecreased(worker_id));
-        }
-
-        /// Increases the worker/lead stake, demands a worker origin. Transfers tokens from the worker
-        /// role_account_id to the stake. No limits on the stake.
-        #[weight = 10_000_000] // TODO: adjust weight
-        pub fn increase_stake(origin, worker_id: WorkerId<T>, balance: BalanceOf<T>) {
-            // Checks worker origin, worker existence
-            let worker = Self::ensure_worker_signed(origin, &worker_id)?;
-
-            ensure!(balance != <BalanceOf<T>>::zero(), Error::<T, I>::StakeBalanceCannotBeZero);
-
-            let stake_profile = worker.role_stake_profile.ok_or(Error::<T, I>::NoWorkerStakeProfile)?;
-
-            //
-            // == MUTATION SAFE ==
-            //
-
-            // This external module call both checks and mutates the state.
-            ensure_on_wrapped_error!(
-                <stake::Module<T>>::increase_stake_from_account(
-                    &stake_profile.stake_id,
-                    &worker.role_account_id,
-                    balance
-                )
-            )?;
-
-            Self::deposit_event(RawEvent::StakeIncreased(worker_id));
-        }
-
-        /// Sets the capacity to enable working group budget. Requires root origin.
-        #[weight = 10_000_000] // TODO: adjust weight
-        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>>::contains_key(mint_id), Error::<T, I>::CannotFindMint);
-
-            // Mint must exist - it is set at genesis or migration.
-            let mint = <minting::Module<T>>::mints(mint_id);
-
-            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));
-            }
-        }
-    }
-}
-
-// ****************** Ensures **********************
-
-impl<T: Trait<I>, I: Instance> Module<T, I> {
-    fn ensure_opening_policy_commitment_is_valid(
-        policy_commitment: &OpeningPolicyCommitment<T::BlockNumber, BalanceOf<T>>,
-    ) -> Result<(), Error<T, I>> {
-        // Helper function. Ensures that unstaking period is None or non-zero.
-        fn check_unstaking_period<BlockNumber: PartialEq + Zero, Error>(
-            unstaking_period: Option<BlockNumber>,
-            error: Error,
-        ) -> Result<(), Error> {
-            if let Some(unstaking_period) = unstaking_period {
-                ensure!(unstaking_period != Zero::zero(), error);
-            }
-            Ok(())
-        }
-
-        // Helper function. Ensures that unstaking period is None or non-zero in the staking_policy.
-        fn check_staking_policy<Balance, BlockNumber: PartialEq + Zero, Error>(
-            staking_policy: Option<hiring::StakingPolicy<Balance, BlockNumber>>,
-            crowded_out_unstaking_period_error: Error,
-            review_period_unstaking_period_error: Error,
-        ) -> Result<(), Error> {
-            if let Some(staking_policy) = staking_policy {
-                check_unstaking_period(
-                    staking_policy.crowded_out_unstaking_period_length,
-                    crowded_out_unstaking_period_error,
-                )?;
-
-                check_unstaking_period(
-                    staking_policy.review_period_expired_unstaking_period_length,
-                    review_period_unstaking_period_error,
-                )?;
-            }
-
-            Ok(())
-        }
-
-        // Check all fill_opening unstaking periods.
-        check_unstaking_period(
-            policy_commitment.fill_opening_failed_applicant_role_stake_unstaking_period,
-            Error::<T, I>::FillOpeningFailedApplicantRoleStakeUnstakingPeriodIsZero,
-        )?;
-
-        check_unstaking_period(
-            policy_commitment.fill_opening_failed_applicant_application_stake_unstaking_period,
-            Error::<T, I>::FillOpeningFailedApplicantApplicationStakeUnstakingPeriodIsZero,
-        )?;
-
-        check_unstaking_period(
-            policy_commitment.fill_opening_successful_applicant_application_stake_unstaking_period,
-            Error::<T, I>::FillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriodIsZero,
-        )?;
-
-        check_unstaking_period(
-            policy_commitment.exit_role_stake_unstaking_period,
-            Error::<T, I>::ExitRoleStakeUnstakingPeriodIsZero,
-        )?;
-
-        check_unstaking_period(
-            policy_commitment.exit_role_application_stake_unstaking_period,
-            Error::<T, I>::ExitRoleApplicationStakeUnstakingPeriodIsZero,
-        )?;
-
-        check_unstaking_period(
-            policy_commitment.terminate_role_stake_unstaking_period,
-            Error::<T, I>::TerminateRoleStakeUnstakingPeriodIsZero,
-        )?;
-
-        check_unstaking_period(
-            policy_commitment.terminate_application_stake_unstaking_period,
-            Error::<T, I>::TerminateApplicationStakeUnstakingPeriodIsZero,
-        )?;
-
-        check_staking_policy(
-            policy_commitment.role_staking_policy.clone(),
-            Error::<T, I>::RoleStakingPolicyCrowdedOutUnstakingPeriodIsZero,
-            Error::<T, I>::RoleStakingPolicyReviewPeriodUnstakingPeriodIsZero,
-        )?;
-
-        check_staking_policy(
-            policy_commitment.application_staking_policy.clone(),
-            Error::<T, I>::ApplicationStakingPolicyCrowdedOutUnstakingPeriodIsZero,
-            Error::<T, I>::ApplicationStakingPolicyReviewPeriodUnstakingPeriodIsZero,
-        )?;
-
-        if let Some(application_rationing_policy) =
-            policy_commitment.application_rationing_policy.clone()
-        {
-            ensure!(
-                application_rationing_policy.max_active_applicants > 0,
-                Error::<T, I>::ApplicationRationingPolicyMaxActiveApplicantsIsZero
-            );
-        }
-
-        Ok(())
-    }
-
-    fn ensure_origin_for_opening_type(
-        origin: T::Origin,
-        opening_type: OpeningType,
-    ) -> DispatchResult {
-        match opening_type {
-            OpeningType::Worker => {
-                // Ensure lead is set and is origin signer.
-                Self::ensure_origin_is_active_leader(origin)
-            }
-            OpeningType::Leader => {
-                // Council proposal.
-                ensure_root(origin).map_err(|err| err.into())
-            }
-        }
-    }
-
-    fn ensure_origin_for_leader(
-        origin: T::Origin,
-        worker_id: WorkerId<T>,
-    ) -> Result<ExitInitiationOrigin, DispatchError> {
-        let leader_worker_id = Self::ensure_lead_is_set()?;
-
-        let (worker_opening_type, exit_origin) = if leader_worker_id == worker_id {
-            (OpeningType::Leader, ExitInitiationOrigin::Sudo)
-        } else {
-            (OpeningType::Worker, ExitInitiationOrigin::Lead)
-        };
-
-        Self::ensure_origin_for_opening_type(origin, worker_opening_type)?;
-
-        Ok(exit_origin)
-    }
-
-    fn ensure_lead_is_set() -> Result<WorkerId<T>, Error<T, I>> {
-        let leader_worker_id = Self::current_lead();
-
-        if let Some(leader_worker_id) = leader_worker_id {
-            Ok(leader_worker_id)
-        } else {
-            Err(Error::<T, I>::CurrentLeadNotSet)
-        }
-    }
-
-    // Checks that provided lead account id belongs to the current working group leader
-    fn ensure_is_lead_account(lead_account_id: T::AccountId) -> DispatchResult {
-        let leader_worker_id = Self::ensure_lead_is_set()?;
-
-        let leader = Self::worker_by_id(leader_worker_id);
-
-        if leader.role_account_id != lead_account_id {
-            return Err(Error::<T, I>::IsNotLeadAccount.into());
-        }
-
-        Ok(())
-    }
-
-    fn ensure_opening_human_readable_text_is_valid(text: &[u8]) -> DispatchResult {
-        <OpeningHumanReadableText<I>>::get()
-            .ensure_valid(
-                text.len(),
-                Error::<T, I>::OpeningTextTooShort.into(),
-                Error::<T, I>::OpeningTextTooLong.into(),
-            )
-            .map_err(|e| DispatchError::Other(e))
-    }
-
-    /// Ensures origin is signed by the leader.
-    pub fn ensure_origin_is_active_leader(origin: T::Origin) -> DispatchResult {
-        // Ensure is signed
-        let signer = ensure_signed(origin)?;
-
-        Self::ensure_is_lead_account(signer)
-    }
-
-    fn ensure_opening_exists(opening_id: &OpeningId<T>) -> Result<OpeningInfo<T>, Error<T, I>> {
-        ensure!(
-            OpeningById::<T, I>::contains_key(opening_id),
-            Error::<T, I>::OpeningDoesNotExist
-        );
-
-        let opening = OpeningById::<T, I>::get(opening_id);
-
-        let hiring_opening = hiring::OpeningById::<T>::get(opening.hiring_opening_id);
-
-        Ok((opening, hiring_opening))
-    }
-
-    fn ensure_member_has_no_active_application_on_opening(
-        applications: ApplicationIdSet<T>,
-        member_id: T::MemberId,
-    ) -> Result<(), Error<T, I>> {
-        for application_id in applications {
-            let application = ApplicationById::<T, I>::get(application_id);
-            // Look for application by the member for the opening
-            if application.member_id != member_id {
-                continue;
-            }
-            // Get application details
-            let application = <hiring::ApplicationById<T>>::get(application.hiring_application_id);
-            // Return error if application is in active stage
-            if application.stage == hiring::ApplicationStage::Active {
-                return Err(Error::<T, I>::MemberHasActiveApplicationOnOpening);
-            }
-        }
-        // Member does not have any active applications to the opening
-        Ok(())
-    }
-
-    fn ensure_application_text_is_valid(text: &[u8]) -> DispatchResult {
-        <WorkerApplicationHumanReadableText<I>>::get()
-            .ensure_valid(
-                text.len(),
-                Error::<T, I>::WorkerApplicationTextTooShort.into(),
-                Error::<T, I>::WorkerApplicationTextTooLong.into(),
-            )
-            .map_err(|e| DispatchError::Other(e))
-    }
-
-    // CRITICAL:
-    // https://github.com/Joystream/substrate-runtime-joystream/issues/92
-    // This assumes that ensure_can_withdraw can be done
-    // for a sum of balance that later will be actually withdrawn
-    // using individual terms in that sum.
-    // This needs to be fully checked across all possibly scenarios
-    // of actual balance, minimum balance limit, reservation, vesting and locking.
-    fn ensure_can_make_stake_imbalance(
-        opt_balances: Vec<&Option<BalanceOf<T>>>,
-        source_account: &T::AccountId,
-    ) -> DispatchResult {
-        let zero_balance = <BalanceOf<T> as Zero>::zero();
-
-        // Total amount to be staked
-        let total_amount = opt_balances.iter().fold(zero_balance, |sum, opt_balance| {
-            sum + if let Some(balance) = opt_balance {
-                *balance
-            } else {
-                zero_balance
-            }
-        });
-
-        if total_amount > zero_balance {
-            // Ensure that
-            if CurrencyOf::<T>::free_balance(source_account) < total_amount {
-                Err(Error::<T, I>::InsufficientBalanceToCoverStake.into())
-            } else {
-                let new_balance = CurrencyOf::<T>::free_balance(source_account) - total_amount;
-
-                CurrencyOf::<T>::ensure_can_withdraw(
-                    source_account,
-                    total_amount,
-                    WithdrawReasons::all(),
-                    new_balance,
-                )
-            }
-        } else {
-            Ok(())
-        }
-    }
-
-    fn ensure_application_exists(
-        application_id: &ApplicationId<T>,
-    ) -> Result<ApplicationInfo<T>, Error<T, I>> {
-        ensure!(
-            ApplicationById::<T, I>::contains_key(application_id),
-            Error::<T, I>::WorkerApplicationDoesNotExist
-        );
-
-        let application = ApplicationById::<T, I>::get(application_id);
-
-        let opening = OpeningById::<T, I>::get(application.opening_id);
-
-        Ok((application, *application_id, opening))
-    }
-
-    /// Ensures the origin contains signed account that belongs to existing worker.
-    pub fn ensure_worker_signed(
-        origin: T::Origin,
-        worker_id: &WorkerId<T>,
-    ) -> Result<WorkerOf<T>, DispatchError> {
-        // Ensure that it is signed
-        let signer_account = ensure_signed(origin)?;
-
-        // Ensure that id corresponds to active worker
-        let worker = Self::ensure_worker_exists(&worker_id)?;
-
-        // Ensure that signer is actually role account of worker
-        ensure!(
-            signer_account == worker.role_account_id,
-            Error::<T, I>::SignerIsNotWorkerRoleAccount
-        );
-
-        Ok(worker)
-    }
-
-    /// Ensures worker under given id already exists
-    pub fn ensure_worker_exists(worker_id: &WorkerId<T>) -> Result<WorkerOf<T>, Error<T, I>> {
-        ensure!(
-            WorkerById::<T, I>::contains_key(worker_id),
-            Error::<T, I>::WorkerDoesNotExist
-        );
-
-        let worker = WorkerById::<T, I>::get(worker_id);
-
-        Ok(worker)
-    }
-
-    fn ensure_worker_has_recurring_reward(
-        worker: &WorkerOf<T>,
-    ) -> Result<T::RewardRelationshipId, Error<T, I>> {
-        if let Some(relationship_id) = worker.reward_relationship {
-            Ok(relationship_id)
-        } else {
-            Err(Error::<T, I>::WorkerHasNoReward)
-        }
-    }
-
-    fn ensure_worker_exit_rationale_text_is_valid(text: &[u8]) -> DispatchResult {
-        Self::worker_exit_rationale_text()
-            .ensure_valid(
-                text.len(),
-                Error::<T, I>::WorkerExitRationaleTextTooShort.into(),
-                Error::<T, I>::WorkerExitRationaleTextTooLong.into(),
-            )
-            .map_err(|e| DispatchError::Other(e))
-    }
-}
-
-/// Creates default text constraint.
-pub fn default_text_constraint() -> InputValidationLengthConstraint {
-    InputValidationLengthConstraint::new(1, 1024)
-}
-
-impl<T: Trait<I>, I: Instance> Module<T, I> {
-    /// Callback from StakingEventsHandler. Refunds unstaked imbalance back to the source account.
-    pub fn refund_working_group_stake(
-        stake_id: StakeId<T>,
-        imbalance: NegativeImbalance<T>,
-    ) -> NegativeImbalance<T> {
-        if !hiring::ApplicationIdByStakingId::<T>::contains_key(stake_id) {
-            print("Working group broken invariant: no stake id in the hiring module.");
-            return imbalance;
-        }
-
-        let hiring_application_id = hiring::ApplicationIdByStakingId::<T>::get(stake_id);
-
-        if !MemberIdByHiringApplicationId::<T, I>::contains_key(hiring_application_id) {
-            // Stake is not related to the working group module.
-            return imbalance;
-        }
-
-        let member_id = Module::<T, I>::member_id_by_hiring_application_id(hiring_application_id);
-
-        if membership::MembershipById::<T>::contains_key(member_id) {
-            let member_profile = membership::MembershipById::<T>::get(member_id);
-            let refunding_result = CurrencyOf::<T>::resolve_into_existing(
-                &member_profile.controller_account,
-                imbalance,
-            );
-
-            if refunding_result.is_err() {
-                print("Working group broken invariant: cannot refund.");
-                // cannot return imbalance here, because of possible double spending.
-                return <NegativeImbalance<T>>::zero();
-            }
-        } else {
-            print("Working group broken invariant: no member profile.");
-            return imbalance;
-        }
-
-        <NegativeImbalance<T>>::zero()
-    }
-
-    /// Returns all existing worker id list excluding the current leader worker id.
-    pub fn get_regular_worker_ids() -> Vec<WorkerId<T>> {
-        let lead_worker_id = Self::current_lead();
-
-        <WorkerById<T, I>>::iter()
-            .filter_map(|(worker_id, _)| {
-                // Filter the leader worker id if the leader is set.
-                lead_worker_id
-                    .clone()
-                    .map_or(Some(worker_id), |lead_worker_id| {
-                        if worker_id == lead_worker_id {
-                            None
-                        } else {
-                            Some(worker_id)
-                        }
-                    })
-            })
-            .collect()
-    }
-
-    /// Returns all existing worker id list.
-    pub fn get_all_worker_ids() -> Vec<WorkerId<T>> {
-        <WorkerById<T, I>>::iter()
-            .map(|(worker_id, _)| worker_id)
-            .collect()
-    }
-
-    fn make_stake_opt_imbalance(
-        opt_balance: &Option<BalanceOf<T>>,
-        source_account: &T::AccountId,
-    ) -> Option<NegativeImbalance<T>> {
-        if let Some(balance) = opt_balance {
-            let withdraw_result = CurrencyOf::<T>::withdraw(
-                source_account,
-                *balance,
-                WithdrawReasons::all(),
-                ExistenceRequirement::AllowDeath,
-            );
-
-            assert!(withdraw_result.is_ok());
-
-            withdraw_result.ok()
-        } else {
-            None
-        }
-    }
-
-    fn deactivate_worker(
-        worker_id: &WorkerId<T>,
-        worker: &WorkerOf<T>,
-        exit_initiation_origin: &ExitInitiationOrigin,
-        rationale_text: &[u8],
-    ) -> Result<(), Error<T, I>> {
-        // Stop any possible recurring rewards
-
-        if let Some(reward_relationship_id) = worker.reward_relationship {
-            // Attempt to deactivate
-            recurringrewards::Module::<T>::try_to_deactivate_relationship(reward_relationship_id)
-                .map_err(|_| Error::<T, I>::RelationshipMustExist)?;
-        }; // else: Did not deactivate, there was no reward relationship!
-
-        // Unstake if stake profile exists
-        if let Some(ref stake_profile) = worker.role_stake_profile {
-            // Determine unstaking period based on who initiated deactivation
-            let unstaking_period = match exit_initiation_origin {
-                ExitInitiationOrigin::Lead => stake_profile.termination_unstaking_period,
-                ExitInitiationOrigin::Sudo => stake_profile.termination_unstaking_period,
-                ExitInitiationOrigin::Worker => stake_profile.exit_unstaking_period,
-            };
-
-            // Unstake
-            ensure_on_wrapped_error!(stake::Module::<T>::initiate_unstaking(
-                &stake_profile.stake_id,
-                unstaking_period
-            ))?;
-        }
-
-        // Unset lead if the leader is leaving.
-        let leader_worker_id = <CurrentLead<T, I>>::get();
-        if let Some(leader_worker_id) = leader_worker_id {
-            if leader_worker_id == *worker_id {
-                Self::unset_lead();
-            }
-        }
-
-        // Remove the worker from the storage.
-        WorkerById::<T, I>::remove(worker_id);
-        Self::decrease_active_worker_counter();
-
-        // Trigger the event
-        let event = match exit_initiation_origin {
-            ExitInitiationOrigin::Lead => {
-                RawEvent::TerminatedWorker(*worker_id, rationale_text.to_vec())
-            }
-            ExitInitiationOrigin::Worker => {
-                RawEvent::WorkerExited(*worker_id, rationale_text.to_vec())
-            }
-            ExitInitiationOrigin::Sudo => {
-                RawEvent::TerminatedLeader(*worker_id, rationale_text.to_vec())
-            }
-        };
-
-        Self::deposit_event(event);
-
-        Ok(())
-    }
-
-    /// Initialize working group constraints and mint.
-    pub 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);
-    }
-
-    // Set worker id as a leader id.
-    pub(crate) fn set_lead(worker_id: WorkerId<T>) {
-        // Update current lead
-        <CurrentLead<T, I>>::put(worker_id);
-
-        // Trigger an event
-        Self::deposit_event(RawEvent::LeaderSet(worker_id));
-    }
-
-    // Evict the currently set lead.
-    pub(crate) fn unset_lead() {
-        if Self::ensure_lead_is_set().is_ok() {
-            // Update current lead
-            <CurrentLead<T, I>>::kill();
-
-            Self::deposit_event(RawEvent::LeaderUnset());
-        }
-    }
-
-    // Processes successful application during the fill_opening().
-    fn fulfill_successful_applications(
-        opening: &OpeningOf<T>,
-        reward_settings: Option<RewardSettings<T>>,
-        successful_applications_info: Vec<ApplicationInfo<T>>,
-    ) -> BTreeMap<ApplicationId<T>, WorkerId<T>> {
-        let mut application_id_to_worker_id = BTreeMap::new();
-
-        successful_applications_info
-            .iter()
-            .for_each(|(successful_application, id, _)| {
-                // Create a reward relationship.
-                let reward_relationship = if let Some((mint_id, checked_policy)) =
-                    reward_settings.clone()
-                {
-                    // Create a new recipient for the new relationship.
-                    let recipient = <recurringrewards::Module<T>>::add_recipient();
-
-                    // Member must exist, since it was checked that it can enter the role.
-                    let member_profile =
-                        <membership::Module<T>>::membership(successful_application.member_id);
-
-                    // Rewards are deposited in the member's root account.
-                    let reward_destination_account = member_profile.root_account;
-
-                    // Values have been checked so this should not fail!
-                    let relationship_id = <recurringrewards::Module<T>>::add_reward_relationship(
-                        mint_id,
-                        recipient,
-                        reward_destination_account,
-                        checked_policy.amount_per_payout,
-                        checked_policy.next_payment_at_block,
-                        checked_policy.payout_interval,
-                    )
-                    .expect("Failed to create reward relationship!");
-
-                    Some(relationship_id)
-                } else {
-                    None
-                };
-
-                // Get possible stake for role
-                let application =
-                    hiring::ApplicationById::<T>::get(successful_application.hiring_application_id);
-
-                // Staking profile for worker
-                let stake_profile = if let Some(ref stake_id) = application.active_role_staking_id {
-                    Some(RoleStakeProfile::new(
-                        stake_id,
-                        &opening
-                            .policy_commitment
-                            .terminate_role_stake_unstaking_period,
-                        &opening.policy_commitment.exit_role_stake_unstaking_period,
-                    ))
-                } else {
-                    None
-                };
-
-                // Get worker id
-                let new_worker_id = <NextWorkerId<T, I>>::get();
-
-                // Construct worker
-                let worker = Worker::new(
-                    &successful_application.member_id,
-                    &successful_application.role_account_id,
-                    &reward_relationship,
-                    &stake_profile,
-                );
-
-                // Store a worker
-                <WorkerById<T, I>>::insert(new_worker_id, worker);
-                Self::increase_active_worker_counter();
-
-                // Update next worker id
-                <NextWorkerId<T, I>>::mutate(|id| *id += <WorkerId<T> as One>::one());
-
-                application_id_to_worker_id.insert(*id, new_worker_id);
-
-                // Sets a leader on successful opening when opening is for leader.
-                if matches!(opening.opening_type, OpeningType::Leader) {
-                    Self::set_lead(new_worker_id);
-                }
-            });
-
-        application_id_to_worker_id
-    }
-
-    // Increases active worker counter (saturating).
-    fn increase_active_worker_counter() {
-        let next_active_worker_count_value = Self::active_worker_count().saturating_add(1);
-        <ActiveWorkerCount<I>>::put(next_active_worker_count_value);
-    }
-
-    // Decreases active worker counter (saturating).
-    fn decrease_active_worker_counter() {
-        let next_active_worker_count_value = Self::active_worker_count().saturating_sub(1);
-        <ActiveWorkerCount<I>>::put(next_active_worker_count_value);
-    }
-}

+ 0 - 932
runtime-modules/working-group/src/tests/fixtures.rs

@@ -1,932 +0,0 @@
-use frame_support::dispatch::{DispatchError, DispatchResult};
-use frame_support::storage::{StorageMap, StorageValue};
-use frame_system::{EventRecord, Phase, RawOrigin};
-use std::collections::BTreeSet;
-
-use super::mock::{
-    Balances, Membership, System, Test, TestEvent, TestWorkingGroup, TestWorkingGroupInstance,
-};
-use crate::tests::fill_worker_position;
-use crate::types::{
-    Application, Opening, OpeningPolicyCommitment, OpeningType, RewardPolicy, RoleStakeProfile,
-    Worker,
-};
-use crate::RawEvent;
-use common::constraints::InputValidationLengthConstraint;
-
-pub struct IncreaseWorkerStakeFixture {
-    origin: RawOrigin<u64>,
-    worker_id: u64,
-    balance: u64,
-    account_id: u64,
-}
-
-impl IncreaseWorkerStakeFixture {
-    pub fn default_for_worker_id(worker_id: u64) -> Self {
-        let account_id = 1;
-        Self {
-            origin: RawOrigin::Signed(1),
-            worker_id,
-            balance: 10,
-            account_id,
-        }
-    }
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-
-    pub fn with_balance(self, balance: u64) -> Self {
-        Self { balance, ..self }
-    }
-
-    pub fn call_and_assert(&self, expected_result: DispatchResult) {
-        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 = TestWorkingGroup::increase_stake(
-            self.origin.clone().into(),
-            self.worker_id,
-            self.balance,
-        );
-
-        assert_eq!(actual_result, expected_result);
-
-        if actual_result.is_ok() {
-            let new_stake = <stake::Module<Test>>::stakes(stake_id);
-
-            // stake increased
-            assert_eq!(
-                get_stake_balance(new_stake),
-                get_stake_balance(old_stake) + self.balance
-            );
-
-            let new_balance = Balances::free_balance(&self.account_id);
-
-            // worker balance decreased
-            assert_eq!(new_balance, old_balance - self.balance,);
-        }
-    }
-}
-
-pub struct TerminateWorkerRoleFixture {
-    worker_id: u64,
-    origin: RawOrigin<u64>,
-    text: Vec<u8>,
-    constraint: InputValidationLengthConstraint,
-    slash_stake: bool,
-}
-
-impl TerminateWorkerRoleFixture {
-    pub fn default_for_worker_id(worker_id: u64) -> Self {
-        Self {
-            worker_id,
-            origin: RawOrigin::Signed(1),
-            text: b"rationale_text".to_vec(),
-            constraint: InputValidationLengthConstraint {
-                min: 1,
-                max_min_diff: 20,
-            },
-            slash_stake: false,
-        }
-    }
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-
-    pub fn with_text(self, text: Vec<u8>) -> Self {
-        Self { text, ..self }
-    }
-
-    pub fn with_slashing(self) -> Self {
-        Self {
-            slash_stake: true,
-            ..self
-        }
-    }
-
-    pub fn call_and_assert(&self, expected_result: DispatchResult) {
-        <crate::WorkerExitRationaleText<TestWorkingGroupInstance>>::put(self.constraint.clone());
-
-        let actual_result = TestWorkingGroup::terminate_role(
-            self.origin.clone().into(),
-            self.worker_id,
-            self.text.clone(),
-            self.slash_stake,
-        );
-        assert_eq!(actual_result, expected_result);
-
-        if actual_result.is_ok() {
-            if actual_result.is_ok() {
-                assert!(
-                    !<crate::WorkerById<Test, TestWorkingGroupInstance>>::contains_key(
-                        self.worker_id
-                    )
-                );
-            }
-        }
-    }
-}
-
-pub(crate) struct LeaveWorkerRoleFixture {
-    worker_id: u64,
-    origin: RawOrigin<u64>,
-}
-
-impl LeaveWorkerRoleFixture {
-    pub fn default_for_worker_id(worker_id: u64) -> Self {
-        Self {
-            worker_id,
-            origin: RawOrigin::Signed(1),
-        }
-    }
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-
-    pub fn call_and_assert(&self, expected_result: DispatchResult) {
-        let rationale_text = b"rationale_text".to_vec();
-        let actual_result = TestWorkingGroup::leave_role(
-            self.origin.clone().into(),
-            self.worker_id,
-            rationale_text.clone(),
-        );
-        assert_eq!(actual_result, expected_result);
-
-        if actual_result.is_ok() {
-            assert!(
-                !<crate::WorkerById<Test, TestWorkingGroupInstance>>::contains_key(self.worker_id)
-            );
-        }
-    }
-}
-
-pub struct UpdateWorkerRewardAmountFixture {
-    worker_id: u64,
-    amount: u64,
-    origin: RawOrigin<u64>,
-}
-
-impl UpdateWorkerRewardAmountFixture {
-    pub fn default_for_worker_id(worker_id: u64) -> Self {
-        let lead_account_id = get_current_lead_account_id();
-
-        Self {
-            worker_id,
-            amount: 120,
-            origin: RawOrigin::Signed(lead_account_id),
-        }
-    }
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-
-    pub fn call_and_assert(&self, expected_result: DispatchResult) {
-        let actual_result = TestWorkingGroup::update_reward_amount(
-            self.origin.clone().into(),
-            self.worker_id,
-            self.amount,
-        );
-
-        assert_eq!(actual_result.clone(), expected_result);
-
-        if actual_result.is_ok() {
-            let worker = TestWorkingGroup::worker_by_id(self.worker_id);
-            let relationship_id = worker.reward_relationship.unwrap();
-
-            let relationship = recurringrewards::RewardRelationships::<Test>::get(relationship_id);
-
-            assert_eq!(relationship.amount_per_payout, self.amount);
-        }
-    }
-}
-pub struct UpdateWorkerRewardAccountFixture {
-    worker_id: u64,
-    new_reward_account_id: u64,
-    origin: RawOrigin<u64>,
-}
-
-impl UpdateWorkerRewardAccountFixture {
-    pub fn default_with_ids(worker_id: u64, new_reward_account_id: u64) -> Self {
-        Self {
-            worker_id,
-            new_reward_account_id,
-            origin: RawOrigin::Signed(1),
-        }
-    }
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-
-    pub fn call_and_assert(&self, expected_result: DispatchResult) {
-        let actual_result = TestWorkingGroup::update_reward_account(
-            self.origin.clone().into(),
-            self.worker_id,
-            self.new_reward_account_id,
-        );
-
-        assert_eq!(actual_result.clone(), expected_result);
-
-        if actual_result.is_ok() {
-            let worker = TestWorkingGroup::worker_by_id(self.worker_id);
-            let relationship_id = worker.reward_relationship.unwrap();
-
-            let relationship = recurringrewards::RewardRelationships::<Test>::get(relationship_id);
-
-            assert_eq!(relationship.account, self.new_reward_account_id);
-        }
-    }
-}
-
-pub struct UpdateWorkerRoleAccountFixture {
-    worker_id: u64,
-    new_role_account_id: u64,
-    origin: RawOrigin<u64>,
-}
-
-impl UpdateWorkerRoleAccountFixture {
-    pub fn default_with_ids(worker_id: u64, new_role_account_id: u64) -> Self {
-        Self {
-            worker_id,
-            new_role_account_id,
-            origin: RawOrigin::Signed(1),
-        }
-    }
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-
-    pub fn call_and_assert(&self, expected_result: DispatchResult) {
-        let actual_result = TestWorkingGroup::update_role_account(
-            self.origin.clone().into(),
-            self.worker_id,
-            self.new_role_account_id,
-        );
-        assert_eq!(actual_result, expected_result);
-
-        if actual_result.is_ok() {
-            let worker = TestWorkingGroup::worker_by_id(self.worker_id);
-
-            assert_eq!(worker.role_account_id, self.new_role_account_id);
-        }
-    }
-}
-
-pub fn set_mint_id(mint_id: u64) {
-    <crate::Mint<Test, TestWorkingGroupInstance>>::put(mint_id);
-}
-
-pub fn create_mint() -> u64 {
-    <minting::Module<Test>>::add_mint(100, None).unwrap()
-}
-
-pub struct FillWorkerOpeningFixture {
-    origin: RawOrigin<u64>,
-    opening_id: u64,
-    successful_application_ids: BTreeSet<u64>,
-    role_account_id: u64,
-    reward_policy: Option<RewardPolicy<u64, u64>>,
-}
-
-impl FillWorkerOpeningFixture {
-    pub fn default_for_ids(opening_id: u64, application_ids: Vec<u64>) -> Self {
-        let application_ids: BTreeSet<u64> = application_ids.iter().map(|x| *x).collect();
-
-        Self {
-            origin: RawOrigin::Signed(1),
-            opening_id,
-            successful_application_ids: application_ids,
-            role_account_id: 1,
-            reward_policy: None,
-        }
-    }
-
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-
-    pub fn with_reward_policy(self, reward_policy: RewardPolicy<u64, u64>) -> Self {
-        Self {
-            reward_policy: Some(reward_policy),
-            ..self
-        }
-    }
-
-    pub fn call(&self) -> Result<u64, DispatchError> {
-        let saved_worker_next_id = TestWorkingGroup::next_worker_id();
-        TestWorkingGroup::fill_opening(
-            self.origin.clone().into(),
-            self.opening_id,
-            self.successful_application_ids.clone(),
-            self.reward_policy.clone(),
-        )?;
-
-        Ok(saved_worker_next_id)
-    }
-
-    pub fn call_and_assert(&self, expected_result: DispatchResult) -> u64 {
-        let saved_worker_next_id = TestWorkingGroup::next_worker_id();
-        let actual_result = self.call().map(|_| ());
-        assert_eq!(actual_result.clone(), expected_result);
-
-        if actual_result.is_ok() {
-            assert_eq!(TestWorkingGroup::next_worker_id(), saved_worker_next_id + 1);
-            let worker_id = saved_worker_next_id;
-
-            let opening = TestWorkingGroup::opening_by_id(self.opening_id);
-
-            let role_stake_profile = if opening
-                .policy_commitment
-                .application_staking_policy
-                .is_some()
-                || opening.policy_commitment.role_staking_policy.is_some()
-            {
-                let stake_id = 0;
-                Some(RoleStakeProfile::new(
-                    &stake_id,
-                    &opening
-                        .policy_commitment
-                        .terminate_role_stake_unstaking_period,
-                    &opening.policy_commitment.exit_role_stake_unstaking_period,
-                ))
-            } else {
-                None
-            };
-            let reward_relationship = self.reward_policy.clone().map(|_| 0);
-
-            let expected_worker = Worker {
-                member_id: 1,
-                role_account_id: self.role_account_id,
-                reward_relationship,
-                role_stake_profile,
-            };
-
-            let actual_worker = TestWorkingGroup::worker_by_id(worker_id);
-
-            assert_eq!(actual_worker, expected_worker);
-        }
-
-        saved_worker_next_id
-    }
-}
-
-pub struct BeginReviewWorkerApplicationsFixture {
-    origin: RawOrigin<u64>,
-    opening_id: u64,
-}
-
-impl BeginReviewWorkerApplicationsFixture {
-    pub fn default_for_opening_id(opening_id: u64) -> Self {
-        Self {
-            origin: RawOrigin::Signed(1),
-            opening_id,
-        }
-    }
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-    pub fn call_and_assert(&self, expected_result: DispatchResult) {
-        let actual_result =
-            TestWorkingGroup::begin_applicant_review(self.origin.clone().into(), self.opening_id);
-        assert_eq!(actual_result, expected_result);
-    }
-}
-
-pub struct TerminateApplicationFixture {
-    origin: RawOrigin<u64>,
-    worker_application_id: u64,
-}
-
-impl TerminateApplicationFixture {
-    pub fn with_signer(self, account_id: u64) -> Self {
-        Self {
-            origin: RawOrigin::Signed(account_id),
-            ..self
-        }
-    }
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-    pub fn default_for_application_id(application_id: u64) -> Self {
-        Self {
-            origin: RawOrigin::Signed(1),
-            worker_application_id: application_id,
-        }
-    }
-    pub fn call_and_assert(&self, expected_result: DispatchResult) {
-        let actual_result = TestWorkingGroup::terminate_application(
-            self.origin.clone().into(),
-            self.worker_application_id,
-        );
-        assert_eq!(actual_result.clone(), expected_result);
-    }
-}
-pub struct WithdrawApplicationFixture {
-    origin: RawOrigin<u64>,
-    worker_application_id: u64,
-}
-
-impl WithdrawApplicationFixture {
-    pub fn with_signer(self, account_id: u64) -> Self {
-        Self {
-            origin: RawOrigin::Signed(account_id),
-            ..self
-        }
-    }
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-    pub fn default_for_application_id(application_id: u64) -> Self {
-        Self {
-            origin: RawOrigin::Signed(1),
-            worker_application_id: application_id,
-        }
-    }
-    pub fn call_and_assert(&self, expected_result: DispatchResult) {
-        let actual_result = TestWorkingGroup::withdraw_application(
-            self.origin.clone().into(),
-            self.worker_application_id,
-        );
-        assert_eq!(actual_result.clone(), expected_result);
-    }
-}
-
-pub fn increase_total_balance_issuance_using_account_id(account_id: u64, balance: u64) {
-    let _ =
-        <Balances as frame_support::traits::Currency<u64>>::deposit_creating(&account_id, balance);
-}
-
-pub fn get_balance(account_id: u64) -> u64 {
-    <super::mock::Balances as frame_support::traits::Currency<u64>>::total_balance(&account_id)
-}
-
-pub fn setup_members(count: u8) {
-    let authority_account_id = 1;
-    Membership::set_screening_authority(RawOrigin::Root.into(), authority_account_id).unwrap();
-
-    for i in 0..count {
-        let account_id: u64 = i as u64;
-        let handle: [u8; 20] = [i; 20];
-        Membership::add_screened_member(
-            RawOrigin::Signed(authority_account_id).into(),
-            account_id,
-            Some(handle.to_vec()),
-            None,
-            None,
-        )
-        .unwrap();
-    }
-}
-
-pub struct ApplyOnWorkerOpeningFixture {
-    origin: RawOrigin<u64>,
-    member_id: u64,
-    worker_opening_id: u64,
-    role_account_id: u64,
-    opt_role_stake_balance: Option<u64>,
-    opt_application_stake_balance: Option<u64>,
-    human_readable_text: Vec<u8>,
-}
-
-impl ApplyOnWorkerOpeningFixture {
-    pub fn with_text(self, text: Vec<u8>) -> Self {
-        Self {
-            human_readable_text: text,
-            ..self
-        }
-    }
-
-    pub fn with_origin(self, origin: RawOrigin<u64>, member_id: u64) -> Self {
-        Self {
-            origin,
-            member_id,
-            ..self
-        }
-    }
-
-    pub fn with_role_stake(self, stake: Option<u64>) -> Self {
-        Self {
-            opt_role_stake_balance: stake,
-            ..self
-        }
-    }
-
-    pub fn with_application_stake(self, stake: u64) -> Self {
-        Self {
-            opt_application_stake_balance: Some(stake),
-            ..self
-        }
-    }
-
-    pub fn default_for_opening_id(opening_id: u64) -> Self {
-        Self {
-            origin: RawOrigin::Signed(1),
-            member_id: 1,
-            worker_opening_id: opening_id,
-            role_account_id: 1,
-            opt_role_stake_balance: None,
-            opt_application_stake_balance: None,
-            human_readable_text: b"human_text".to_vec(),
-        }
-    }
-
-    pub fn call(&self) -> Result<u64, DispatchError> {
-        let saved_application_next_id = TestWorkingGroup::next_application_id();
-        TestWorkingGroup::apply_on_opening(
-            self.origin.clone().into(),
-            self.member_id,
-            self.worker_opening_id,
-            self.role_account_id,
-            self.opt_role_stake_balance,
-            self.opt_application_stake_balance,
-            self.human_readable_text.clone(),
-        )?;
-
-        Ok(saved_application_next_id)
-    }
-    pub fn call_and_assert(&self, expected_result: DispatchResult) -> u64 {
-        let saved_application_next_id = TestWorkingGroup::next_application_id();
-
-        let actual_result = self.call().map(|_| ());
-        assert_eq!(actual_result.clone(), expected_result);
-
-        if actual_result.is_ok() {
-            assert_eq!(
-                TestWorkingGroup::next_application_id(),
-                saved_application_next_id + 1
-            );
-            let application_id = saved_application_next_id;
-
-            let actual_application = TestWorkingGroup::application_by_id(application_id);
-
-            let expected_application = Application {
-                role_account_id: self.role_account_id,
-                opening_id: self.worker_opening_id,
-                member_id: self.member_id,
-                hiring_application_id: application_id,
-            };
-
-            assert_eq!(actual_application, expected_application);
-
-            let current_opening = TestWorkingGroup::opening_by_id(self.worker_opening_id);
-            assert!(current_opening.applications.contains(&application_id));
-        }
-
-        saved_application_next_id
-    }
-}
-
-pub struct AcceptWorkerApplicationsFixture {
-    origin: RawOrigin<u64>,
-    opening_id: u64,
-}
-
-impl AcceptWorkerApplicationsFixture {
-    pub fn default_for_opening_id(opening_id: u64) -> Self {
-        Self {
-            origin: RawOrigin::Signed(1),
-            opening_id,
-        }
-    }
-
-    pub fn call_and_assert(&self, expected_result: DispatchResult) {
-        let actual_result =
-            TestWorkingGroup::accept_applications(self.origin.clone().into(), self.opening_id);
-        assert_eq!(actual_result, expected_result);
-    }
-}
-
-pub struct SetLeadFixture {
-    pub member_id: u64,
-    pub role_account_id: u64,
-    pub worker_id: u64,
-}
-impl Default for SetLeadFixture {
-    fn default() -> Self {
-        SetLeadFixture {
-            member_id: 1,
-            role_account_id: 1,
-            worker_id: 1,
-        }
-    }
-}
-
-impl SetLeadFixture {
-    pub fn unset_lead() {
-        TestWorkingGroup::unset_lead();
-    }
-
-    pub fn set_lead(self) {
-        TestWorkingGroup::set_lead(self.worker_id);
-    }
-    pub fn set_lead_with_ids(member_id: u64, role_account_id: u64, worker_id: u64) {
-        Self {
-            member_id,
-            role_account_id,
-            worker_id,
-        }
-        .set_lead();
-    }
-}
-
-pub struct HireLeadFixture {
-    setup_environment: bool,
-    stake: Option<u64>,
-    reward_policy: Option<RewardPolicy<u64, u64>>,
-}
-
-impl Default for HireLeadFixture {
-    fn default() -> Self {
-        Self {
-            setup_environment: true,
-            stake: None,
-            reward_policy: None,
-        }
-    }
-}
-impl HireLeadFixture {
-    pub fn with_stake(self, stake: u64) -> Self {
-        Self {
-            stake: Some(stake),
-            ..self
-        }
-    }
-    pub fn with_reward_policy(self, reward_policy: RewardPolicy<u64, u64>) -> Self {
-        Self {
-            reward_policy: Some(reward_policy),
-            ..self
-        }
-    }
-
-    pub fn hire_lead(self) -> u64 {
-        fill_worker_position(
-            self.reward_policy,
-            self.stake,
-            self.setup_environment,
-            OpeningType::Leader,
-            Some(b"leader".to_vec()),
-        )
-    }
-}
-
-pub fn get_worker_by_id(worker_id: u64) -> Worker<u64, u64, u64, u64, u64> {
-    TestWorkingGroup::worker_by_id(worker_id)
-}
-
-pub struct AddWorkerOpeningFixture {
-    origin: RawOrigin<u64>,
-    activate_at: hiring::ActivateOpeningAt<u64>,
-    commitment: OpeningPolicyCommitment<u64, u64>,
-    human_readable_text: Vec<u8>,
-    opening_type: OpeningType,
-}
-
-impl Default for AddWorkerOpeningFixture {
-    fn default() -> Self {
-        Self {
-            origin: RawOrigin::Signed(1),
-            activate_at: hiring::ActivateOpeningAt::CurrentBlock,
-            commitment: <OpeningPolicyCommitment<u64, u64>>::default(),
-            human_readable_text: b"human_text".to_vec(),
-            opening_type: OpeningType::Worker,
-        }
-    }
-}
-
-impl AddWorkerOpeningFixture {
-    pub fn with_policy_commitment(
-        self,
-        policy_commitment: OpeningPolicyCommitment<u64, u64>,
-    ) -> Self {
-        Self {
-            commitment: policy_commitment,
-            ..self
-        }
-    }
-
-    pub fn call_and_assert(&self, expected_result: DispatchResult) -> u64 {
-        let saved_opening_next_id = TestWorkingGroup::next_opening_id();
-        let actual_result = self.call().map(|_| ());
-
-        assert_eq!(actual_result.clone(), expected_result);
-
-        if actual_result.is_ok() {
-            assert_eq!(
-                TestWorkingGroup::next_opening_id(),
-                saved_opening_next_id + 1
-            );
-            let opening_id = saved_opening_next_id;
-
-            let actual_opening = TestWorkingGroup::opening_by_id(opening_id);
-
-            let expected_opening = Opening::<u64, u64, u64, u64> {
-                hiring_opening_id: opening_id,
-                applications: BTreeSet::new(),
-                policy_commitment: self.commitment.clone(),
-                opening_type: self.opening_type,
-            };
-
-            assert_eq!(actual_opening, expected_opening);
-        }
-
-        saved_opening_next_id
-    }
-
-    pub fn call(&self) -> Result<u64, DispatchError> {
-        let saved_opening_next_id = TestWorkingGroup::next_opening_id();
-        TestWorkingGroup::add_opening(
-            self.origin.clone().into(),
-            self.activate_at.clone(),
-            self.commitment.clone(),
-            self.human_readable_text.clone(),
-            self.opening_type,
-        )?;
-
-        Ok(saved_opening_next_id)
-    }
-
-    pub fn with_text(self, text: Vec<u8>) -> Self {
-        Self {
-            human_readable_text: text,
-            ..self
-        }
-    }
-
-    pub fn with_opening_type(self, opening_type: OpeningType) -> Self {
-        Self {
-            opening_type,
-            ..self
-        }
-    }
-
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-
-    pub fn with_activate_at(self, activate_at: hiring::ActivateOpeningAt<u64>) -> Self {
-        Self {
-            activate_at,
-            ..self
-        }
-    }
-}
-
-pub struct EventFixture;
-impl EventFixture {
-    pub fn assert_last_crate_event(
-        expected_raw_event: RawEvent<
-            u64,
-            u64,
-            u64,
-            u64,
-            std::collections::BTreeMap<u64, u64>,
-            Vec<u8>,
-            u64,
-            u64,
-            TestWorkingGroupInstance,
-        >,
-    ) {
-        let converted_event = TestEvent::working_group_TestWorkingGroupInstance(expected_raw_event);
-
-        Self::assert_last_global_event(converted_event)
-    }
-
-    pub fn assert_last_global_event(expected_event: TestEvent) {
-        let expected_event = EventRecord {
-            phase: Phase::Initialization,
-            event: expected_event,
-            topics: vec![],
-        };
-
-        assert_eq!(System::events().pop().unwrap(), expected_event);
-    }
-}
-
-pub struct DecreaseWorkerStakeFixture {
-    origin: RawOrigin<u64>,
-    worker_id: u64,
-    balance: u64,
-    account_id: u64,
-}
-
-impl DecreaseWorkerStakeFixture {
-    pub fn default_for_worker_id(worker_id: u64) -> Self {
-        let account_id = 1;
-
-        let lead_account_id = get_current_lead_account_id();
-
-        Self {
-            origin: RawOrigin::Signed(lead_account_id),
-            worker_id,
-            balance: 10,
-            account_id,
-        }
-    }
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-
-    pub fn with_balance(self, balance: u64) -> Self {
-        Self { balance, ..self }
-    }
-
-    pub fn call_and_assert(&self, expected_result: DispatchResult) {
-        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 = TestWorkingGroup::decrease_stake(
-            self.origin.clone().into(),
-            self.worker_id,
-            self.balance,
-        );
-
-        assert_eq!(actual_result, expected_result);
-
-        if actual_result.is_ok() {
-            let new_stake = <stake::Module<Test>>::stakes(stake_id);
-
-            // stake decreased
-            assert_eq!(
-                get_stake_balance(new_stake),
-                get_stake_balance(old_stake) - self.balance
-            );
-
-            let new_balance = Balances::free_balance(&self.account_id);
-
-            // worker balance increased
-            assert_eq!(new_balance, old_balance + self.balance,);
-        }
-    }
-}
-
-pub(crate) fn get_stake_balance(stake: stake::Stake<u64, u64, u64>) -> u64 {
-    if let stake::StakingStatus::Staked(stake) = stake.staking_status {
-        return stake.staked_amount;
-    }
-
-    panic!("Not staked.");
-}
-
-fn get_current_lead_account_id() -> u64 {
-    let leader_worker_id = TestWorkingGroup::current_lead();
-
-    if let Some(leader_worker_id) = leader_worker_id {
-        let leader = TestWorkingGroup::worker_by_id(leader_worker_id);
-        leader.role_account_id
-    } else {
-        0 // return invalid lead_account_id for testing
-    }
-}
-
-pub struct SlashWorkerStakeFixture {
-    origin: RawOrigin<u64>,
-    worker_id: u64,
-    balance: u64,
-    account_id: u64,
-}
-
-impl SlashWorkerStakeFixture {
-    pub fn default_for_worker_id(worker_id: u64) -> Self {
-        let account_id = 1;
-
-        let lead_account_id = get_current_lead_account_id();
-
-        Self {
-            origin: RawOrigin::Signed(lead_account_id),
-            worker_id,
-            balance: 10,
-            account_id,
-        }
-    }
-    pub fn with_origin(self, origin: RawOrigin<u64>) -> Self {
-        Self { origin, ..self }
-    }
-
-    pub fn with_balance(self, balance: u64) -> Self {
-        Self { balance, ..self }
-    }
-
-    pub fn call_and_assert(&self, expected_result: DispatchResult) {
-        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 =
-            TestWorkingGroup::slash_stake(self.origin.clone().into(), self.worker_id, self.balance);
-
-        assert_eq!(actual_result, expected_result);
-
-        if actual_result.is_ok() {
-            let new_stake = <stake::Module<Test>>::stakes(stake_id);
-
-            // stake decreased
-            assert_eq!(
-                get_stake_balance(new_stake),
-                get_stake_balance(old_stake) - self.balance
-            );
-
-            let new_balance = Balances::free_balance(&self.account_id);
-
-            // worker balance unchanged
-            assert_eq!(new_balance, old_balance,);
-        }
-    }
-}

+ 0 - 201
runtime-modules/working-group/src/tests/hiring_workflow.rs

@@ -1,201 +0,0 @@
-use frame_support::dispatch::{DispatchError, DispatchResult};
-use frame_system::RawOrigin;
-
-use crate::tests::fixtures::{
-    create_mint, increase_total_balance_issuance_using_account_id, set_mint_id, setup_members,
-    AddWorkerOpeningFixture, ApplyOnWorkerOpeningFixture, BeginReviewWorkerApplicationsFixture,
-    FillWorkerOpeningFixture, SetLeadFixture,
-};
-use crate::tests::mock::TestWorkingGroup;
-use crate::{OpeningPolicyCommitment, OpeningType, RewardPolicy};
-
-#[derive(Clone)]
-struct HiringWorkflowApplication {
-    stake: Option<u64>,
-    worker_handle: Vec<u8>,
-    origin: RawOrigin<u64>,
-    member_id: u64,
-}
-
-pub struct HiringWorkflow {
-    opening_type: OpeningType,
-    expected_result: DispatchResult,
-    role_stake: Option<u64>,
-    applications: Vec<HiringWorkflowApplication>,
-    setup_environment: bool,
-    reward_policy: Option<RewardPolicy<u64, u64>>,
-}
-
-impl Default for HiringWorkflow {
-    fn default() -> Self {
-        Self {
-            opening_type: OpeningType::Worker,
-            expected_result: Ok(()),
-            role_stake: None,
-            applications: Vec::new(),
-            setup_environment: true,
-            reward_policy: None,
-        }
-    }
-}
-
-impl HiringWorkflow {
-    pub fn expect(self, result: DispatchResult) -> Self {
-        Self {
-            expected_result: result,
-            ..self
-        }
-    }
-
-    pub fn disable_setup_environment(self) -> Self {
-        Self {
-            setup_environment: false,
-            ..self
-        }
-    }
-
-    pub fn with_setup_environment(self, setup_environment: bool) -> Self {
-        Self {
-            setup_environment,
-            ..self
-        }
-    }
-
-    pub fn with_opening_type(self, opening_type: OpeningType) -> Self {
-        Self {
-            opening_type,
-            ..self
-        }
-    }
-
-    pub fn with_role_stake(self, role_stake: Option<u64>) -> Self {
-        Self { role_stake, ..self }
-    }
-
-    pub fn with_reward_policy(self, reward_policy: Option<RewardPolicy<u64, u64>>) -> Self {
-        Self {
-            reward_policy,
-            ..self
-        }
-    }
-
-    pub fn add_default_application(self) -> Self {
-        let worker_handle = b"default worker handle".to_vec();
-
-        self.add_application(worker_handle)
-    }
-
-    pub fn add_application(self, worker_handle: Vec<u8>) -> Self {
-        self.add_application_with_origin(worker_handle, RawOrigin::Signed(1), 1)
-    }
-
-    pub fn add_application_with_origin(
-        self,
-        worker_handle: Vec<u8>,
-        origin: RawOrigin<u64>,
-        member_id: u64,
-    ) -> Self {
-        let mut applications = self.applications;
-        applications.push(HiringWorkflowApplication {
-            worker_handle,
-            stake: self.role_stake.clone(),
-            origin,
-            member_id,
-        });
-
-        Self {
-            applications,
-            ..self
-        }
-    }
-
-    fn setup_environment(&self) {
-        if matches!(self.opening_type, OpeningType::Worker) {
-            SetLeadFixture::default().set_lead();
-        }
-        increase_total_balance_issuance_using_account_id(1, 10000);
-        setup_members(4);
-        set_mint_id(create_mint());
-    }
-
-    pub fn execute(&self) -> Option<u64> {
-        if self.setup_environment {
-            self.setup_environment()
-        }
-
-        let result = self.fill_worker_position();
-
-        let check_result = result.clone().map(|_| ());
-
-        assert_eq!(check_result, self.expected_result);
-
-        result.ok()
-    }
-
-    fn fill_worker_position(&self) -> Result<u64, DispatchError> {
-        let origin = match self.opening_type {
-            OpeningType::Leader => RawOrigin::Root,
-            OpeningType::Worker => {
-                let leader_worker_id = TestWorkingGroup::current_lead().unwrap();
-                let leader = TestWorkingGroup::worker_by_id(leader_worker_id);
-                let lead_account_id = leader.role_account_id;
-
-                RawOrigin::Signed(lead_account_id)
-            }
-        };
-
-        // create the opening
-        let mut add_worker_opening_fixture = AddWorkerOpeningFixture::default()
-            .with_opening_type(self.opening_type)
-            .with_origin(origin.clone());
-
-        if let Some(stake) = self.role_stake.clone() {
-            add_worker_opening_fixture =
-                add_worker_opening_fixture.with_policy_commitment(OpeningPolicyCommitment {
-                    role_staking_policy: Some(hiring::StakingPolicy {
-                        amount: stake,
-                        amount_mode: hiring::StakingAmountLimitMode::AtLeast,
-                        crowded_out_unstaking_period_length: None,
-                        review_period_expired_unstaking_period_length: None,
-                    }),
-                    ..OpeningPolicyCommitment::default()
-                });
-        }
-
-        let opening_id = add_worker_opening_fixture.call()?;
-
-        // Fill applications.
-        let mut application_ids = Vec::new();
-        for application in self.applications.clone() {
-            let apply_on_worker_opening_fixture =
-                ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id)
-                    .with_text(application.worker_handle)
-                    .with_origin(application.origin, application.member_id)
-                    .with_role_stake(self.role_stake);
-
-            let application_id = apply_on_worker_opening_fixture.call()?;
-            application_ids.push(application_id);
-        }
-
-        // begin application review
-
-        let begin_review_worker_applications_fixture =
-            BeginReviewWorkerApplicationsFixture::default_for_opening_id(opening_id)
-                .with_origin(origin.clone());
-        begin_review_worker_applications_fixture.call_and_assert(Ok(()));
-
-        // fill opening
-        let mut fill_worker_opening_fixture =
-            FillWorkerOpeningFixture::default_for_ids(opening_id, application_ids)
-                .with_origin(origin.clone());
-
-        if let Some(reward_policy) = self.reward_policy.clone() {
-            fill_worker_opening_fixture =
-                fill_worker_opening_fixture.with_reward_policy(reward_policy);
-        }
-
-        let worker_id = fill_worker_opening_fixture.call()?;
-
-        Ok(worker_id)
-    }
-}

+ 0 - 237
runtime-modules/working-group/src/tests/mock.rs

@@ -1,237 +0,0 @@
-use frame_support::storage::StorageMap;
-use frame_support::traits::{OnFinalize, OnInitialize};
-use frame_support::{impl_outer_event, impl_outer_origin, parameter_types};
-use frame_system;
-use sp_core::H256;
-use sp_runtime::{
-    testing::Header,
-    traits::{BlakeTwo256, IdentityLookup},
-    Perbill,
-};
-use std::marker::PhantomData;
-
-use crate::{BalanceOf, Module, NegativeImbalance, Trait};
-use common::constraints::InputValidationLengthConstraint;
-
-impl_outer_origin! {
-    pub enum Origin for Test {}
-}
-
-mod working_group {
-    pub use super::TestWorkingGroupInstance;
-    pub use crate::Event;
-}
-
-mod membership_mod {
-    pub use membership::Event;
-}
-
-impl_outer_event! {
-    pub enum TestEvent for Test {
-        balances<T>,
-        working_group TestWorkingGroupInstance <T>,
-        membership_mod<T>,
-        frame_system<T>,
-    }
-}
-
-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;
-    pub const StakePoolId: [u8; 8] = *b"joystake";
-    pub const ExistentialDeposit: u32 = 0;
-}
-
-// Workaround for https://github.com/rust-lang/rust/issues/26925 - remove when sorted.
-#[derive(Clone, PartialEq, Eq, Debug)]
-pub struct Test;
-
-impl frame_system::Trait for Test {
-    type BaseCallFilter = ();
-    type Origin = Origin;
-    type Call = ();
-    type Index = u64;
-    type BlockNumber = u64;
-    type Hash = H256;
-    type Hashing = BlakeTwo256;
-    type AccountId = u64;
-    type Lookup = IdentityLookup<Self::AccountId>;
-    type Header = Header;
-    type Event = TestEvent;
-    type BlockHashCount = BlockHashCount;
-    type MaximumBlockWeight = MaximumBlockWeight;
-    type DbWeight = ();
-    type BlockExecutionWeight = ();
-    type ExtrinsicBaseWeight = ();
-    type MaximumExtrinsicWeight = ();
-    type MaximumBlockLength = MaximumBlockLength;
-    type AvailableBlockRatio = AvailableBlockRatio;
-    type Version = ();
-    type PalletInfo = ();
-    type AccountData = balances::AccountData<u64>;
-    type OnNewAccount = ();
-    type OnKilledAccount = ();
-    type SystemWeightInfo = ();
-}
-
-impl hiring::Trait for Test {
-    type OpeningId = u64;
-    type ApplicationId = u64;
-    type ApplicationDeactivatedHandler = ();
-    type StakeHandlerProvider = hiring::Module<Self>;
-}
-
-impl minting::Trait for Test {
-    type Currency = Balances;
-    type MintId = u64;
-}
-
-impl stake::Trait for Test {
-    type Currency = Balances;
-    type StakePoolId = StakePoolId;
-    type StakingEventsHandler = StakingEventsHandler<Test>;
-    type StakeId = u64;
-    type SlashId = u64;
-}
-
-impl membership::Trait for Test {
-    type Event = TestEvent;
-    type MemberId = u64;
-    type PaidTermId = u64;
-    type SubscriptionId = u64;
-    type ActorId = u64;
-}
-
-impl common::currency::GovernanceCurrency for Test {
-    type Currency = Balances;
-}
-
-impl pallet_timestamp::Trait for Test {
-    type Moment = u64;
-    type OnTimestampSet = ();
-    type MinimumPeriod = MinimumPeriod;
-    type WeightInfo = ();
-}
-
-impl balances::Trait for Test {
-    type Balance = u64;
-    type DustRemoval = ();
-    type Event = TestEvent;
-    type ExistentialDeposit = ExistentialDeposit;
-    type AccountStore = System;
-    type WeightInfo = ();
-    type MaxLocks = ();
-}
-
-impl recurringrewards::Trait for Test {
-    type PayoutStatusHandler = ();
-    type RecipientId = u64;
-    type RewardRelationshipId = u64;
-}
-
-pub type Balances = balances::Module<Test>;
-pub type System = frame_system::Module<Test>;
-
-parameter_types! {
-    pub const MaxWorkerNumberLimit: u32 = 3;
-}
-
-impl Trait<TestWorkingGroupInstance> for Test {
-    type Event = TestEvent;
-    type MaxWorkerNumberLimit = MaxWorkerNumberLimit;
-}
-
-pub type Membership = membership::Module<Test>;
-
-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() -> sp_io::TestExternalities {
-    let mut t = frame_system::GenesisConfig::default()
-        .build_storage::<Test>()
-        .unwrap();
-
-    crate::GenesisConfig::<Test, TestWorkingGroupInstance> {
-        phantom: Default::default(),
-        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()
-}
-
-pub struct StakingEventsHandler<T> {
-    pub marker: PhantomData<T>,
-}
-
-impl<T: stake::Trait + crate::Trait<TestWorkingGroupInstance>> stake::StakingEventsHandler<T>
-    for StakingEventsHandler<T>
-{
-    /// Unstake remaining sum back to the source_account_id
-    fn unstaked(
-        stake_id: &<T as stake::Trait>::StakeId,
-        _unstaked_amount: BalanceOf<T>,
-        remaining_imbalance: NegativeImbalance<T>,
-    ) -> NegativeImbalance<T> {
-        // Stake not related to a staked role managed by the hiring module.
-        if !hiring::ApplicationIdByStakingId::<T>::contains_key(*stake_id) {
-            return remaining_imbalance;
-        }
-
-        let hiring_application_id = hiring::ApplicationIdByStakingId::<T>::get(*stake_id);
-
-        if crate::MemberIdByHiringApplicationId::<T, TestWorkingGroupInstance>::contains_key(
-            hiring_application_id,
-        ) {
-            return <crate::Module<T, TestWorkingGroupInstance>>::refund_working_group_stake(
-                *stake_id,
-                remaining_imbalance,
-            );
-        }
-
-        remaining_imbalance
-    }
-
-    /// Empty handler for slashing
-    fn slashed(
-        _: &<T as stake::Trait>::StakeId,
-        _: Option<<T as stake::Trait>::SlashId>,
-        _: BalanceOf<T>,
-        _: BalanceOf<T>,
-        remaining_imbalance: NegativeImbalance<T>,
-    ) -> NegativeImbalance<T> {
-        remaining_imbalance
-    }
-}
-
-// Recommendation from Parity on testing on_finalize
-// https://substrate.dev/docs/en/next/development/module/tests
-pub fn run_to_block(n: u64) {
-    while System::block_number() < n {
-        <System as OnFinalize<u64>>::on_finalize(System::block_number());
-        <TestWorkingGroup as OnFinalize<u64>>::on_finalize(System::block_number());
-        System::set_block_number(System::block_number() + 1);
-        <System as OnInitialize<u64>>::on_initialize(System::block_number());
-        <TestWorkingGroup as OnInitialize<u64>>::on_initialize(System::block_number());
-    }
-}

+ 0 - 2354
runtime-modules/working-group/src/tests/mod.rs

@@ -1,2354 +0,0 @@
-mod fixtures;
-mod hiring_workflow;
-mod mock;
-
-use frame_support::dispatch::DispatchError;
-use frame_support::storage::{StorageMap, StorageValue};
-use frame_system::RawOrigin;
-use std::collections::BTreeMap;
-
-use crate::tests::hiring_workflow::HiringWorkflow;
-use crate::types::{OpeningPolicyCommitment, OpeningType, RewardPolicy};
-use crate::{Error, RawEvent, Worker};
-use common::constraints::InputValidationLengthConstraint;
-use fixtures::*;
-use mock::{
-    build_test_externalities, run_to_block, Test, TestWorkingGroup, TestWorkingGroupInstance,
-    WORKING_GROUP_CONSTRAINT_DIFF, WORKING_GROUP_CONSTRAINT_MIN, WORKING_GROUP_MINT_CAPACITY,
-};
-
-#[test]
-fn hire_lead_succeeds() {
-    build_test_externalities().execute_with(|| {
-        // Ensure that lead is default
-        assert_eq!(TestWorkingGroup::current_lead(), None);
-
-        HireLeadFixture::default().hire_lead();
-
-        assert!(TestWorkingGroup::current_lead().is_some());
-    });
-}
-
-#[test]
-fn hire_lead_fails_with_existing_lead() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let hiring_workflow = HiringWorkflow::default()
-            .disable_setup_environment()
-            .with_opening_type(OpeningType::Leader)
-            .add_application(b"leader_handle".to_vec())
-            .expect(Err(
-                Error::<Test, TestWorkingGroupInstance>::CannotHireLeaderWhenLeaderExists.into(),
-            ));
-
-        hiring_workflow.execute();
-    });
-}
-
-#[test]
-fn hire_lead_fails_multiple_applications() {
-    build_test_externalities().execute_with(|| {
-        let hiring_workflow = HiringWorkflow::default()
-            .with_opening_type(OpeningType::Leader)
-            .add_application_with_origin(b"leader_handle".to_vec(), RawOrigin::Signed(1), 1)
-            .add_application_with_origin(b"leader_handle2".to_vec(), RawOrigin::Signed(2), 2)
-            .expect(Err(
-                Error::<Test, TestWorkingGroupInstance>::CannotHireMultipleLeaders.into(),
-            ));
-
-        hiring_workflow.execute();
-    });
-}
-
-#[test]
-fn add_opening_fails_with_incorrect_unstaking_periods() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                fill_opening_failed_applicant_role_stake_unstaking_period: Some(0),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::FillOpeningFailedApplicantRoleStakeUnstakingPeriodIsZero.into(),
-        ));
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                fill_opening_failed_applicant_application_stake_unstaking_period: Some(0),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::FillOpeningFailedApplicantApplicationStakeUnstakingPeriodIsZero.into(),
-        ));
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                fill_opening_successful_applicant_application_stake_unstaking_period: Some(0),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::FillOpeningSuccessfulApplicantApplicationStakeUnstakingPeriodIsZero.into(),
-        ));
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                exit_role_stake_unstaking_period: Some(0),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture.call_and_assert(Err(Error::<Test, TestWorkingGroupInstance>::ExitRoleStakeUnstakingPeriodIsZero.into()));
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                exit_role_application_stake_unstaking_period: Some(0),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture
-            .call_and_assert(Err(Error::<Test, TestWorkingGroupInstance>::ExitRoleApplicationStakeUnstakingPeriodIsZero.into()));
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                terminate_role_stake_unstaking_period: Some(0),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture.call_and_assert(Err(Error::<Test, TestWorkingGroupInstance>::TerminateRoleStakeUnstakingPeriodIsZero.into()));
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                terminate_application_stake_unstaking_period: Some(0),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture
-            .call_and_assert(Err(Error::<Test, TestWorkingGroupInstance>::TerminateApplicationStakeUnstakingPeriodIsZero.into()));
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                role_staking_policy: Some(hiring::StakingPolicy {
-                    crowded_out_unstaking_period_length: Some(0),
-                    ..Default::default()
-                }),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture
-            .call_and_assert(Err(Error::<Test, TestWorkingGroupInstance>::RoleStakingPolicyCrowdedOutUnstakingPeriodIsZero.into()));
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                role_staking_policy: Some(hiring::StakingPolicy {
-                    review_period_expired_unstaking_period_length: Some(0),
-                    ..Default::default()
-                }),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::RoleStakingPolicyReviewPeriodUnstakingPeriodIsZero.into(),
-        ));
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                application_staking_policy: Some(hiring::StakingPolicy {
-                    crowded_out_unstaking_period_length: Some(0),
-                    ..Default::default()
-                }),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::ApplicationStakingPolicyCrowdedOutUnstakingPeriodIsZero.into(),
-        ));
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                application_staking_policy: Some(hiring::StakingPolicy {
-                    review_period_expired_unstaking_period_length: Some(0),
-                    ..Default::default()
-                }),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::ApplicationStakingPolicyReviewPeriodUnstakingPeriodIsZero.into(),
-        ));
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                application_rationing_policy: Some(hiring::ApplicationRationingPolicy {
-                    max_active_applicants: 0,
-                }),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::ApplicationRationingPolicyMaxActiveApplicantsIsZero.into(),
-        ));
-    });
-}
-
-#[test]
-fn add_opening_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::OpeningAdded(opening_id));
-    });
-}
-
-#[test]
-fn add_leader_opening_fails_with_incorrect_origin_for_opening_type() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_opening_type(OpeningType::Leader);
-
-        add_opening_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn add_leader_opening_succeeds() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default()
-            .with_opening_type(OpeningType::Leader)
-            .with_origin(RawOrigin::Root);
-
-        add_opening_fixture.call_and_assert(Ok(()));
-    });
-}
-
-#[test]
-fn add_opening_fails_with_lead_is_not_set() {
-    build_test_externalities().execute_with(|| {
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-
-        add_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::CurrentLeadNotSet.into(),
-        ));
-    });
-}
-
-#[test]
-fn add_opening_fails_with_invalid_human_readable_text() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        <crate::OpeningHumanReadableText<TestWorkingGroupInstance>>::put(
-            InputValidationLengthConstraint {
-                min: 1,
-                max_min_diff: 5,
-            },
-        );
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default().with_text(Vec::new());
-
-        add_opening_fixture.call_and_assert(Err(DispatchError::Other("OpeningTextTooShort")));
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_text(b"Long text".to_vec());
-
-        add_opening_fixture.call_and_assert(Err(DispatchError::Other("OpeningTextTooLong")));
-    });
-}
-
-#[test]
-fn add_opening_fails_with_hiring_error() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default()
-            .with_activate_at(hiring::ActivateOpeningAt::ExactBlock(0));
-
-        add_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::AddWorkerOpeningActivatesInThePast.into(),
-        ));
-    });
-}
-
-#[test]
-fn accept_applications_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default()
-            .with_activate_at(hiring::ActivateOpeningAt::ExactBlock(5));
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let accept_applications_fixture =
-            AcceptWorkerApplicationsFixture::default_for_opening_id(opening_id);
-        accept_applications_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::AcceptedApplications(opening_id));
-    });
-}
-
-#[test]
-fn accept_applications_fails_for_invalid_opening_type() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default()
-            .with_origin(RawOrigin::Root)
-            .with_opening_type(OpeningType::Leader)
-            .with_activate_at(hiring::ActivateOpeningAt::ExactBlock(5));
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let accept_applications_fixture =
-            AcceptWorkerApplicationsFixture::default_for_opening_id(opening_id);
-        accept_applications_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn accept_applications_fails_with_hiring_error() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let accept_applications_fixture =
-            AcceptWorkerApplicationsFixture::default_for_opening_id(opening_id);
-        accept_applications_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::AcceptWorkerApplicationsOpeningIsNotWaitingToBegin.into(),
-        ));
-    });
-}
-
-#[test]
-fn accept_applications_fails_with_not_lead() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        SetLeadFixture::set_lead_with_ids(2, 2, 2);
-
-        let accept_applications_fixture =
-            AcceptWorkerApplicationsFixture::default_for_opening_id(opening_id);
-        accept_applications_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::IsNotLeadAccount.into(),
-        ));
-    });
-}
-
-#[test]
-fn accept_applications_fails_with_no_opening() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let opening_id = 55; // random opening id
-
-        let accept_applications_fixture =
-            AcceptWorkerApplicationsFixture::default_for_opening_id(opening_id);
-        accept_applications_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::OpeningDoesNotExist.into(),
-        ));
-    });
-}
-
-#[test]
-fn apply_on_opening_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::AppliedOnOpening(
-            opening_id,
-            application_id,
-        ));
-    });
-}
-
-#[test]
-fn apply_on_opening_fails_with_no_opening() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let opening_id = 123; // random opening id
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        apply_on_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::OpeningDoesNotExist.into(),
-        ));
-    });
-}
-
-#[test]
-fn apply_on_opening_fails_with_not_set_members() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id)
-                .with_origin(RawOrigin::Signed(55), 55);
-        apply_on_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::OriginIsNeitherMemberControllerOrRoot.into(),
-        ));
-    });
-}
-
-#[test]
-fn apply_on_opening_fails_with_hiring_error() {
-    build_test_externalities().execute_with(|| {
-        increase_total_balance_issuance_using_account_id(1, 500000);
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id)
-                .with_application_stake(100);
-        apply_on_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::AddWorkerOpeningStakeProvidedWhenRedundant
-                .into(),
-        ));
-    });
-}
-
-#[test]
-fn apply_on_opening_fails_with_invalid_application_stake() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let stake = 100;
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                application_staking_policy: Some(hiring::StakingPolicy {
-                    amount: stake,
-                    ..hiring::StakingPolicy::default()
-                }),
-                ..OpeningPolicyCommitment::default()
-            });
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id)
-                .with_origin(RawOrigin::Signed(2), 2)
-                .with_application_stake(stake);
-        apply_on_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::InsufficientBalanceToApply.into(),
-        ));
-    });
-}
-
-#[test]
-fn add_opening_fails_with_invalid_zero_application_stake() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let zero_stake = 0;
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                application_staking_policy: Some(hiring::StakingPolicy {
-                    amount: zero_stake,
-                    amount_mode: hiring::StakingAmountLimitMode::AtLeast,
-                    ..hiring::StakingPolicy::default()
-                }),
-                ..OpeningPolicyCommitment::default()
-            });
-        add_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::AddWorkerOpeningApplicationStakeCannotBeZero
-                .into(),
-        ));
-    });
-}
-
-#[test]
-fn apply_on_opening_fails_with_invalid_role_stake() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let stake = 100;
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                role_staking_policy: Some(hiring::StakingPolicy {
-                    amount: stake,
-                    ..hiring::StakingPolicy::default()
-                }),
-                ..OpeningPolicyCommitment::default()
-            });
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id)
-                .with_role_stake(Some(stake))
-                .with_origin(RawOrigin::Signed(2), 2);
-        apply_on_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::InsufficientBalanceToApply.into(),
-        ));
-    });
-}
-
-#[test]
-fn apply_on_opening_fails_with_invalid_text() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        <crate::WorkerApplicationHumanReadableText<TestWorkingGroupInstance>>::put(
-            InputValidationLengthConstraint {
-                min: 1,
-                max_min_diff: 5,
-            },
-        );
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id).with_text(Vec::new());
-        apply_on_opening_fixture
-            .call_and_assert(Err(DispatchError::Other("WorkerApplicationTextTooShort")));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id)
-                .with_text(b"Long text".to_vec());
-        apply_on_opening_fixture
-            .call_and_assert(Err(DispatchError::Other("WorkerApplicationTextTooLong")));
-    });
-}
-
-#[test]
-fn apply_on_opening_fails_with_already_active_application() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        apply_on_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::MemberHasActiveApplicationOnOpening.into(),
-        ));
-    });
-}
-
-#[test]
-fn withdraw_worker_application_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        let withdraw_application_fixture =
-            WithdrawApplicationFixture::default_for_application_id(application_id);
-        withdraw_application_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::ApplicationWithdrawn(application_id));
-    });
-}
-
-#[test]
-fn withdraw_worker_application_fails_invalid_application_id() {
-    build_test_externalities().execute_with(|| {
-        let invalid_application_id = 6;
-
-        let withdraw_application_fixture =
-            WithdrawApplicationFixture::default_for_application_id(invalid_application_id);
-        withdraw_application_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::WorkerApplicationDoesNotExist.into(),
-        ));
-    });
-}
-
-#[test]
-fn withdraw_worker_application_fails_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        let withdraw_application_fixture =
-            WithdrawApplicationFixture::default_for_application_id(application_id)
-                .with_origin(RawOrigin::None);
-        withdraw_application_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn withdraw_worker_application_fails_with_invalid_application_author() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        let invalid_author_account_id = 55;
-        let withdraw_application_fixture =
-            WithdrawApplicationFixture::default_for_application_id(application_id)
-                .with_signer(invalid_author_account_id);
-        withdraw_application_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::OriginIsNotApplicant.into(),
-        ));
-    });
-}
-
-#[test]
-fn withdraw_worker_application_fails_with_hiring_error() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        let withdraw_application_fixture =
-            WithdrawApplicationFixture::default_for_application_id(application_id);
-        withdraw_application_fixture.call_and_assert(Ok(()));
-        withdraw_application_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::WithdrawWorkerApplicationApplicationNotActive
-                .into(),
-        ));
-    });
-}
-
-#[test]
-fn terminate_worker_application_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        let terminate_application_fixture =
-            TerminateApplicationFixture::default_for_application_id(application_id);
-        terminate_application_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::ApplicationTerminated(application_id));
-    });
-}
-
-#[test]
-fn terminate_worker_application_fails_with_invalid_application_author() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        let invalid_author_account_id = 55;
-        let terminate_application_fixture =
-            TerminateApplicationFixture::default_for_application_id(application_id)
-                .with_signer(invalid_author_account_id);
-        terminate_application_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::IsNotLeadAccount.into(),
-        ));
-    });
-}
-
-#[test]
-fn terminate_worker_application_fails_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        let terminate_application_fixture =
-            TerminateApplicationFixture::default_for_application_id(application_id)
-                .with_origin(RawOrigin::None);
-        terminate_application_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn terminate_worker_application_fails_invalid_application_id() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let invalid_application_id = 6;
-
-        let terminate_application_fixture =
-            TerminateApplicationFixture::default_for_application_id(invalid_application_id);
-        terminate_application_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::WorkerApplicationDoesNotExist.into(),
-        ));
-    });
-}
-
-#[test]
-fn terminate_worker_application_fails_with_hiring_error() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        let terminate_application_fixture =
-            TerminateApplicationFixture::default_for_application_id(application_id);
-        terminate_application_fixture.call_and_assert(Ok(()));
-        terminate_application_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::WithdrawWorkerApplicationApplicationNotActive
-                .into(),
-        ));
-    });
-}
-
-#[test]
-fn begin_review_worker_applications_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let begin_review_worker_applications_fixture =
-            BeginReviewWorkerApplicationsFixture::default_for_opening_id(opening_id);
-        begin_review_worker_applications_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::BeganApplicationReview(opening_id));
-    });
-}
-
-#[test]
-fn begin_review_worker_applications_fails_with_invalid_origin_for_opening_type() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default()
-            .with_origin(RawOrigin::Root)
-            .with_opening_type(OpeningType::Leader);
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let begin_review_worker_applications_fixture =
-            BeginReviewWorkerApplicationsFixture::default_for_opening_id(opening_id);
-        begin_review_worker_applications_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn begin_review_worker_applications_fails_with_not_a_lead() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        SetLeadFixture::set_lead_with_ids(2, 2, 2);
-
-        let begin_review_worker_applications_fixture =
-            BeginReviewWorkerApplicationsFixture::default_for_opening_id(opening_id);
-        begin_review_worker_applications_fixture.call_and_assert(Err(Error::<
-            Test,
-            TestWorkingGroupInstance,
-        >::IsNotLeadAccount
-            .into()));
-    });
-}
-
-#[test]
-fn begin_review_worker_applications_fails_with_invalid_opening() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let invalid_opening_id = 6;
-
-        let begin_review_worker_applications_fixture =
-            BeginReviewWorkerApplicationsFixture::default_for_opening_id(invalid_opening_id);
-        begin_review_worker_applications_fixture.call_and_assert(Err(Error::<
-            Test,
-            TestWorkingGroupInstance,
-        >::OpeningDoesNotExist
-            .into()));
-    });
-}
-
-#[test]
-fn begin_review_worker_applications_with_hiring_error() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let begin_review_worker_applications_fixture =
-            BeginReviewWorkerApplicationsFixture::default_for_opening_id(opening_id);
-        begin_review_worker_applications_fixture.call_and_assert(Ok(()));
-        begin_review_worker_applications_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::BeginWorkerApplicantReviewOpeningOpeningIsNotWaitingToBegin.into(),
-        ));
-    });
-}
-
-#[test]
-fn begin_review_worker_applications_fails_with_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let begin_review_worker_applications_fixture =
-            BeginReviewWorkerApplicationsFixture::default_for_opening_id(opening_id)
-                .with_origin(RawOrigin::None);
-        begin_review_worker_applications_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn fill_opening_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        HireLeadFixture::default().hire_lead();
-        increase_total_balance_issuance_using_account_id(1, 10000);
-
-        let add_opening_fixture =
-            AddWorkerOpeningFixture::default().with_policy_commitment(OpeningPolicyCommitment {
-                role_staking_policy: Some(hiring::StakingPolicy {
-                    amount: 10,
-                    amount_mode: hiring::StakingAmountLimitMode::AtLeast,
-                    crowded_out_unstaking_period_length: None,
-                    review_period_expired_unstaking_period_length: None,
-                }),
-                ..OpeningPolicyCommitment::default()
-            });
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id)
-                .with_role_stake(Some(10));
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        let begin_review_worker_applications_fixture =
-            BeginReviewWorkerApplicationsFixture::default_for_opening_id(opening_id);
-        begin_review_worker_applications_fixture.call_and_assert(Ok(()));
-
-        let mint_id = create_mint();
-        set_mint_id(mint_id);
-
-        let fill_opening_fixture =
-            FillWorkerOpeningFixture::default_for_ids(opening_id, vec![application_id])
-                .with_reward_policy(RewardPolicy {
-                    amount_per_payout: 1000,
-                    next_payment_at_block: 20,
-                    payout_interval: None,
-                });
-        let worker_id = fill_opening_fixture.call_and_assert(Ok(()));
-
-        let mut worker_application_dictionary = BTreeMap::new();
-        worker_application_dictionary.insert(application_id, worker_id);
-
-        EventFixture::assert_last_crate_event(RawEvent::OpeningFilled(
-            opening_id,
-            worker_application_dictionary,
-        ));
-    });
-}
-
-#[test]
-fn fill_opening_fails_with_invalid_origin_for_opening_type() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-        increase_total_balance_issuance_using_account_id(1, 10000);
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default()
-            .with_policy_commitment(OpeningPolicyCommitment {
-                role_staking_policy: Some(hiring::StakingPolicy {
-                    amount: 10,
-                    amount_mode: hiring::StakingAmountLimitMode::AtLeast,
-                    crowded_out_unstaking_period_length: None,
-                    review_period_expired_unstaking_period_length: None,
-                }),
-                ..OpeningPolicyCommitment::default()
-            })
-            .with_opening_type(OpeningType::Leader)
-            .with_origin(RawOrigin::Root);
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id)
-                .with_role_stake(Some(10));
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        let begin_review_worker_applications_fixture =
-            BeginReviewWorkerApplicationsFixture::default_for_opening_id(opening_id)
-                .with_origin(RawOrigin::Root);
-        begin_review_worker_applications_fixture.call_and_assert(Ok(()));
-
-        set_mint_id(create_mint());
-
-        let fill_opening_fixture =
-            FillWorkerOpeningFixture::default_for_ids(opening_id, vec![application_id])
-                .with_reward_policy(RewardPolicy {
-                    amount_per_payout: 1000,
-                    next_payment_at_block: 20,
-                    payout_interval: None,
-                });
-        fill_opening_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn fill_opening_fails_with_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let fill_opening_fixture =
-            FillWorkerOpeningFixture::default_for_ids(opening_id, Vec::new())
-                .with_origin(RawOrigin::None);
-        fill_opening_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn fill_opening_fails_with_not_a_lead() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        SetLeadFixture::set_lead_with_ids(2, 2, 2);
-
-        let fill_opening_fixture =
-            FillWorkerOpeningFixture::default_for_ids(opening_id, Vec::new());
-        fill_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::IsNotLeadAccount.into(),
-        ));
-    });
-}
-
-#[test]
-fn fill_opening_fails_with_invalid_opening() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let invalid_opening_id = 6;
-
-        let fill_opening_fixture =
-            FillWorkerOpeningFixture::default_for_ids(invalid_opening_id, Vec::new());
-        fill_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::OpeningDoesNotExist.into(),
-        ));
-    });
-}
-
-#[test]
-fn fill_opening_fails_with_invalid_application_list() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        let begin_review_worker_applications_fixture =
-            BeginReviewWorkerApplicationsFixture::default_for_opening_id(opening_id);
-        begin_review_worker_applications_fixture.call_and_assert(Ok(()));
-
-        let invalid_application_id = 66;
-        let fill_opening_fixture = FillWorkerOpeningFixture::default_for_ids(
-            opening_id,
-            vec![application_id, invalid_application_id],
-        );
-        fill_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::SuccessfulWorkerApplicationDoesNotExist.into(),
-        ));
-    });
-}
-
-#[test]
-fn fill_opening_fails_with_invalid_application_with_hiring_error() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let fill_opening_fixture =
-            FillWorkerOpeningFixture::default_for_ids(opening_id, Vec::new());
-        fill_opening_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::FullWorkerOpeningOpeningNotInReviewPeriodStage
-                .into(),
-        ));
-    });
-}
-
-#[test]
-fn fill_opening_fails_with_invalid_reward_policy() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let add_opening_fixture = AddWorkerOpeningFixture::default();
-        let opening_id = add_opening_fixture.call_and_assert(Ok(()));
-
-        let apply_on_opening_fixture =
-            ApplyOnWorkerOpeningFixture::default_for_opening_id(opening_id);
-        let application_id = apply_on_opening_fixture.call_and_assert(Ok(()));
-
-        let begin_review_worker_applications_fixture =
-            BeginReviewWorkerApplicationsFixture::default_for_opening_id(opening_id);
-        begin_review_worker_applications_fixture.call_and_assert(Ok(()));
-
-        let fill_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_opening_fixture
-    });
-}
-
-#[test]
-fn update_worker_role_account_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        let new_account_id = 10;
-        let worker_id = fill_default_worker_position();
-
-        let update_worker_account_fixture =
-            UpdateWorkerRoleAccountFixture::default_with_ids(worker_id, new_account_id);
-
-        update_worker_account_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::WorkerRoleAccountUpdated(
-            worker_id,
-            new_account_id,
-        ));
-    });
-}
-
-#[test]
-fn update_worker_role_account_by_leader_succeeds() {
-    build_test_externalities().execute_with(|| {
-        let new_account_id = 10;
-        let worker_id = HireLeadFixture::default().hire_lead();
-
-        let old_lead = TestWorkingGroup::worker_by_id(worker_id);
-
-        let update_worker_account_fixture =
-            UpdateWorkerRoleAccountFixture::default_with_ids(worker_id, new_account_id);
-
-        update_worker_account_fixture.call_and_assert(Ok(()));
-
-        let new_lead = TestWorkingGroup::worker_by_id(worker_id);
-
-        assert_eq!(
-            new_lead,
-            Worker {
-                role_account_id: new_account_id,
-                ..old_lead
-            }
-        );
-    });
-}
-
-#[test]
-fn update_worker_role_account_fails_with_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_default_worker_position();
-        let update_worker_account_fixture =
-            UpdateWorkerRoleAccountFixture::default_with_ids(worker_id, 1)
-                .with_origin(RawOrigin::None);
-
-        update_worker_account_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::MembershipUnsignedOrigin.into(),
-        ));
-    });
-}
-
-#[test]
-fn update_worker_reward_account_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        let worker_id = fill_default_worker_position();
-
-        let new_role_account = 22;
-        let update_worker_account_fixture =
-            UpdateWorkerRewardAccountFixture::default_with_ids(worker_id, new_role_account);
-
-        update_worker_account_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::WorkerRewardAccountUpdated(
-            worker_id,
-            new_role_account,
-        ));
-    });
-}
-
-#[test]
-fn update_worker_reward_account_succeeds_for_leader() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = HireLeadFixture::default()
-            .with_reward_policy(RewardPolicy {
-                amount_per_payout: 1000,
-                next_payment_at_block: 20,
-                payout_interval: None,
-            })
-            .hire_lead();
-
-        let new_reward_account = 22;
-        let update_worker_account_fixture =
-            UpdateWorkerRewardAccountFixture::default_with_ids(worker_id, new_reward_account);
-
-        update_worker_account_fixture.call_and_assert(Ok(()));
-    });
-}
-
-#[test]
-fn update_worker_reward_account_fails_with_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        let update_worker_account_fixture =
-            UpdateWorkerRewardAccountFixture::default_with_ids(1, 1).with_origin(RawOrigin::None);
-
-        update_worker_account_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn update_worker_reward_account_fails_with_invalid_origin_signed_account() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_default_worker_position();
-        let worker = get_worker_by_id(worker_id);
-
-        let invalid_role_account = 23333;
-        let update_worker_account_fixture =
-            UpdateWorkerRewardAccountFixture::default_with_ids(worker_id, worker.role_account_id)
-                .with_origin(RawOrigin::Signed(invalid_role_account));
-
-        update_worker_account_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::SignerIsNotWorkerRoleAccount.into(),
-        ));
-    });
-}
-
-#[test]
-fn update_worker_reward_account_fails_with_invalid_worker_id() {
-    build_test_externalities().execute_with(|| {
-        let invalid_worker_id = 1;
-        fill_default_worker_position();
-
-        let new_reward_account = 2;
-        let update_worker_account_fixture = UpdateWorkerRewardAccountFixture::default_with_ids(
-            invalid_worker_id,
-            new_reward_account,
-        );
-
-        update_worker_account_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::WorkerDoesNotExist.into(),
-        ));
-    });
-}
-
-#[test]
-fn update_worker_reward_account_fails_with_no_recurring_reward() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_worker_position_with_no_reward();
-
-        let new_reward_account = 343;
-
-        let update_worker_account_fixture =
-            UpdateWorkerRewardAccountFixture::default_with_ids(worker_id, new_reward_account);
-
-        update_worker_account_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::WorkerHasNoReward.into(),
-        ));
-    });
-}
-
-#[test]
-fn update_worker_reward_amount_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        let worker_id = fill_default_worker_position();
-
-        let update_worker_amount_fixture =
-            UpdateWorkerRewardAmountFixture::default_for_worker_id(worker_id);
-
-        update_worker_amount_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::WorkerRewardAmountUpdated(worker_id));
-    });
-}
-
-#[test]
-fn update_worker_reward_amount_succeeds_for_leader() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = HireLeadFixture::default()
-            .with_reward_policy(RewardPolicy {
-                amount_per_payout: 1000,
-                next_payment_at_block: 20,
-                payout_interval: None,
-            })
-            .hire_lead();
-
-        let update_worker_amount_fixture =
-            UpdateWorkerRewardAmountFixture::default_for_worker_id(worker_id)
-                .with_origin(RawOrigin::Root);
-
-        update_worker_amount_fixture.call_and_assert(Ok(()));
-    });
-}
-
-#[test]
-fn update_worker_reward_amount_fails_with_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let worker_id = 22; // random worker id
-
-        let update_worker_amount_fixture =
-            UpdateWorkerRewardAmountFixture::default_for_worker_id(worker_id)
-                .with_origin(RawOrigin::None);
-
-        update_worker_amount_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn update_worker_reward_amount_fails_with_invalid_origin_for_leader() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = HireLeadFixture::default().hire_lead();
-
-        let update_worker_amount_fixture =
-            UpdateWorkerRewardAmountFixture::default_for_worker_id(worker_id)
-                .with_origin(RawOrigin::None);
-
-        update_worker_amount_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn update_worker_reward_amount_fails_with_invalid_origin_signed_account() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_default_worker_position();
-
-        let update_worker_amount_fixture =
-            UpdateWorkerRewardAmountFixture::default_for_worker_id(worker_id)
-                .with_origin(RawOrigin::Signed(2));
-
-        update_worker_amount_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::IsNotLeadAccount.into(),
-        ));
-    });
-}
-
-#[test]
-fn update_worker_reward_amount_fails_with_invalid_worker_id() {
-    build_test_externalities().execute_with(|| {
-        let invalid_worker_id = 12;
-        fill_default_worker_position();
-
-        let update_worker_amount_fixture =
-            UpdateWorkerRewardAmountFixture::default_for_worker_id(invalid_worker_id);
-
-        update_worker_amount_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::WorkerDoesNotExist.into(),
-        ));
-    });
-}
-
-#[test]
-fn update_worker_reward_amount_fails_with_no_recurring_reward() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_worker_position_with_no_reward();
-
-        let update_worker_amount_fixture =
-            UpdateWorkerRewardAmountFixture::default_for_worker_id(worker_id);
-
-        update_worker_amount_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::WorkerHasNoReward.into(),
-        ));
-    });
-}
-
-fn fill_default_worker_position() -> u64 {
-    fill_worker_position(
-        Some(RewardPolicy {
-            amount_per_payout: 1000,
-            next_payment_at_block: 20,
-            payout_interval: None,
-        }),
-        None,
-        true,
-        OpeningType::Worker,
-        None,
-    )
-}
-
-fn fill_worker_position_with_no_reward() -> u64 {
-    fill_worker_position(None, None, true, OpeningType::Worker, None)
-}
-
-fn fill_worker_position_with_stake(stake: u64) -> u64 {
-    fill_worker_position(
-        Some(RewardPolicy {
-            amount_per_payout: 1000,
-            next_payment_at_block: 20,
-            payout_interval: None,
-        }),
-        Some(stake),
-        true,
-        OpeningType::Worker,
-        None,
-    )
-}
-
-fn fill_worker_position(
-    reward_policy: Option<RewardPolicy<u64, u64>>,
-    role_stake: Option<u64>,
-    setup_environment: bool,
-    opening_type: OpeningType,
-    worker_handle: Option<Vec<u8>>,
-) -> u64 {
-    let mut hiring_workflow = HiringWorkflow::default()
-        .with_role_stake(role_stake)
-        .with_setup_environment(setup_environment)
-        .with_opening_type(opening_type)
-        .with_reward_policy(reward_policy);
-
-    hiring_workflow = if let Some(worker_handle) = worker_handle {
-        hiring_workflow.add_application(worker_handle)
-    } else {
-        hiring_workflow.add_default_application()
-    };
-
-    hiring_workflow.execute().unwrap()
-}
-
-#[test]
-fn leave_worker_role_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        let worker_id = fill_default_worker_position();
-
-        let leave_worker_role_fixture = LeaveWorkerRoleFixture::default_for_worker_id(worker_id);
-
-        leave_worker_role_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::WorkerExited(
-            worker_id,
-            b"rationale_text".to_vec(),
-        ));
-    });
-}
-
-#[test]
-fn leave_worker_role_by_leader_succeeds() {
-    build_test_externalities().execute_with(|| {
-        // Ensure that lead is default
-        assert_eq!(TestWorkingGroup::current_lead(), None);
-        let worker_id = HireLeadFixture::default().hire_lead();
-
-        assert!(TestWorkingGroup::current_lead().is_some());
-
-        let leave_worker_role_fixture = LeaveWorkerRoleFixture::default_for_worker_id(worker_id);
-
-        leave_worker_role_fixture.call_and_assert(Ok(()));
-
-        assert_eq!(TestWorkingGroup::current_lead(), None);
-    });
-}
-
-#[test]
-fn leave_worker_role_fails_with_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        let leave_worker_role_fixture =
-            LeaveWorkerRoleFixture::default_for_worker_id(1).with_origin(RawOrigin::None);
-
-        leave_worker_role_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn leave_worker_role_fails_with_invalid_origin_signed_account() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_default_worker_position();
-
-        let leave_worker_role_fixture = LeaveWorkerRoleFixture::default_for_worker_id(worker_id)
-            .with_origin(RawOrigin::Signed(2));
-
-        leave_worker_role_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::SignerIsNotWorkerRoleAccount.into(),
-        ));
-    });
-}
-
-#[test]
-fn leave_worker_role_fails_with_invalid_worker_id() {
-    build_test_externalities().execute_with(|| {
-        let invalid_worker_id = 1;
-        fill_default_worker_position();
-
-        let leave_worker_role_fixture =
-            LeaveWorkerRoleFixture::default_for_worker_id(invalid_worker_id);
-
-        leave_worker_role_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::WorkerDoesNotExist.into(),
-        ));
-    });
-}
-
-#[test]
-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 = TestWorkingGroup::worker_by_id(worker_id);
-        worker.reward_relationship = Some(2);
-
-        <crate::WorkerById<Test, TestWorkingGroupInstance>>::insert(worker_id, worker);
-
-        let leave_worker_role_fixture = LeaveWorkerRoleFixture::default_for_worker_id(worker_id);
-
-        leave_worker_role_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::RelationshipMustExist.into(),
-        ));
-    });
-}
-
-#[test]
-fn leave_worker_role_succeeds_with_stakes() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        let worker_id = fill_worker_position_with_stake(100);
-
-        let leave_worker_role_fixture = LeaveWorkerRoleFixture::default_for_worker_id(worker_id);
-
-        leave_worker_role_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::WorkerExited(
-            worker_id,
-            b"rationale_text".to_vec(),
-        ));
-    });
-}
-
-#[test]
-fn terminate_worker_role_succeeds_with_stakes() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        let total_balance = 10000;
-        let stake_balance = 100;
-
-        let worker_account_id = 2;
-        let worker_member_id = 2;
-        increase_total_balance_issuance_using_account_id(worker_account_id, total_balance);
-
-        HireLeadFixture::default().hire_lead();
-
-        let worker_id = HiringWorkflow::default()
-            .disable_setup_environment()
-            .with_role_stake(Some(stake_balance))
-            .add_application_with_origin(
-                b"worker_handle".to_vec(),
-                RawOrigin::Signed(worker_account_id),
-                worker_member_id,
-            )
-            .execute()
-            .unwrap();
-
-        // Balance was staked.
-        assert_eq!(
-            get_balance(worker_account_id),
-            total_balance - stake_balance
-        );
-
-        let stake_id = 0;
-        let old_stake = <stake::Module<Test>>::stakes(stake_id);
-
-        assert_eq!(get_stake_balance(old_stake), stake_balance);
-
-        let terminate_worker_role_fixture =
-            TerminateWorkerRoleFixture::default_for_worker_id(worker_id);
-
-        terminate_worker_role_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::TerminatedWorker(
-            worker_id,
-            b"rationale_text".to_vec(),
-        ));
-
-        // Balance was restored.
-
-        assert_eq!(get_balance(worker_account_id), total_balance);
-
-        let new_stake = <stake::Module<Test>>::stakes(stake_id);
-        assert!(matches!(
-            new_stake.staking_status,
-            stake::StakingStatus::NotStaked
-        ));
-    });
-}
-
-#[test]
-fn terminate_worker_role_succeeds_with_slashing() {
-    build_test_externalities().execute_with(|| {
-        let total_balance = 10000;
-        let stake_balance = 100;
-
-        let worker_account_id = 2;
-        let worker_member_id = 2;
-        increase_total_balance_issuance_using_account_id(worker_account_id, total_balance);
-
-        assert_eq!(get_balance(worker_account_id), total_balance);
-
-        HireLeadFixture::default().hire_lead();
-
-        let worker_id = HiringWorkflow::default()
-            .disable_setup_environment()
-            .with_role_stake(Some(stake_balance))
-            .add_application_with_origin(
-                b"worker_handle".to_vec(),
-                RawOrigin::Signed(worker_account_id),
-                worker_member_id,
-            )
-            .execute()
-            .unwrap();
-
-        // Balance was staked.
-
-        assert_eq!(
-            get_balance(worker_account_id),
-            total_balance - stake_balance
-        );
-
-        let stake_id = 0;
-        let old_stake = <stake::Module<Test>>::stakes(stake_id);
-
-        assert_eq!(get_stake_balance(old_stake), stake_balance);
-
-        // Terminate with slashing.
-
-        let terminate_worker_role_fixture =
-            TerminateWorkerRoleFixture::default_for_worker_id(worker_id).with_slashing();
-
-        terminate_worker_role_fixture.call_and_assert(Ok(()));
-
-        // Balance was slashed.
-
-        assert_eq!(
-            get_balance(worker_account_id),
-            total_balance - stake_balance
-        );
-
-        let new_stake = <stake::Module<Test>>::stakes(stake_id);
-        assert!(matches!(
-            new_stake.staking_status,
-            stake::StakingStatus::NotStaked
-        ));
-    });
-}
-
-#[test]
-fn terminate_worker_role_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        HireLeadFixture::default().hire_lead();
-
-        let worker_id = HiringWorkflow::default()
-            .disable_setup_environment()
-            .add_application_with_origin(b"worker_handle".to_vec(), RawOrigin::Signed(2), 2)
-            .execute()
-            .unwrap();
-
-        let terminate_worker_role_fixture =
-            TerminateWorkerRoleFixture::default_for_worker_id(worker_id);
-
-        terminate_worker_role_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::TerminatedWorker(
-            worker_id,
-            b"rationale_text".to_vec(),
-        ));
-    });
-}
-
-#[test]
-fn fire_leader_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        let worker_id = HireLeadFixture::default().hire_lead();
-
-        let terminate_worker_role_fixture =
-            TerminateWorkerRoleFixture::default_for_worker_id(worker_id)
-                .with_origin(RawOrigin::Root);
-
-        terminate_worker_role_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::TerminatedLeader(
-            worker_id,
-            b"rationale_text".to_vec(),
-        ));
-
-        assert_eq!(TestWorkingGroup::current_lead(), None);
-    });
-}
-
-#[test]
-fn terminate_worker_role_fails_with_invalid_text() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let worker_id = HiringWorkflow::default()
-            .disable_setup_environment()
-            .add_application_with_origin(b"worker_handle".to_vec(), RawOrigin::Signed(2), 2)
-            .execute()
-            .unwrap();
-
-        let terminate_worker_role_fixture =
-            TerminateWorkerRoleFixture::default_for_worker_id(worker_id).with_text(Vec::new());
-        terminate_worker_role_fixture
-            .call_and_assert(Err(DispatchError::Other("WorkerExitRationaleTextTooShort")));
-
-        let terminate_worker_role_fixture =
-            TerminateWorkerRoleFixture::default_for_worker_id(worker_id)
-                .with_text(b"MSG_WORKER_EXIT_RATIONALE_TEXT_TOO_LONG".to_vec());
-        terminate_worker_role_fixture
-            .call_and_assert(Err(DispatchError::Other("WorkerExitRationaleTextTooLong")));
-    });
-}
-
-#[test]
-fn terminate_worker_role_fails_with_unset_lead() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_default_worker_position();
-
-        SetLeadFixture::unset_lead();
-
-        let terminate_worker_role_fixture =
-            TerminateWorkerRoleFixture::default_for_worker_id(worker_id);
-
-        terminate_worker_role_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::CurrentLeadNotSet.into(),
-        ));
-    });
-}
-
-#[test]
-fn terminate_worker_role_fails_with_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let worker_id = HiringWorkflow::default()
-            .disable_setup_environment()
-            .add_application_with_origin(b"worker_handle".to_vec(), RawOrigin::Signed(2), 2)
-            .execute()
-            .unwrap();
-
-        let terminate_worker_role_fixture =
-            TerminateWorkerRoleFixture::default_for_worker_id(worker_id)
-                .with_origin(RawOrigin::None);
-
-        terminate_worker_role_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn fire_leader_fails_with_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = HireLeadFixture::default().hire_lead();
-
-        let terminate_worker_role_fixture =
-            TerminateWorkerRoleFixture::default_for_worker_id(worker_id)
-                .with_origin(RawOrigin::None);
-
-        terminate_worker_role_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn increase_worker_stake_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        let worker_id = fill_worker_position_with_stake(100);
-
-        let increase_stake_fixture = IncreaseWorkerStakeFixture::default_for_worker_id(worker_id);
-
-        increase_stake_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::StakeIncreased(worker_id));
-    });
-}
-
-#[test]
-fn increase_worker_stake_succeeds_for_leader() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = HireLeadFixture::default().with_stake(100).hire_lead();
-
-        let increase_stake_fixture = IncreaseWorkerStakeFixture::default_for_worker_id(worker_id);
-
-        increase_stake_fixture.call_and_assert(Ok(()));
-    });
-}
-
-#[test]
-fn increase_worker_stake_fails_with_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = 0;
-        let increase_stake_fixture = IncreaseWorkerStakeFixture::default_for_worker_id(worker_id)
-            .with_origin(RawOrigin::None);
-
-        increase_stake_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn increase_worker_stake_fails_with_zero_balance() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_worker_position_with_stake(100);
-
-        let increase_stake_fixture =
-            IncreaseWorkerStakeFixture::default_for_worker_id(worker_id).with_balance(0);
-
-        increase_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::StakeBalanceCannotBeZero.into(),
-        ));
-    });
-}
-
-#[test]
-fn increase_worker_stake_fails_with_invalid_worker_id() {
-    build_test_externalities().execute_with(|| {
-        let invalid_worker_id = 11;
-
-        let increase_stake_fixture =
-            IncreaseWorkerStakeFixture::default_for_worker_id(invalid_worker_id);
-
-        increase_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::WorkerDoesNotExist.into(),
-        ));
-    });
-}
-
-#[test]
-fn increase_worker_stake_fails_with_invalid_balance() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_worker_position_with_stake(100);
-        let invalid_balance = 100000000;
-        let increase_stake_fixture = IncreaseWorkerStakeFixture::default_for_worker_id(worker_id)
-            .with_balance(invalid_balance);
-
-        increase_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::StakingErrorInsufficientBalanceInSourceAccount
-                .into(),
-        ));
-    });
-}
-
-#[test]
-fn increase_worker_stake_fails_with_no_stake_profile() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_default_worker_position();
-
-        let increase_stake_fixture = IncreaseWorkerStakeFixture::default_for_worker_id(worker_id);
-
-        increase_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::NoWorkerStakeProfile.into(),
-        ));
-    });
-}
-
-#[test]
-fn decrease_worker_stake_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        let worker_id = fill_worker_position_with_stake(100);
-
-        let decrease_stake_fixture = DecreaseWorkerStakeFixture::default_for_worker_id(worker_id);
-
-        decrease_stake_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::StakeDecreased(worker_id));
-    });
-}
-
-#[test]
-fn decrease_worker_stake_succeeds_for_leader() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = HireLeadFixture::default().with_stake(100).hire_lead();
-
-        let decrease_stake_fixture = DecreaseWorkerStakeFixture::default_for_worker_id(worker_id)
-            .with_origin(RawOrigin::Root);
-
-        decrease_stake_fixture.call_and_assert(Ok(()));
-    });
-}
-
-#[test]
-fn decrease_worker_stake_fails_with_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let worker_id = 22; // random worker id
-        let decrease_stake_fixture = DecreaseWorkerStakeFixture::default_for_worker_id(worker_id)
-            .with_origin(RawOrigin::None);
-
-        decrease_stake_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn decrease_worker_stake_fails_with_invalid_origin_for_leader() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = HireLeadFixture::default().hire_lead();
-        let decrease_stake_fixture = DecreaseWorkerStakeFixture::default_for_worker_id(worker_id)
-            .with_origin(RawOrigin::None);
-
-        decrease_stake_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn decrease_worker_stake_fails_with_zero_balance() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_worker_position_with_stake(100);
-
-        let decrease_stake_fixture =
-            DecreaseWorkerStakeFixture::default_for_worker_id(worker_id).with_balance(0);
-
-        decrease_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::StakeBalanceCannotBeZero.into(),
-        ));
-    });
-}
-
-#[test]
-fn decrease_worker_stake_fails_with_invalid_worker_id() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-        let invalid_worker_id = 11;
-
-        let decrease_stake_fixture =
-            DecreaseWorkerStakeFixture::default_for_worker_id(invalid_worker_id);
-
-        decrease_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::WorkerDoesNotExist.into(),
-        ));
-    });
-}
-
-#[test]
-fn decrease_worker_stake_fails_with_invalid_balance() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_worker_position_with_stake(100);
-        let invalid_balance = 100000000;
-        let decrease_stake_fixture = DecreaseWorkerStakeFixture::default_for_worker_id(worker_id)
-            .with_balance(invalid_balance);
-
-        decrease_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::StakingErrorInsufficientStake.into(),
-        ));
-    });
-}
-
-#[test]
-fn decrease_worker_stake_fails_with_no_stake_profile() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_default_worker_position();
-
-        let decrease_stake_fixture = DecreaseWorkerStakeFixture::default_for_worker_id(worker_id);
-
-        decrease_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::NoWorkerStakeProfile.into(),
-        ));
-    });
-}
-
-#[test]
-fn decrease_worker_stake_fails_with_not_set_lead() {
-    build_test_externalities().execute_with(|| {
-        let invalid_worker_id = 11;
-
-        let decrease_stake_fixture =
-            DecreaseWorkerStakeFixture::default_for_worker_id(invalid_worker_id);
-
-        decrease_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::CurrentLeadNotSet.into(),
-        ));
-    });
-}
-
-#[test]
-fn slash_worker_stake_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-          Events are not emitted on block 0.
-          So any dispatchable calls made during genesis block formation will have no events emitted.
-          https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        let worker_id = fill_worker_position_with_stake(100);
-
-        let slash_stake_fixture = SlashWorkerStakeFixture::default_for_worker_id(worker_id);
-
-        slash_stake_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::StakeSlashed(worker_id));
-    });
-}
-
-#[test]
-fn slash_leader_stake_succeeds() {
-    build_test_externalities().execute_with(|| {
-        /*
-           Events are not emitted on block 0.
-           So any dispatchable calls made during genesis block formation will have no events emitted.
-           https://substrate.dev/recipes/2-appetizers/4-events.html
-        */
-        run_to_block(1);
-
-        let leader_worker_id = HiringWorkflow::default()
-            .with_role_stake(Some(100))
-            .with_opening_type(OpeningType::Leader)
-            .add_default_application()
-            .execute()
-            .unwrap();
-
-        let slash_stake_fixture = SlashWorkerStakeFixture::default_for_worker_id(leader_worker_id)
-            .with_origin(RawOrigin::Root);
-
-        slash_stake_fixture.call_and_assert(Ok(()));
-
-        EventFixture::assert_last_crate_event(RawEvent::StakeSlashed(leader_worker_id));
-    });
-}
-
-#[test]
-fn slash_worker_stake_fails_with_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        let invalid_worker_id = 22;
-        let slash_stake_fixture = SlashWorkerStakeFixture::default_for_worker_id(invalid_worker_id)
-            .with_origin(RawOrigin::None);
-
-        slash_stake_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn slash_leader_stake_fails_with_invalid_origin() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = HireLeadFixture::default().hire_lead();
-
-        let slash_stake_fixture =
-            SlashWorkerStakeFixture::default_for_worker_id(worker_id).with_origin(RawOrigin::None);
-
-        slash_stake_fixture.call_and_assert(Err(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn slash_worker_stake_fails_with_zero_balance() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_worker_position_with_stake(100);
-
-        let slash_stake_fixture =
-            SlashWorkerStakeFixture::default_for_worker_id(worker_id).with_balance(0);
-
-        slash_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::StakeBalanceCannotBeZero.into(),
-        ));
-    });
-}
-
-#[test]
-fn slash_worker_stake_fails_with_invalid_worker_id() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-        let invalid_worker_id = 11;
-
-        let slash_stake_fixture = SlashWorkerStakeFixture::default_for_worker_id(invalid_worker_id);
-
-        slash_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::WorkerDoesNotExist.into(),
-        ));
-    });
-}
-
-#[test]
-fn slash_worker_stake_fails_with_no_stake_profile() {
-    build_test_externalities().execute_with(|| {
-        let worker_id = fill_default_worker_position();
-
-        let slash_stake_fixture = SlashWorkerStakeFixture::default_for_worker_id(worker_id);
-
-        slash_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::NoWorkerStakeProfile.into(),
-        ));
-    });
-}
-
-#[test]
-fn slash_worker_stake_fails_with_not_set_lead() {
-    build_test_externalities().execute_with(|| {
-        let invalid_worker_id = 11;
-
-        let slash_stake_fixture = SlashWorkerStakeFixture::default_for_worker_id(invalid_worker_id);
-
-        slash_stake_fixture.call_and_assert(Err(
-            Error::<Test, TestWorkingGroupInstance>::CurrentLeadNotSet.into(),
-        ));
-    });
-}
-
-#[test]
-fn get_regular_worker_ids_succeeds() {
-    build_test_externalities().execute_with(|| {
-        let worker_ids = TestWorkingGroup::get_regular_worker_ids();
-        assert_eq!(worker_ids, Vec::<u64>::new());
-
-        let leader_worker_id = HireLeadFixture::default().hire_lead();
-
-        let worker_id1 = fill_worker_position(None, None, false, OpeningType::Worker, None);
-        let worker_id2 = fill_worker_position(None, None, false, OpeningType::Worker, None);
-
-        let mut expected_ids = vec![worker_id1, worker_id2];
-        expected_ids.sort();
-
-        let mut worker_ids = TestWorkingGroup::get_regular_worker_ids();
-        worker_ids.sort();
-        assert_eq!(worker_ids, expected_ids);
-
-        assert!(!expected_ids.contains(&leader_worker_id));
-
-        <crate::WorkerById<Test, TestWorkingGroupInstance>>::remove(worker_id1);
-        let worker_ids = TestWorkingGroup::get_regular_worker_ids();
-        assert_eq!(worker_ids, vec![worker_id2]);
-    });
-}
-
-#[test]
-fn get_all_worker_ids_succeeds() {
-    build_test_externalities().execute_with(|| {
-        let worker_ids = TestWorkingGroup::get_all_worker_ids();
-        assert_eq!(worker_ids, Vec::<u64>::new());
-
-        let leader_worker_id = HireLeadFixture::default().hire_lead();
-
-        let worker_id1 = fill_worker_position(None, None, false, OpeningType::Worker, None);
-        let worker_id2 = fill_worker_position(None, None, false, OpeningType::Worker, None);
-
-        let mut expected_ids = vec![leader_worker_id, worker_id1, worker_id2];
-        expected_ids.sort();
-
-        let mut worker_ids = TestWorkingGroup::get_all_worker_ids();
-        worker_ids.sort();
-        assert_eq!(worker_ids, expected_ids);
-
-        <crate::WorkerById<Test, TestWorkingGroupInstance>>::remove(worker_id1);
-        let worker_ids = TestWorkingGroup::get_all_worker_ids();
-        assert_eq!(worker_ids, vec![leader_worker_id, 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::<Test, TestWorkingGroupInstance>::CannotFindMint.into())
-        );
-    });
-}
-
-#[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(DispatchError::BadOrigin));
-    });
-}
-
-#[test]
-fn ensure_setting_genesis_working_group_mint_succeeds() {
-    build_test_externalities().execute_with(|| {
-        let mint_id = TestWorkingGroup::mint();
-
-        assert!(minting::Mints::<Test>::contains_key(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::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);
-    });
-}
-
-#[test]
-fn active_worker_counter_works_successfully() {
-    build_test_externalities().execute_with(|| {
-        assert_eq!(TestWorkingGroup::active_worker_count(), 0);
-
-        let leader_id = HireLeadFixture::default().hire_lead();
-        assert_eq!(TestWorkingGroup::active_worker_count(), 1);
-
-        let worker_id1 = fill_worker_position(
-            None,
-            None,
-            false,
-            OpeningType::Worker,
-            Some(b"worker1".to_vec()),
-        );
-        assert_eq!(TestWorkingGroup::active_worker_count(), 2);
-
-        let worker_id2 = fill_worker_position(
-            None,
-            None,
-            false,
-            OpeningType::Worker,
-            Some(b"worker1".to_vec()),
-        );
-        assert_eq!(TestWorkingGroup::active_worker_count(), 3);
-
-        TerminateWorkerRoleFixture::default_for_worker_id(worker_id1).call_and_assert(Ok(()));
-        assert_eq!(TestWorkingGroup::active_worker_count(), 2);
-
-        TerminateWorkerRoleFixture::default_for_worker_id(worker_id2).call_and_assert(Ok(()));
-        assert_eq!(TestWorkingGroup::active_worker_count(), 1);
-
-        TerminateWorkerRoleFixture::default_for_worker_id(leader_id)
-            .with_origin(RawOrigin::Root)
-            .call_and_assert(Ok(()));
-        assert_eq!(TestWorkingGroup::active_worker_count(), 0);
-    });
-}
-
-#[test]
-fn adding_too_much_workers_fails_with_single_application_out_of_limit() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        fill_worker_position(None, None, false, OpeningType::Worker, None);
-        fill_worker_position(None, None, false, OpeningType::Worker, None);
-
-        let hiring_workflow = HiringWorkflow::default()
-            .disable_setup_environment()
-            .add_default_application()
-            .expect(Err(
-                Error::<Test, TestWorkingGroupInstance>::MaxActiveWorkerNumberExceeded.into(),
-            ));
-
-        hiring_workflow.execute()
-    });
-}
-
-#[test]
-fn fill_opening_cannot_hire_more_workers_using_several_applicationst_han_allows_worker_limit() {
-    build_test_externalities().execute_with(|| {
-        HireLeadFixture::default().hire_lead();
-
-        fill_worker_position(None, None, false, OpeningType::Worker, None);
-
-        let hiring_workflow = HiringWorkflow::default()
-            .disable_setup_environment()
-            .add_application_with_origin(b"Some1".to_vec(), RawOrigin::Signed(2), 2)
-            .add_application_with_origin(b"Some2".to_vec(), RawOrigin::Signed(3), 3)
-            .expect(Err(
-                Error::<Test, TestWorkingGroupInstance>::MaxActiveWorkerNumberExceeded.into(),
-            ));
-
-        hiring_workflow.execute()
-    });
-}

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

@@ -1,251 +0,0 @@
-#![warn(missing_docs)]
-
-use codec::{Decode, Encode};
-use sp_std::collections::btree_set::BTreeSet;
-
-#[cfg(feature = "std")]
-use serde::{Deserialize, Serialize};
-
-/// Terms for slashes applied to a given role.
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Debug, Clone, PartialEq, Eq)]
-pub struct SlashableTerms {
-    /// Maximum number of slashes.
-    pub max_count: u16,
-
-    /// Maximum percentage points of remaining stake which may be slashed in a single slash.
-    pub max_percent_pts_per_time: u16,
-}
-
-/// Terms for what slashing can be applied in some context.
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Debug, Clone, PartialEq, Eq)]
-pub enum SlashingTerms {
-    /// Cannot be slashed.
-    Unslashable,
-
-    /// Can be slashed.
-    Slashable(SlashableTerms),
-}
-
-/// Must be default constructable because it indirectly is a value in a storage map.
-/// ***SHOULD NEVER ACTUALLY GET CALLED, IS REQUIRED TO DUE BAD STORAGE MODEL IN SUBSTRATE***
-impl Default for SlashingTerms {
-    fn default() -> Self {
-        Self::Unslashable
-    }
-}
-
-/// A commitment to the set of policy variables relevant to an opening.
-/// An applicant can observe this commitment and be secure that the terms
-/// of the application process cannot be changed ex-post.
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Debug, Clone, Default, PartialEq, Eq)]
-pub struct OpeningPolicyCommitment<BlockNumber, Balance> {
-    /// Rationing to be used.
-    pub application_rationing_policy: Option<hiring::ApplicationRationingPolicy>,
-
-    /// Maximum length of review period of applications.
-    pub max_review_period_length: BlockNumber,
-
-    /// Staking policy for application.
-    pub application_staking_policy: Option<hiring::StakingPolicy<Balance, BlockNumber>>,
-
-    /// Staking policy for role itself.
-    pub role_staking_policy: Option<hiring::StakingPolicy<Balance, BlockNumber>>,
-
-    /// Slashing terms during role, NOT application itself!
-    pub role_slashing_terms: SlashingTerms,
-
-    /// When filling an opening: unstaking period for application stake of successful applicants.
-    pub fill_opening_successful_applicant_application_stake_unstaking_period: Option<BlockNumber>,
-
-    /// When filling an opening: unstaking period for the application stake of failed applicants.
-    pub fill_opening_failed_applicant_application_stake_unstaking_period: Option<BlockNumber>,
-
-    /// When filling an opening: unstaking period for the role stake of failed applicants.
-    pub fill_opening_failed_applicant_role_stake_unstaking_period: Option<BlockNumber>,
-
-    /// When terminating a worker: unstaking period for application stake.
-    pub terminate_application_stake_unstaking_period: Option<BlockNumber>,
-
-    /// When terminating a worke/leadr: unstaking period for role stake.
-    pub terminate_role_stake_unstaking_period: Option<BlockNumber>,
-
-    /// When a worker/lead exists: unstaking period for application stake.
-    pub exit_role_application_stake_unstaking_period: Option<BlockNumber>,
-
-    /// When a worker/lead exists: unstaking period for role stake.
-    pub exit_role_stake_unstaking_period: Option<BlockNumber>,
-}
-
-/// An opening for a worker or lead role.
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
-pub struct Opening<OpeningId, BlockNumber, Balance, WorkerApplicationId: core::cmp::Ord> {
-    /// Identifier for underlying opening in the hiring module.
-    pub hiring_opening_id: OpeningId,
-
-    /// Set of identifiers for all worker applications ever added.
-    pub applications: BTreeSet<WorkerApplicationId>,
-
-    /// Commitment to policies in opening.
-    pub policy_commitment: OpeningPolicyCommitment<BlockNumber, Balance>,
-
-    /// Defines opening type: Leader or worker.
-    pub opening_type: OpeningType,
-}
-
-/// Defines type of the opening: regular working group fellow or group leader.
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Debug, Clone, PartialEq, Eq, Copy)]
-pub enum OpeningType {
-    /// Group leader.
-    Leader,
-
-    /// Regular worker.
-    Worker,
-}
-
-/// Must be default constructible because it indirectly is a value in a storage map.
-/// ***SHOULD NEVER ACTUALLY GET CALLED, IS REQUIRED TO DUE BAD STORAGE MODEL IN SUBSTRATE***
-impl Default for OpeningType {
-    fn default() -> Self {
-        Self::Worker
-    }
-}
-
-/// An application for the worker/lead role.
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
-pub struct Application<AccountId, OpeningId, MemberId, ApplicationId> {
-    /// Account used to authenticate in this role.
-    pub role_account_id: AccountId,
-
-    /// Opening on which this application applies.
-    pub opening_id: OpeningId,
-
-    /// Member applying.
-    pub member_id: MemberId,
-
-    /// Underlying application in hiring module.
-    pub hiring_application_id: ApplicationId,
-}
-
-impl<AccountId: Clone, OpeningId: Clone, MemberId: Clone, ApplicationId: Clone>
-    Application<AccountId, OpeningId, MemberId, ApplicationId>
-{
-    /// Creates a new worker application using parameters.
-    pub fn new(
-        role_account_id: &AccountId,
-        opening_id: &OpeningId,
-        member_id: &MemberId,
-        application_id: &ApplicationId,
-    ) -> Self {
-        Application {
-            role_account_id: role_account_id.clone(),
-            opening_id: opening_id.clone(),
-            member_id: member_id.clone(),
-            hiring_application_id: application_id.clone(),
-        }
-    }
-}
-
-/// Role stake information for a worker/lead.
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
-pub struct RoleStakeProfile<StakeId, BlockNumber> {
-    /// Whether participant is staked, and if so, the identifier for this staking in the staking module.
-    pub stake_id: StakeId,
-
-    /// Unstaking period when terminated.
-    pub termination_unstaking_period: Option<BlockNumber>,
-
-    /// Unstaking period when exiting.
-    pub exit_unstaking_period: Option<BlockNumber>,
-}
-
-impl<StakeId: Clone, BlockNumber: Clone> RoleStakeProfile<StakeId, BlockNumber> {
-    /// Creates a new worker/lead role stake profile using stake parameters.
-    pub fn new(
-        stake_id: &StakeId,
-        termination_unstaking_period: &Option<BlockNumber>,
-        exit_unstaking_period: &Option<BlockNumber>,
-    ) -> Self {
-        Self {
-            stake_id: stake_id.clone(),
-            termination_unstaking_period: termination_unstaking_period.clone(),
-            exit_unstaking_period: exit_unstaking_period.clone(),
-        }
-    }
-}
-
-/// Working group participant: worker/lead.
-/// This role can be staked, have reward and be inducted through the hiring module.
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
-pub struct Worker<AccountId, RewardRelationshipId, StakeId, BlockNumber, MemberId> {
-    /// Member id related to the worker/lead.
-    pub member_id: MemberId,
-
-    /// Account used to authenticate in this role.
-    pub role_account_id: AccountId,
-
-    /// Whether the role has recurring reward, and if so an identifier for this.
-    pub reward_relationship: Option<RewardRelationshipId>,
-
-    /// When set, describes role stake of the worker/lead.
-    pub role_stake_profile: Option<RoleStakeProfile<StakeId, BlockNumber>>,
-}
-
-impl<
-        AccountId: Clone,
-        RewardRelationshipId: Clone,
-        StakeId: Clone,
-        BlockNumber: Clone,
-        MemberId: Clone,
-    > Worker<AccountId, RewardRelationshipId, StakeId, BlockNumber, MemberId>
-{
-    /// Creates a new _Worker_ using parameters.
-    pub fn new(
-        member_id: &MemberId,
-        role_account_id: &AccountId,
-        reward_relationship: &Option<RewardRelationshipId>,
-        role_stake_profile: &Option<RoleStakeProfile<StakeId, BlockNumber>>,
-    ) -> Self {
-        Worker {
-            member_id: member_id.clone(),
-            role_account_id: role_account_id.clone(),
-            reward_relationship: reward_relationship.clone(),
-            role_stake_profile: role_stake_profile.clone(),
-        }
-    }
-}
-
-/// Origin of exit initiation.
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Debug, Clone, PartialEq)]
-pub enum ExitInitiationOrigin {
-    /// Lead fires the worker.
-    Lead,
-
-    /// Worker leaves the position.
-    Worker,
-
-    /// Council fires the leader.
-    Sudo,
-}
-
-/// The recurring reward if any to be assigned to an actor when filling in the position.
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-#[derive(Encode, Decode, Clone, PartialEq, Debug)]
-pub struct RewardPolicy<Balance, BlockNumber> {
-    /// Balance per payout.
-    pub amount_per_payout: Balance,
-
-    /// Next payment time (in blocks).
-    pub next_payment_at_block: BlockNumber,
-
-    /// Optional payout interval.
-    pub payout_interval: Option<BlockNumber>,
-}