Browse Source

Add membership benchmarking to the runtime, complete buy_membership_with_referrer branch

iorveth 4 years ago
parent
commit
815723e7c2

+ 82 - 59
runtime-modules/membership/src/benchmarking.rs

@@ -15,12 +15,13 @@ use frame_system::{EventRecord, RawOrigin};
 use sp_arithmetic::traits::{One, Zero};
 use sp_runtime::traits::Bounded;
 use sp_std::collections::btree_set::BTreeSet;
+use sp_std::prelude::*;
 
 /// Balance alias for `balances` module.
 pub type BalanceOf<T> = <T as balances::Trait>::Balance;
 
 const SEED: u32 = 0;
-const MAX_BYTES: u32 = 255;
+const MAX_BYTES: u32 = 16384;
 
 fn get_byte(num: u32, byte_number: u8) -> u8 {
     ((num & (0xff << (8 * byte_number))) >> 8 * byte_number) as u8
@@ -76,15 +77,13 @@ fn assert_last_event<T: Trait>(generic_event: <T as Trait>::Event) {
 // Method to generate a distintic valid handle
 // for a membership. For each index.
 fn handle_from_id<T: Trait>(id: u32) -> Vec<u8> {
-    let min_handle_length = 1;
-
     let mut handle = vec![];
 
-    for i in 0..4 {
-        handle.push(get_byte(id, i));
+    for j in 0..4 {
+        handle.push(get_byte(id, j));
     }
 
-    while handle.len() < (min_handle_length as usize) {
+    while handle.len() < (id as usize) {
         handle.push(0u8);
     }
 
@@ -103,7 +102,7 @@ benchmarks! {
 
         let account_id = account::<T::AccountId>("member", member_id, SEED);
 
-        let handle = handle_from_id::<T>(member_id);
+        let handle = handle_from_id::<T>(i);
 
         let member_id = T::MemberId::from(member_id.try_into().unwrap());
 
@@ -152,52 +151,76 @@ benchmarks! {
         assert_last_event::<T>(RawEvent::MemberRegistered(member_id).into());
     }
 
-    // buy_membership_with_referrer{
-
-    //     let i in 1 .. MAX_BYTES;
-
-    //     let account_id = account::<T::AccountId>(name, id, SEED);
-
-    //     let handle = handle_from_id::<T>(id, i);
-
-    //     let _ = Balances::<T>::make_free_balance_be(&account_id, BalanceOf::<T>::max_value());
-
-    //     let params = membership::BuyMembershipParameters {
-    //         root_account: account_id.clone(),
-    //         controller_account: account_id.clone(),
-    //         name: None,
-    //         handle: Some(handle),
-    //         avatar_uri: None,
-    //         about: None,
-    //         referrer_id: None,
-    //     };
-
-    // }: buy_membership(RawOrigin::Signed(account_id), params)
-    // verify {
-
-    //     let new_category = Category {
-    //         title_hash: T::calculate_hash(title.as_slice()),
-    //         description_hash: T::calculate_hash(description.as_slice()),
-    //         archived: false,
-    //         num_direct_subcategories: 0,
-    //         num_direct_threads: 0,
-    //         num_direct_moderators: 0,
-    //         parent_category_id,
-    //         sticky_thread_ids: vec![],
-    //     };
-
-    //     let category_id = Module::<T>::next_category_id() - T::CategoryId::one();
-    //     assert_eq!(Module::<T>::category_by_id(category_id), new_category);
-    //     assert_eq!(<Module<T>>::category_counter(), category_counter + T::CategoryId::one());
-
-    //     if let (Some(parent_category), Some(parent_category_id)) = (parent_category, parent_category_id) {
-    //         assert_eq!(
-    //             Module::<T>::category_by_id(parent_category_id).num_direct_subcategories,
-    //             parent_category.num_direct_subcategories + 1
-    //         );
-    //     }
-    //     assert_last_event::<T>(RawEvent::CategoryCreated(category_id).into());
-    // }
+    buy_membership_with_referrer{
+
+        let i in 0 .. MAX_BYTES;
+
+        let member_id = 0;
+
+        let account_id = account::<T::AccountId>("member", member_id, SEED);
+
+        let handle = handle_from_id::<T>(i);
+
+        let _ = Balances::<T>::make_free_balance_be(&account_id, BalanceOf::<T>::max_value());
+
+        let fee = Module::<T>::membership_price();
+
+        let mut params = BuyMembershipParameters {
+            root_account: account_id.clone(),
+            controller_account: account_id.clone(),
+            name: None,
+            handle: Some(handle.clone()),
+            avatar_uri: None,
+            about: None,
+            referrer_id: None,
+        };
+
+        let referral_cut: BalanceOf<T> = 1.into();
+
+        Module::<T>::set_referral_cut(RawOrigin::Root.into(), referral_cut);
+
+        Module::<T>::buy_membership(RawOrigin::Signed(account_id.clone()).into(), params.clone());
+
+        let member_id = T::MemberId::from(member_id.try_into().unwrap());
+
+        params.referrer_id = Some(member_id);
+        let second_handle = handle_from_id::<T>(i + 1);
+
+        params.handle = Some(second_handle.clone());
+
+        let free_balance = Balances::<T>::free_balance(&account_id.clone());
+
+    }: buy_membership(RawOrigin::Signed(account_id.clone()), params)
+    verify {
+
+        assert_eq!(Module::<T>::members_created(), member_id + T::MemberId::one() + T::MemberId::one());
+
+        // Same account id gets reward for being referral.
+        assert_eq!(Balances::<T>::free_balance(&account_id.clone()), free_balance - fee + referral_cut);
+
+        let handle_hash = T::Hashing::hash(&second_handle).as_ref().to_vec();
+
+        let membership: Membership<T> = MembershipObject {
+            handle_hash: handle_hash.clone(),
+            root_account: account_id.clone(),
+            controller_account: account_id.clone(),
+            verified: false,
+            // Save the updated profile.
+            invites: 5,
+        };
+
+        let second_member_id = member_id + T::MemberId::one();
+
+        assert_eq!(MemberIdsByRootAccountId::<T>::get(account_id.clone()), vec![member_id, second_member_id]);
+
+        assert_eq!(MemberIdsByControllerAccountId::<T>::get(account_id.clone()), vec![member_id, second_member_id]);
+
+        assert_eq!(MembershipById::<T>::get(second_member_id), membership);
+
+        assert_eq!(Module::<T>::handles(handle_hash), second_member_id);
+
+        assert_last_event::<T>(RawEvent::MemberRegistered(second_member_id).into());
+    }
 }
 
 #[cfg(test)]
@@ -206,12 +229,12 @@ mod tests {
     use crate::tests::*;
     use frame_support::assert_ok;
 
-    // #[test]
-    // fn buy_membership_with_referrer() {
-    //     with_test_externalities(|| {
-    //         assert_ok!(test_benchmark_buy_membership_with_referrer::<Runtime>());
-    //     });
-    // }
+    #[test]
+    fn buy_membership_with_referrer() {
+        with_test_externalities(|| {
+            assert_ok!(test_benchmark_buy_membership_with_referrer::<Runtime>());
+        });
+    }
 
     #[test]
     fn buy_membership_without_referrer() {

+ 2 - 2
runtime-modules/membership/src/lib.rs

@@ -43,11 +43,11 @@
 // Ensure we're `no_std` when compiling for Wasm.
 #![cfg_attr(not(feature = "std"), no_std)]
 
+pub mod benchmarking;
+
 pub mod genesis;
 mod tests;
 
-mod benchmarking;
-
 use codec::{Decode, Encode};
 use frame_support::traits::{Currency, Get};
 use frame_support::{decl_error, decl_event, decl_module, decl_storage, ensure};

+ 1 - 0
runtime/Cargo.toml

@@ -168,6 +168,7 @@ runtime-benchmarks = [
     "pallet_constitution/runtime-benchmarks",
     "working-group/runtime-benchmarks",
     "forum/runtime-benchmarks",
+    "membership/runtime-benchmarks",
     "council/runtime-benchmarks",
     "referendum/runtime-benchmarks",
     "hex-literal",

+ 2 - 0
runtime/src/runtime_api.rs

@@ -264,6 +264,7 @@ impl_runtime_apis! {
             use crate::ProposalsEngine;
             use crate::Constitution;
             use crate::Forum;
+            use crate::Members;
             use crate::ContentDirectoryWorkingGroup;
             use crate::Utility;
             use crate::Timestamp;
@@ -330,6 +331,7 @@ impl_runtime_apis! {
             // Joystream Benchmarks
             add_benchmark!(params, batches, proposals_discussion, ProposalsDiscussion);
             add_benchmark!(params, batches, proposals_engine, ProposalsEngine);
+            add_benchmark!(params, batches, membership, Members);
             add_benchmark!(params, batches, forum, Forum);
             add_benchmark!(params, batches, pallet_constitution, Constitution);
             add_benchmark!(params, batches, working_group, ContentDirectoryWorkingGroup);

+ 10 - 9
scripts/generate-weights.sh

@@ -34,8 +34,8 @@ benchmark() {
 # So uncomment this when we move to a version that contains that PR.
 # See issue: #1979
 # benchmark frame_system
-benchmark pallet_utility
-benchmark pallet_session
+# benchmark pallet_utility
+# benchmark pallet_session
 # benchmark pallet_timestamp
 
 # This benchmark takes too long with 50 steps and 20 repeats in a normal laptop.
@@ -45,10 +45,11 @@ benchmark pallet_session
 # benchmark pallet_im_online
 
 # Joystrem benchmarks
-benchmark proposals_discussion
-benchmark proposals_engine
-benchmark pallet_constitution
-benchmark working_group
-benchmark forum
-benchmark council
-benchmark referendum
+# benchmark proposals_discussion
+# benchmark proposals_engine
+# benchmark pallet_constitution
+# benchmark working_group
+# benchmark forum
+benchmark membership
+# benchmark council
+# benchmark referendum