Skip to content

Commit

Permalink
benchmarking
Browse files Browse the repository at this point in the history
  • Loading branch information
TarekkMA committed Oct 27, 2022
1 parent fa387e0 commit e472c50
Show file tree
Hide file tree
Showing 9 changed files with 317 additions and 47 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

53 changes: 48 additions & 5 deletions pallets/roles/src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ impl<T: Config> Pallet<T> {
for role_id in role_ids {
if let Some(role) = Self::role_by_id(role_id) {
if role.disabled {
continue;
continue
}

let mut is_expired = false;
Expand All @@ -104,14 +104,45 @@ impl<T: Config> Pallet<T> {
}

if !is_expired && role.permissions.contains(&permission) {
return Ok(());
return Ok(())
}
}
}

Err(error)
}

pub fn do_create_role(
space_owner: &T::AccountId,
space_id: SpaceId,
time_to_live: Option<T::BlockNumber>,
content: Content,
permissions: Vec<SpacePermission>,
) -> Result<RoleId, DispatchError> {
ensure!(!permissions.is_empty(), Error::<T>::NoPermissionsProvided);

ensure_content_is_valid(content.clone())?;
ensure!(
T::IsContentBlocked::is_allowed_content(content.clone(), space_id),
ModerationError::ContentIsBlocked,
);

Self::ensure_role_manager(space_owner.clone(), space_id)?;

let permissions_set = permissions.into_iter().collect();
let new_role =
Role::<T>::new(space_owner.clone(), space_id, time_to_live, content, permissions_set)?;

// TODO review strange code:
let next_role_id = new_role.id.checked_add(1).ok_or(Error::<T>::RoleIdOverflow)?;
NextRoleId::<T>::put(next_role_id);

RoleById::<T>::insert(new_role.id, new_role.clone());
RoleIdsBySpaceId::<T>::mutate(space_id, |role_ids| role_ids.push(new_role.id));

Ok(new_role.id)
}

