Skip to content

Commit

Permalink
Add flow benchmarks
Browse files Browse the repository at this point in the history
  • Loading branch information
vayesy committed Jun 16, 2022
1 parent e5d3570 commit a208070
Show file tree
Hide file tree
Showing 4 changed files with 311 additions and 38 deletions.
16 changes: 11 additions & 5 deletions flow/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ frame-system = { git = "https://github.com/paritytech/substrate", branch = "polk
frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.13", default-features = false, optional = true }

orml-traits = { path = "../../orml/traits", default-features = false }
orml-tokens = { path = "../../orml/tokens", optional = true }
orml-currencies = { path = "../../orml/currencies", optional = true }

gamedao-traits = { package = "gamedao-traits", path = "../traits", default-features = false }
gamedao-control = { package = "gamedao-control", path = "../control", optional = true }

[dev-dependencies]
sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.13" }
Expand All @@ -33,14 +37,14 @@ sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0
pallet-timestamp = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.13" }
pallet-balances = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.13" }

orml-tokens = { path = "../../orml/tokens", default-features = false }
orml-currencies = { path = "../../orml/currencies", default-features = false }

gamedao-control = { package = "gamedao-control", path = "../control", default-features = true }

[features]
default = ["std"]
runtime-benchmarks = ["frame-benchmarking"]
runtime-benchmarks = [
"frame-benchmarking",
"gamedao-traits/frame-benchmarking",
]
std = [
"codec/std",
"serde/std",
Expand All @@ -53,10 +57,12 @@ std = [
"sp-core/std",
"sp-std/std",
"sp-runtime/std",

"orml-traits/std",
"orml-tokens/std",
"orml-currencies/std",

"gamedao-traits/std",
"gamedao-control/std",
"gamedao-control/std",
]
try-runtime = ["frame-support/try-runtime"]
113 changes: 108 additions & 5 deletions flow/src/benchmarking.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,119 @@
//! Benchmarking setup for gamedao-flow
use super::*;

#[allow(unused)]
use crate::Pallet as Flow;
use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite};
use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, whitelisted_caller};
use frame_system::RawOrigin;
use sp_std::vec;
use sp_runtime::{DispatchError, traits::{Saturating}};
use sp_std::{vec};


fn fund_account<T: Config>(account_id: &T::AccountId, multiplier: Option<u32>) -> Result<(), DispatchError> {
let amount = T::MinContribution::get().saturating_mul(multiplier.unwrap_or(10).into());
T::Currency::deposit(T::ProtocolTokenId::get(), account_id, amount)?;
T::Currency::deposit(T::PaymentTokenId::get(), account_id, amount)?;
Ok(())
}

/// Fund accounts with tokens, needed for org interactions
fn fund_accounts<T: Config>(account_ids: &Vec<T::AccountId>, multiplier: Option<u32>) -> Result<(), DispatchError> {
for account_id in account_ids {
fund_account::<T>(&account_id, multiplier)?;
}
Ok(())
}

fn create_campaign_call<T: Config>(caller: T::AccountId, org_id: T::Hash) -> Result<T::Hash, &'static str> {
let name: Vec<u8> = vec![0; T::MaxNameLength::get() as usize];
let cid: Vec<u8> = vec![0; T::MaxNameLength::get() as usize];
let token_symbol: Vec<u8> = vec![0; 5];
let token_name: Vec<u8> = vec![0; 32];
Flow::<T>::create_campaign(
RawOrigin::Signed(caller.clone()).into(),
org_id,
caller.clone(),
name,
T::MinContribution::get(),
T::MinContribution::get(),
frame_system::Pallet::<T>::block_number() + 200_u32.into(),
Default::default(),
Default::default(),
cid,
token_name,
token_symbol
)?;
let nonce = Nonce::<T>::get() - 1u128;
Ok(T::Hashing::hash_of(&nonce))
}


