Sfoglia il codice sorgente

benchmark: working-team: add mock runtime impl and benchmark for leave_role

* Adds a mock impl for working_team in the runtime needed to test benchmark code
* Adds benchmarks in the runtime
* Adds benchmark for working_team
* Implement first draft for leave_role benchmarking implementation
conectado 4 anni fa
parent
commit
e0a6f5425c

+ 11 - 2
Cargo.lock

@@ -1690,6 +1690,12 @@ dependencies = [
  "proc-macro-hack",
 ]
 
+[[package]]
+name = "hex-literal"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5af1f635ef1bc545d78392b136bfe1c9809e029023c84a3638a864a10b8819c8"
+
 [[package]]
 name = "hex-literal-impl"
 version = "0.2.2"
@@ -2061,6 +2067,7 @@ dependencies = [
  "frame-system",
  "frame-system-benchmarking",
  "frame-system-rpc-runtime-api",
+ "hex-literal 0.3.1",
  "pallet-authority-discovery",
  "pallet-authorship",
  "pallet-babe",
@@ -2098,6 +2105,7 @@ dependencies = [
  "pallet-versioned-store",
  "pallet-versioned-store-permissions",
  "pallet-working-group",
+ "pallet-working-team",
  "parity-scale-codec",
  "serde",
  "sp-api",
@@ -3887,6 +3895,7 @@ dependencies = [
 name = "pallet-working-team"
 version = "1.0.0"
 dependencies = [
+ "frame-benchmarking",
  "frame-support",
  "frame-system",
  "pallet-balances",
@@ -5048,7 +5057,7 @@ dependencies = [
  "fnv",
  "futures 0.3.4",
  "hash-db",
- "hex-literal",
+ "hex-literal 0.2.1",
  "kvdb",
  "lazy_static",
  "log",
@@ -5658,7 +5667,7 @@ dependencies = [
  "fdlimit",
  "futures 0.1.29",
  "futures 0.3.4",
- "hex-literal",
+ "hex-literal 0.2.1",
  "log",
  "parity-scale-codec",
  "parking_lot 0.10.2",

+ 3 - 0
runtime-modules/working-team/Cargo.toml

@@ -16,6 +16,7 @@ common = { package = 'pallet-common', default-features = false, path = '../commo
 membership = { package = 'pallet-membership', default-features = false, path = '../membership'}
 balances = { package = 'pallet-balances', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
 
+frame-benchmarking = { package = 'frame-benchmarking', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4', optional = true}
 
 [dev-dependencies]
 sp-io = { package = 'sp-io', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
@@ -24,6 +25,7 @@ pallet-timestamp = { package = 'pallet-timestamp', default-features = false, git
 
 [features]
 default = ['std']
+runtime-benchmarks = ["frame-benchmarking"]
 std = [
 	'serde',
 	'codec/std',
@@ -35,4 +37,5 @@ std = [
 	'common/std',
 	'membership/std',
 	'balances/std',
+  'frame-benchmarking/std',
 ]

+ 131 - 0
runtime-modules/working-team/src/benchmarking.rs

@@ -0,0 +1,131 @@
+#![cfg(feature = "runtime-benchmarks")]
+use super::*;
+use frame_benchmarking::{benchmarks_instance, Zero};
+use sp_std::prelude::*;
+use system as frame_system;
+use system::RawOrigin;
+
+fn create_a_worker<T: Trait<I>, I: Instance>(
+    caller_id: &T::AccountId,
+    member_id: &T::MemberId,
+    can_leave_immediatly: bool,
+) -> TeamWorker<T> {
+    let job_unstaking_period = if !can_leave_immediatly {
+        <T as system::Trait>::BlockNumber::from(1u32)
+    } else {
+        Zero::zero()
+    };
+    TeamWorker::<T>::new(
+        &member_id,
+        &caller_id,
+        &caller_id,
+        &None,
+        job_unstaking_period,
+        None,
+        Zero::zero(),
+    )
+}
+
+fn insert_a_worker<T: Trait<I>, I: Instance>(
+    can_leave_immediatly: bool,
+) -> (T::AccountId, TeamWorkerId<T>) {
+    /*
+     * TODO: Be able to have a different name for each account/member
+     */
+    let caller_id = frame_benchmarking::account::<T::AccountId>("caller", 0, 0);
+    let member_id = frame_benchmarking::account::<T::MemberId>("member", 0, 0);
+
+    let worker_id = <NextWorkerId<T, I>>::get();
+
+    let worker = create_a_worker::<T, I>(&caller_id, &member_id, can_leave_immediatly);
+
+    <NextWorkerId<T, I>>::mutate(|id| *id += <TeamWorkerId<T> as One>::one());
+    <ActiveWorkerCount<I>>::put(<ActiveWorkerCount<I>>::get() + 1);
+
+    <WorkerById<T, I>>::insert(worker_id, worker);
+
+    (caller_id, worker_id)
+}
+
+benchmarks_instance! {
+    _ { }
+
+    leave_role_immediatly {
+        let i in 0 .. 10;
+
+        let (caller_id, caller_worker_id) = insert_a_worker::<T, I>(true);
+        // Worst case scenario there is a lead(this requires **always** more steps)
+        // could separate into new branch to tighten weight
+        let (_, _) = insert_a_worker::<T, I>(false);
+
+    }: leave_role(RawOrigin::Signed(caller_id), caller_worker_id)
+    verify { }
+
+
+    leave_role_later {
+        let i in 0 .. 10;
+
+        let (caller_id, caller_worker_id) = insert_a_worker::<T, I>(false);
+    }: leave_role(RawOrigin::Signed(caller_id), caller_worker_id)
+    verify { }
+
+    /*
+    set_budget {
+      let i in 0 .. 10;
+
+      let balance = BalanceOfCurrency::<T>::from(0u32);
+
+    }: _ (RawOrigin::Root, balance)
+    verify { }
+
+    add_opening {
+      let i in 0 .. 10;
+
+      let description = vec![0u8];
+      let opening_type = JobOpeningType::Regular;
+      let stake_policy = None;
+      let reward_policy = None;
+      /*
+       * TODO: IMPLEMENT
+       */
+
+    }: _ (i, description, opening_type, stake_policy, reward_policy)
+    verify {}
+
+    apply_on_opening {
+      let i in 0 .. 10;
+
+      let member_id = frame_benchmarking::account::<T::MemberId>("member", 0, 0);
+      let
+      ApplyOnOpeningParameters<T, I> {
+        member_id
+      }
+
+    }: _ ()
+    verify {}
+    */
+}
+
+/*
+    on_initialize {
+      let i in 0 .. T::MaxWorkerNumberLimit::get();
+    }: _ ()
+    verify { }
+*/
+
+/*
+TODO: we need to implement new_test_ext that creates a `sp_io::TestExternalities`
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::tests::{new_test_ext, Test};
+    use frame_support::assert_ok;
+
+    #[test]
+    fn test_benchmarks() {
+        new_test_ext().execute_with(|| {
+            assert_ok!(test_benchmark_leave_role::<Test>());
+        });
+    }
+}
+*/

+ 1 - 0
runtime-modules/working-team/src/checks.rs

@@ -9,6 +9,7 @@ use frame_support::traits::Get;
 use frame_support::{ensure, StorageMap, StorageValue};
 use sp_arithmetic::traits::Zero;
 use sp_std::collections::btree_set::BTreeSet;
+use sp_std::vec::Vec;
 use system::{ensure_root, ensure_signed};
 
 use crate::types::{ApplicationInfo, StakeParameters};

+ 7 - 1
runtime-modules/working-team/src/lib.rs

@@ -29,6 +29,7 @@
 // Do not delete! Cannot be uncommented by default, because of Parity decl_module! issue.
 //#![warn(missing_docs)]
 
+mod benchmarking;
 mod checks;
 mod errors;
 #[cfg(test)]
@@ -47,7 +48,12 @@ use sp_std::vec::Vec;
 use system::{ensure_root, ensure_signed};
 
 pub use errors::Error;
-use types::{ApplicationInfo, BalanceOfCurrency, MemberId, TeamWorker, TeamWorkerId, WorkerInfo};
+/*
+ * TODO: Change this back, this is only needed for the temporary implementation of `working_team` in the `Runtime`
+ */
+
+pub use types::BalanceOfCurrency;
+use types::{ApplicationInfo, MemberId, TeamWorker, TeamWorkerId, WorkerInfo};
 pub use types::{
     ApplyOnOpeningParameters, JobApplication, JobOpening, JobOpeningType, Penalty, RewardPolicy,
     StakePolicy, StakingHandler,

+ 1 - 0
runtime-modules/working-team/src/types.rs

@@ -4,6 +4,7 @@ use codec::{Decode, Encode};
 use common::currency::GovernanceCurrency;
 use frame_support::dispatch::DispatchResult;
 use frame_support::traits::Currency;
+use sp_std::vec::Vec;
 
 #[cfg(feature = "std")]
 use serde::{Deserialize, Serialize};

+ 13 - 8
runtime/Cargo.toml

@@ -10,6 +10,7 @@ version = '7.1.0'
 # Third-party dependencies
 serde = { version = "1.0.101", optional = true, features = ["derive"] }
 codec = { package = 'parity-scale-codec', version = '1.3.1', default-features = false, features = ['derive'] }
+hex-literal = { optional = true, version = '0.3.1' }
 
 # Substrate primitives
 sp-std = { package = 'sp-std', default-features = false, git = 'https://github.com/paritytech/substrate.git', rev = '00768a1f21a579c478fe5d4f51e1fa71f7db9fd4'}
@@ -69,6 +70,7 @@ hiring = { package = 'pallet-hiring', default-features = false, path = '../runti
 minting = { package = 'pallet-token-mint', default-features = false, path = '../runtime-modules/token-minting'}
 recurring-rewards = { package = 'pallet-recurring-reward', default-features = false, path = '../runtime-modules/recurring-reward'}
 working-group = { package = 'pallet-working-group', default-features = false, path = '../runtime-modules/working-group'}
+working-team = { package = 'pallet-working-team', default-features = false, path = '../runtime-modules/working-team'}
 content-working-group = { package = 'pallet-content-working-group', default-features = false, path = '../runtime-modules/content-working-group'}
 versioned-store = { package = 'pallet-versioned-store', default-features = false, path = '../runtime-modules/versioned-store'}
 versioned-store-permissions = { package = 'pallet-versioned-store-permissions', default-features = false, path = '../runtime-modules/versioned-store-permissions'}
@@ -144,6 +146,7 @@ std = [
     'minting/std',
     'recurring-rewards/std',
     'working-group/std',
+    'working-team/std',
     'content-working-group/std',
     'versioned-store/std',
     'versioned-store-permissions/std',
@@ -155,17 +158,19 @@ std = [
 ]
 runtime-benchmarks = [
     "system/runtime-benchmarks",
-	"frame-support/runtime-benchmarks",
-	"sp-runtime/runtime-benchmarks",
-	"pallet-balances/runtime-benchmarks",
-	"pallet-collective/runtime-benchmarks",
-	"pallet-im-online/runtime-benchmarks",
-	"pallet-staking/runtime-benchmarks",
-	"pallet-timestamp/runtime-benchmarks",
+    "frame-support/runtime-benchmarks",
+    "sp-runtime/runtime-benchmarks",
+    "pallet-balances/runtime-benchmarks",
+    "pallet-collective/runtime-benchmarks",
+    "pallet-im-online/runtime-benchmarks",
+    "pallet-staking/runtime-benchmarks",
+    "pallet-timestamp/runtime-benchmarks",
     "frame-benchmarking",
     "frame-system-benchmarking",
     "pallet-offences-benchmarking",
-	"pallet-session-benchmarking",
+    "pallet-session-benchmarking",
+    "working-team/runtime-benchmarks",
+    "hex-literal",
 ]
 
 

+ 88 - 0
runtime/src/lib.rs

@@ -65,6 +65,90 @@ pub use versioned_store;
 pub use versioned_store_permissions;
 pub use working_group;
 
+/*
+ * TODO: revert, used by temporary implementation for working_team for benchmark
+ * ====================== Starts here =========================================
+ */
+use frame_support::dispatch::DispatchResult;
+pub use working_team;
+use working_team::BalanceOfCurrency;
+pub type StorageWorkingTeamInstance = working_team::Instance1;
+
+parameter_types! {
+  pub const RewardPeriod: u32 = 3;
+  pub const MinUnstakingPeriodLimit: u32 = 3;
+}
+
+impl working_team::Trait<StorageWorkingTeamInstance> for Runtime {
+    type OpeningId = u64;
+    type ApplicationId = u64;
+    type Event = Event;
+    type MaxWorkerNumberLimit = MaxWorkerNumberLimit;
+    type StakingHandler = Runtime;
+    type MemberOriginValidator = MembershipOriginValidator<Self>;
+    type MinUnstakingPeriodLimit = MinUnstakingPeriodLimit;
+    type RewardPeriod = RewardPeriod;
+}
+
+impl working_team::StakingHandler<Runtime> for Runtime {
+    fn lock(
+        _account_id: &<Runtime as system::Trait>::AccountId,
+        _amount: BalanceOfCurrency<Runtime>,
+    ) {
+    }
+
+    fn unlock(_account_id: &<Runtime as system::Trait>::AccountId) {}
+
+    fn slash(
+        _account_id: &<Runtime as system::Trait>::AccountId,
+        _amount: Option<BalanceOfCurrency<Runtime>>,
+    ) -> BalanceOfCurrency<Runtime> {
+        0
+    }
+
+    fn decrease_stake(
+        _account_id: &<Runtime as system::Trait>::AccountId,
+        _new_stake: BalanceOfCurrency<Runtime>,
+    ) {
+    }
+
+    fn increase_stake(
+        _account_id: &<Runtime as system::Trait>::AccountId,
+        _new_stake: BalanceOfCurrency<Runtime>,
+    ) -> DispatchResult {
+        Ok(())
+    }
+
+    fn is_member_staking_account(
+        _member_id: &<Runtime as membership::Trait>::MemberId,
+        _account_id: &<Runtime as system::Trait>::AccountId,
+    ) -> bool {
+        true
+    }
+
+    fn is_account_free_of_conflicting_stakes(
+        _account_id: &<Runtime as system::Trait>::AccountId,
+    ) -> bool {
+        true
+    }
+
+    fn is_enough_balance_for_stake(
+        _account_id: &<Runtime as system::Trait>::AccountId,
+        _amount: BalanceOfCurrency<Runtime>,
+    ) -> bool {
+        true
+    }
+
+    fn current_stake(
+        _account_id: &<Runtime as system::Trait>::AccountId,
+    ) -> BalanceOfCurrency<Runtime> {
+        0
+    }
+}
+/*
+ * ====================== Ends here =========================================
+ */
+
 /// This runtime version.
 pub const VERSION: RuntimeVersion = RuntimeVersion {
     spec_name: create_runtime_str!("joystream-node"),
@@ -618,5 +702,9 @@ construct_runtime!(
         // --- Working groups
         // reserved for the future use: ForumWorkingGroup: working_group::<Instance1>::{Module, Call, Storage, Event<T>},
         StorageWorkingGroup: working_group::<Instance2>::{Module, Call, Storage, Config<T>, Event<T>},
+        /*
+         * TODO: revert, used by temporary implementation for working_team for benchmark
+         */
+        WorkingTeam: working_team::<Instance1>::{Module, Call, Storage, Event<T>},
     }
 );

+ 50 - 0
runtime/src/runtime_api.rs

@@ -8,6 +8,7 @@ use sp_core::crypto::KeyTypeId;
 use sp_core::OpaqueMetadata;
 use sp_runtime::traits::{BlakeTwo256, Block as BlockT, NumberFor};
 use sp_runtime::{generic, ApplyExtrinsicResult};
+use sp_std::vec;
 use sp_std::vec::Vec;
 
 use crate::constants::PRIMARY_PROBABILITY;
@@ -201,4 +202,53 @@ impl_runtime_apis! {
             SessionKeys::decode_into_raw_public_keys(&encoded)
         }
     }
+
+
+    #[cfg(feature = "runtime-benchmarks")]
+    impl frame_benchmarking::Benchmark<Block> for Runtime {
+        fn dispatch_benchmark(
+            pallet: Vec<u8>,
+            benchmark: Vec<u8>,
+            lowest_range_values: Vec<u32>,
+            highest_range_values: Vec<u32>,
+            steps: Vec<u32>,
+            repeat: u32,
+        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
+            /*
+             * TODO: remember to benchhmark every pallet
+             */
+            use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark};
+            use frame_system_benchmarking::Module as SystemBench;
+            impl frame_system_benchmarking::Trait for Runtime {}
+
+            use crate::WorkingTeam;
+
+            let whitelist: Vec<Vec<u8>> = vec![
+                // Block Number
+                // frame_system::Number::<Runtime>::hashed_key().to_vec(),
+                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec(),
+                // Total Issuance
+                hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec(),
+                // Execution Phase
+                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec(),
+                // Event Count
+                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec(),
+                // System Events
+                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec(),
+                // Caller 0 Account
+                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da946c154ffd9992e395af90b5b13cc6f295c77033fce8a9045824a6690bbf99c6db269502f0a8d1d2a008542d5690a0749").to_vec(),
+                // Treasury Account
+                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec(),
+            ];
+
+            let mut batches = Vec::<BenchmarkBatch>::new();
+            let params = (&pallet, &benchmark, &lowest_range_values, &highest_range_values, &steps, repeat, &whitelist);
+
+            add_benchmark!(params, batches, b"system", SystemBench::<Runtime>);
+            add_benchmark!(params, batches, b"working-team", WorkingTeam);
+
+            if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
+            Ok(batches)
+        }
+    }
 }