pub fn do_grant_role(
manager: Option<T::AccountId>,
role_id: RoleId,
Expand Down Expand Up @@ -180,9 +211,9 @@ impl<T: Config> Role<T> {

pub fn set_disabled(&mut self, disable: bool) -> DispatchResult {
if self.disabled && disable {
return Err(Error::<T>::RoleAlreadyDisabled.into());
return Err(Error::<T>::RoleAlreadyDisabled.into())
} else if !self.disabled && !disable {
return Err(Error::<T>::RoleAlreadyEnabled.into());
return Err(Error::<T>::RoleAlreadyEnabled.into())
}

self.disabled = disable;
Expand Down Expand Up @@ -225,7 +256,9 @@ impl<T: Config> PermissionChecker for Pallet<T> {
}
}

impl<T: Config> RolesInterface<RoleId, SpaceId, T::AccountId> for Pallet<T> {
impl<T: Config> RolesInterface<RoleId, SpaceId, T::AccountId, SpacePermission, T::BlockNumber>
for Pallet<T>
{
fn get_role_space(role_id: RoleId) -> Result<SpaceId, DispatchError> {
let role = Pallet::<T>::require_role(role_id)?;
Ok(role.space_id)
Expand All @@ -234,4 +267,14 @@ impl<T: Config> RolesInterface<RoleId, SpaceId, T::AccountId> for Pallet<T> {
fn grant_role(account_id: T::AccountId, role_id: RoleId) -> DispatchResult {
Pallet::<T>::do_grant_role(None, role_id, vec![User::Account(account_id)])
}

fn create_role(
space_owner: &T::AccountId,
space_id: SpaceId,
time_to_live: Option<T::BlockNumber>,
content: Content,
permissions: Vec<SpacePermission>,
) -> Result<RoleId, DispatchError> {
Pallet::<T>::do_create_role(space_owner, space_id, time_to_live, content, permissions)
}
}
38 changes: 8 additions & 30 deletions pallets/roles/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
#![cfg_attr(not(feature = "std"), no_std)]

use codec::{Decode, Encode};
use frame_support::{dispatch::DispatchResult, ensure, traits::Get};
use frame_system::{self as system, ensure_signed};
use frame_support::{dispatch::DispatchResult, ensure};
use frame_system as system;
use scale_info::TypeInfo;
use sp_runtime::RuntimeDebug;
use sp_std::{collections::btree_set::BTreeSet, prelude::*};
Expand Down Expand Up @@ -182,32 +182,10 @@ pub mod pallet {
) -> DispatchResult {
let who = ensure_signed(origin)?;

ensure!(!permissions.is_empty(), Error::<T>::NoPermissionsProvided);
let role_id =
Pallet::<T>::do_create_role(&who, space_id, time_to_live, content, permissions)?;

ensure_content_is_valid(content.clone())?;
ensure!(
T::IsContentBlocked::is_allowed_content(content.clone(), space_id),
ModerationError::ContentIsBlocked,
);

Self::ensure_role_manager(who.clone(), space_id)?;

let permissions_set = permissions.into_iter().collect();
let new_role =
Role::<T>::new(who.clone(), space_id, time_to_live, content, permissions_set)?;

// TODO review strange code:
let next_role_id = new_role.id.checked_add(1).ok_or(Error::<T>::RoleIdOverflow)?;
NextRoleId::<T>::put(next_role_id);

RoleById::<T>::insert(new_role.id, new_role.clone());
RoleIdsBySpaceId::<T>::mutate(space_id, |role_ids| role_ids.push(new_role.id));

Self::deposit_event(Event::RoleCreated {
account: who,
space_id,
role_id: new_role.id,
});
Self::deposit_event(Event::RoleCreated { account: who, space_id, role_id });
Ok(())
}

Expand All @@ -221,9 +199,9 @@ pub mod pallet {
) -> DispatchResult {
let who = ensure_signed(origin)?;

let has_updates = update.disabled.is_some()
|| update.content.is_some()
|| update.permissions.is_some();
let has_updates = update.disabled.is_some() ||
update.content.is_some() ||
update.permissions.is_some();

ensure!(has_updates, Error::<T>::NoUpdatesProvided);

Expand Down
4 changes: 4 additions & 0 deletions pallets/subscriptions/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ frame-support = { git = "https://github.com/paritytech/substrate", branch = "pol
frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false }
pallet-balances = { git = 'https://github.com/paritytech/substrate', branch = 'polkadot-v0.9.24', default-features = false }

subsocial-support = { default-features = false, path = '../support' }
pallet-permissions = { default-features = false, path = '../permissions' }

[dev-dependencies]
pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false }
Expand All @@ -44,6 +46,8 @@ std = [
"frame-benchmarking/std",
"frame-support/std",
"frame-system/std",
"pallet-balances/std",
"pallet-permissions/std",
"sp-runtime/std",
"sp-std/std",
"subsocial-support/std",
Expand Down
111 changes: 111 additions & 0 deletions pallets/subscriptions/src/benchmarking.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
use frame_benchmarking::{account, benchmarks};
use frame_support::{
ensure,
sp_runtime::traits::{Bounded, Saturating},
traits::{Currency, Get},
};
use frame_system::RawOrigin;
use sp_std::vec;

use pallet_permissions::SpacePermission;
use subsocial_support::{
mock_functions::valid_content_ipfs,
traits::{RolesInterface, SpacesInterface},
Content,
};

use crate::types::{SubscriberInfo, SubscriptionSettings};

use super::*;

fn ed_multiplied_by<T: pallet_balances::Config + Config>(multiplier: u32) -> BalanceOf<T>
where
BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
{
T::ExistentialDeposit::get().saturating_mul(multiplier.into()).into()
}

benchmarks! {
where_clause { where
T: pallet_balances::Config,
BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
}

update_subscription_settings {
let owner: T::AccountId = account("owner", 24, 0);
let space_id = T::SpacesInterface::create_space(&owner, valid_content_ipfs())?;
let role_id = T::RolesInterface::create_role(
&owner,
space_id,
None,
Content::None,
vec![
SpacePermission::CreatePosts,
SpacePermission::UpdateOwnPosts,
SpacePermission::UpdateAnyPost,
SpacePermission::UpdateEntityStatus,
],
)?;

let settings = SubscriptionSettings::<BalanceOf<T>, T::RoleId> {
subscription: ed_multiplied_by::<T>(10),
disabled: false,
role_id: role_id,
};
}: _(RawOrigin::Signed(owner.clone()), space_id, settings.clone())
verify {
let maybe_settings = SubscriptionSettingsBySpace::<T>::get(space_id);
ensure!(maybe_settings == Some(settings), "Settings isn't updated");
}

subscribe {
let owner: T::AccountId = account("owner", 24, 0);
let space_id = T::SpacesInterface::create_space(&owner, valid_content_ipfs())?;
let role_id = T::RolesInterface::create_role(
&owner,
space_id,
None,
Content::None,
vec![
SpacePermission::CreatePosts,
SpacePermission::UpdateOwnPosts,
SpacePermission::UpdateAnyPost,
SpacePermission::UpdateEntityStatus,
],
)?;

SubscriptionSettingsBySpace::<T>::insert(space_id, SubscriptionSettings::<BalanceOf<T>, T::RoleId> {
subscription: ed_multiplied_by::<T>(15),
disabled: false,
role_id: role_id,
});

let subscriber: T::AccountId = account("subscriber", 24, 0);
<T as Config>::Currency::make_free_balance_be(&subscriber, BalanceOf::<T>::max_value());
}: _(RawOrigin::Signed(subscriber.clone()), space_id)
verify {
let info = SpaceSubscribers::<T>::get(space_id, subscriber).ok_or("Info wasn't set")?;
ensure!(info.subscription == ed_multiplied_by::<T>(15), "subscription didn't match");
ensure!(info.granted_role_id == role_id, "granted_role_id didn't match");
ensure!(!info.unsubscribed, "account should be subscribed");
}


unsubscribe {
let subscriber: T::AccountId = account("subscriber", 24, 0);
let space_id = T::SpaceId::default();
let role_id = T::RoleId::default();

SpaceSubscribers::<T>::insert(space_id.clone(), subscriber.clone(), SubscriberInfo::<BalanceOf<T>, T::RoleId, T::BlockNumber> {
subscribed_on: <frame_system::Pallet<T>>::block_number(),
subscription: ed_multiplied_by::<T>(3),
granted_role_id: role_id,
unsubscribed: false,
});
}: _(RawOrigin::Signed(subscriber.clone()), space_id.clone())
verify {
let info = SpaceSubscribers::<T>::get(space_id, subscriber).ok_or("Info wasn't set")?;
ensure!(info.unsubscribed, "account should be unsubscribed");
}

}
38 changes: 27 additions & 11 deletions pallets/subscriptions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,25 @@

pub use pallet::*;

pub use crate::weights::WeightInfo;

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
mod types;
pub mod weights;

#[frame_support::pallet]
pub mod pallet {
use std::fmt::Debug;

use codec::EncodeLike;
use frame_support::fail;
use frame_support::pallet_prelude::*;
use frame_support::traits::{Currency, ExistenceRequirement};
use frame_support::{
fail,
pallet_prelude::*,
traits::{Currency, ExistenceRequirement},
};
use frame_system::pallet_prelude::*;
use sp_std::fmt::Debug;

use pallet_permissions::SpacePermission;
use subsocial_support::traits::{RolesInterface, SpacesInterface};

use crate::types::*;
Expand All @@ -32,13 +39,22 @@ pub mod pallet {
/// The currency trait.
type Currency: Currency<Self::AccountId>;

type SpaceId: MaxEncodedLen + Copy + Decode + TypeInfo + EncodeLike + Eq + Debug;
type SpaceId: MaxEncodedLen + Copy + Decode + TypeInfo + EncodeLike + Eq + Debug + Default;

type SpacesInterface: SpacesInterface<Self::AccountId, Self::SpaceId>;

type RoleId: MaxEncodedLen + Copy + Decode + TypeInfo + EncodeLike + Eq + Debug;
type RoleId: MaxEncodedLen + Copy + Decode + TypeInfo + EncodeLike + Eq + Debug + Default;

type RolesInterface: RolesInterface<
Self::RoleId,
Self::SpaceId,
Self::AccountId,
SpacePermission,
Self::BlockNumber,
>;

type RolesInterface: RolesInterface<Self::RoleId, Self::SpaceId, Self::AccountId>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
}

#[pallet::pallet]
Expand Down Expand Up @@ -105,7 +121,7 @@ pub mod pallet {
// // Set up a subscriptions settings for the first time.
// }

#[pallet::weight(100_000_000)]
#[pallet::weight(< T as Config >::WeightInfo::update_subscription_settings())]
pub fn update_subscription_settings(
origin: OriginFor<T>,
space_id: T::SpaceId,
Expand Down Expand Up @@ -133,7 +149,7 @@ pub mod pallet {
Ok(())
}

#[pallet::weight(100_000_000)]
#[pallet::weight(< T as Config >::WeightInfo::subscribe())]
pub fn subscribe(origin: OriginFor<T>, space_id: T::SpaceId) -> DispatchResult {
let subscriber = ensure_signed(origin)?;

Expand Down Expand Up @@ -179,7 +195,7 @@ pub mod pallet {
Ok(())
}

#[pallet::weight(100_000_000)]
#[pallet::weight(< T as Config >::WeightInfo::unsubscribe())]
pub fn unsubscribe(origin: OriginFor<T>, space_id: T::SpaceId) -> DispatchResult {
let subscriber = ensure_signed(origin)?;

Expand Down
Loading

0 comments on commit e472c50

Please sign in to comment.