benchmarks! {

simple_benchmark {}: {}
// <T as orml_tokens::Config>::Currency::set_balance(GameCurrencyId, &creator, 1000);
create_campaign {
let b in 0 .. T::MaxCampaignsPerBlock::get()-1; // already created campaigns at current block

let caller: T::AccountId = whitelisted_caller();
fund_account::<T>(&caller, None)?;
let org_id = T::Control::create_org(caller.clone().into())?;
let treasury_id = T::Control::org_treasury_account(&org_id);
fund_account::<T>(&treasury_id, None)?;
for i in 0..b {
create_campaign_call::<T>(caller.clone(), org_id.clone())?;
}
let count_before = CampaignsCount::<T>::get();

}: _(
RawOrigin::Signed(caller.clone()),
org_id,
caller.clone(),
vec![0; T::MaxNameLength::get() as usize],
T::MinContribution::get(),
T::MinContribution::get(),
200_u32.into(),
Default::default(),
Default::default(),
vec![0; T::MaxNameLength::get() as usize],
vec![0; 5],
vec![0; 32]
)
verify {
assert!(CampaignsCount::<T>::get() == count_before + 1);
}

update_state {
let caller: T::AccountId = whitelisted_caller();
fund_account::<T>(&caller, None)?;
let org_id = T::Control::create_org(caller.clone().into())?;
let treasury_id = T::Control::org_treasury_account(&org_id);
fund_account::<T>(&treasury_id, None)?;
let campaign_id = create_campaign_call::<T>(caller.clone(), org_id.clone())?;
let new_state = FlowState::Paused;
}: _(
RawOrigin::Signed(caller.clone()),
campaign_id,
new_state.clone()
)
verify {
assert!(CampaignState::<T>::get(&campaign_id) == new_state);
}

contribute {
let amount_to_contribute = T::MinContribution::get();
let owner: T::AccountId = whitelisted_caller();
let contributor: T::AccountId = account("contributor", 0, 0);
fund_accounts::<T>(&vec![owner.clone(), contributor.clone()], None)?;
let org_id = T::Control::create_org(owner.clone().into())?;
let treasury_id = T::Control::org_treasury_account(&org_id);
fund_account::<T>(&treasury_id, None)?;
let campaign_id = create_campaign_call::<T>(owner, org_id)?;
}: _(
RawOrigin::Signed(contributor.clone()),
campaign_id.clone(),
amount_to_contribute
)
verify {
assert!(CampaignContribution::<T>::contains_key((&campaign_id, &contributor)));
}

}

Expand Down
59 changes: 31 additions & 28 deletions flow/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// _______ ________ ________ ________ ______ _______ _______
// ╱╱ ╲╱ ╲╱ ╲╱ ╲_╱ ╲╲╱ ╲╲╱ ╲╲
// ╱╱ __╱ ╱ ╱ ╱ ╱╱ ╱╱ ╱╱
// ╱ ╱ ╱ ╱ ╱ _╱ ╱ ╱
// _______ ________ ________ ________ ______ _______ _______
// ╱╱ ╲╱ ╲╱ ╲╱ ╲_╱ ╲╲╱ ╲╲╱ ╲╲
// ╱╱ __╱ ╱ ╱ ╱ ╱╱ ╱╱ ╱╱
// ╱ ╱ ╱ ╱ ╱ _╱ ╱ ╱
// ╲________╱╲___╱____╱╲__╱__╱__╱╲________╱╲________╱╲___╱____╱╲________╱
//
// This file is part of GameDAO Protocol.
Expand Down Expand Up @@ -42,9 +42,9 @@ pub use types::*;

mod mock;
mod tests;

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

// TODO: weights
// mod default_weights;
Expand All @@ -53,8 +53,7 @@ mod tests;
// mod errors;

use frame_support::{
codec::Encode,
dispatch::DispatchResult,
dispatch::{DispatchResult, DispatchResultWithPostInfo},
traits::{Get, UnixTime, BalanceStatus},
transactional,
weights::Weight
Expand All @@ -67,10 +66,11 @@ use sp_std::vec::Vec;
use sp_std::convert::TryFrom;

use codec::HasCompact;
use gamedao_traits::{ControlTrait, FlowTrait};
use gamedao_traits::{ControlTrait, ControlBenchmarkingTrait, FlowTrait};
use orml_traits::{MultiCurrency, MultiReservableCurrency};

pub use pallet::*;
pub use weights::WeightInfo;

// TODO: use associated type instead
pub type Moment = u64;
Expand Down Expand Up @@ -112,15 +112,16 @@ pub mod pallet {
+ TypeInfo;

/// Weight information for extrinsics in this module.
type WeightInfo: frame_system::weights::WeightInfo;
type WeightInfo: WeightInfo;

/// Multi-currency support for asset management.
type Currency: MultiCurrency<Self::AccountId, CurrencyId = Self::CurrencyId, Balance = Self::Balance>
+ MultiReservableCurrency<Self::AccountId>;

type UnixTime: UnixTime;

type Control: ControlTrait<Self::AccountId, Self::Hash>;
type Control: ControlTrait<Self::AccountId, Self::Hash>
+ ControlBenchmarkingTrait<Self::AccountId, Self::Hash>;

/// The GameDAO Treasury AccountId.
#[pallet::constant]
Expand Down Expand Up @@ -486,13 +487,13 @@ pub mod pallet {
#[pallet::hooks]
impl<T: Config> Hooks<T::BlockNumber> for Pallet<T> {

fn on_initialize(block_number: T::BlockNumber) -> Weight {
fn on_initialize(block_number: T::BlockNumber) -> Weight {
let mut processed: u32 = 0;
Self::process_campaigns(&block_number, FlowState::Finalizing, &mut processed)
.saturating_add(
Self::process_campaigns(&block_number, FlowState::Reverting, &mut processed)
)
}
}

fn on_finalize(block_number: T::BlockNumber) {
Self::schedule_campaign_settlements(block_number)
Expand All @@ -519,7 +520,9 @@ pub mod pallet {
/// Emits `CampaignCreated` event when successful.
///
/// Weight: `O(1)`
#[pallet::weight(5_000_000)]
#[pallet::weight(T::WeightInfo::create_campaign(
T::MaxCampaignsPerBlock::get()
))]
#[transactional]
pub fn create_campaign(
origin: OriginFor<T>,
Expand All @@ -534,9 +537,9 @@ pub mod pallet {
cid: Vec<u8>,
token_symbol: Vec<u8>, // up to 5
token_name: Vec<u8>, /* cleartext
* token_curve_a: u8, // preset
* token_curve_b: Vec<u8>, // custom */
) -> DispatchResult {
* token_curve_a: u8, // preset
* token_curve_b: Vec<u8>, // custom */
) -> DispatchResultWithPostInfo {
let creator = ensure_signed(origin)?;
let owner = T::Control::org_controller_account(&org_id);
ensure!(creator == owner, Error::<T>::AuthorizationError);
Expand Down Expand Up @@ -572,9 +575,9 @@ pub mod pallet {
// for collision

// check contribution limit per block
let camapaigns = CampaignsByBlock::<T>::get(expiry);
let campaigns = CampaignsByBlock::<T>::get(expiry);
ensure!(
(camapaigns.len() as u32) < T::MaxCampaignsPerBlock::get(),
(campaigns.len() as u32) < T::MaxCampaignsPerBlock::get(),
Error::<T>::CampaignsPerBlockExceeded
);

Expand Down Expand Up @@ -612,7 +615,7 @@ pub mod pallet {
expiry,
name,
});
Ok(())
Ok(Some(T::WeightInfo::create_campaign(campaigns.len() as u32)).into())

// No fees are paid here if we need to create this account;
// that's why we don't just use the stock `transfer`.
Expand All @@ -627,8 +630,8 @@ pub mod pallet {
///
/// Emits `CampaignUpdated` event when successful.
///
/// Weight:
#[pallet::weight(1_000_000)]
/// Weight: O(1)
#[pallet::weight(T::WeightInfo::update_state())]
pub fn update_state(origin: OriginFor<T>, campaign_id: T::Hash, state: FlowState) -> DispatchResult {
// access control
let sender = ensure_signed(origin)?;
Expand Down Expand Up @@ -665,8 +668,8 @@ pub mod pallet {
///
/// Emits `CampaignContributed` event when successful.
///
/// Weight:
#[pallet::weight(5_000_000)]
/// Weight: O(1)
#[pallet::weight(T::WeightInfo::contribute())]
pub fn contribute(origin: OriginFor<T>, campaign_id: T::Hash, contribution: T::Balance) -> DispatchResult {
// check

Expand Down Expand Up @@ -859,7 +862,7 @@ impl<T: Config> Pallet<T> {

fn process_campaigns(block_number: &T::BlockNumber, state: FlowState, processed: &mut u32) -> Weight {
let campaign_ids = CampaignsByState::<T>::get(&state);
let total_weight: Weight = 0;
let mut total_weight: Weight = 0;
for campaign_id in campaign_ids {
let campaign = Campaigns::<T>::get(campaign_id);
let campaign_balance = CampaignBalance::<T>::get(campaign_id);
Expand All @@ -869,14 +872,14 @@ impl<T: Config> Pallet<T> {

if state == FlowState::Finalizing {
if let Some(owner) = CampaignOwner::<T>::get(campaign.id) {
total_weight.saturating_add(
total_weight = total_weight.saturating_add(
Self::finalize_campaign(&block_number, processed, &campaign, &campaign_balance, &org, &org_treasury, &contributors, &owner)
);
} else {
// TODO: If no campaign owner: revert the campaign or leave it as is?
}
} else if state == FlowState::Reverting {
total_weight.saturating_add(
total_weight = total_weight.saturating_add(
Self::revert_campaign(&block_number, processed, &campaign, &campaign_balance, &org, &org_treasury, &contributors)
);
}
Expand Down
Loading

0 comments on commit a208070

Please sign in to comment.