Skip to content

Commit

Permalink
events for inflation rewards and benchmark for rewards
Browse files Browse the repository at this point in the history
  • Loading branch information
girazoki committed Oct 18, 2023
1 parent 38b8fb2 commit dc42ba4
Show file tree
Hide file tree
Showing 8 changed files with 146 additions and 27 deletions.
53 changes: 41 additions & 12 deletions pallets/inflation-rewards/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@ pub mod pallet {
// Let the runtime handle the non-staking part
T::OnUnbalanced::on_unbalanced(not_distributed_rewards.merge(total_reminder));

// Reward orchestrator chain author
weight += Self::reward_orchestrator_author();

weight
Expand All @@ -126,6 +125,9 @@ pub mod pallet {

#[pallet::config]
pub trait Config: frame_system::Config {
/// Overarching event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

type Currency: Inspect<Self::AccountId> + Balanced<Self::AccountId>;

type ContainerChains: GetCurrentContainerChains;
Expand All @@ -152,6 +154,22 @@ pub mod pallet {
type RewardsPortion: Get<Perbill>;
}

#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Rewarding orchestrator author
RewardedOrchestrator {
account_id: T::AccountId,
balance: BalanceOf<T>,
},
/// Rewarding container author
RewardedContainer {
account_id: T::AccountId,
para_id: ParaId,
balance: BalanceOf<T>,
},
}

/// Container chains to reward per block
#[pallet::storage]
#[pallet::getter(fn container_chains_to_reward)]
Expand All @@ -175,7 +193,7 @@ pub mod pallet {
if let Some(chains_to_reward) = ChainsToReward::<T>::get() {
total_weight += T::DbWeight::get().reads(1);
match T::StakingRewardsDistributor::distribute_rewards(
orchestrator_author,
orchestrator_author.clone(),
T::Currency::withdraw(
&T::PendingRewardsAccount::get(),
chains_to_reward.rewards_per_chain,
Expand All @@ -185,14 +203,19 @@ pub mod pallet {
)
.unwrap_or(CreditOf::<T>::zero()),
) {
Ok(frame_support::dispatch::PostDispatchInfo {
actual_weight: Some(weight),
..
}) => total_weight += weight,
Ok(frame_support::dispatch::PostDispatchInfo { actual_weight, .. }) => {
Self::deposit_event(Event::RewardedOrchestrator {
account_id: orchestrator_author,
balance: chains_to_reward.rewards_per_chain,
});

if let Some(weight) = actual_weight {
total_weight += weight
}
}
Err(e) => {
log::debug!("Fail to distribute rewards: {:?}", e)
}
_ => {}
}
} else {
panic!("ChainsToReward not filled");
Expand All @@ -207,6 +230,7 @@ pub mod pallet {
// There will be no additional check other than checking if we have already
// rewarded this author for **in this tanssi block**
// Any additional check should be done in the calling function
// TODO: consider passing a vector here
impl<T: Config> AuthorNotingHook<T::AccountId> for Pallet<T> {
fn on_container_author_noted(
author: &T::AccountId,
Expand All @@ -230,14 +254,19 @@ impl<T: Config> AuthorNotingHook<T::AccountId> for Pallet<T> {
)
.unwrap_or(CreditOf::<T>::zero()),
) {
Ok(frame_support::dispatch::PostDispatchInfo {
actual_weight: Some(weight),
..
}) => total_weight += weight,
Ok(frame_support::dispatch::PostDispatchInfo { actual_weight, .. }) => {
Self::deposit_event(Event::RewardedContainer {
account_id: author.clone(),
balance: container_chains_to_reward.rewards_per_chain,
para_id,
});
if let Some(weight) = actual_weight {
total_weight += weight
}
}
Err(e) => {
log::debug!("Fail to distribute rewards: {:?}", e)
}
_ => {}
}
// we remove the para id from container-chains to reward
// this makes sure we dont reward it twice in the same block
Expand Down
45 changes: 38 additions & 7 deletions pallets/invulnerables/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,18 @@ use super::*;

#[allow(unused)]
use crate::Pallet as InvulnerablesPallet;
use sp_runtime::traits::AtLeast32BitUnsigned;
use {
frame_benchmarking::{account, impl_benchmark_test_suite, v2::*, BenchmarkError},
frame_support::{
pallet_prelude::*,
traits::{Currency, EnsureOrigin, Get},
traits::{tokens::fungible::Balanced, Currency, EnsureOrigin, Get},
},
frame_system::{EventRecord, RawOrigin},
pallet_session::{self as session, SessionManager},
sp_std::prelude::*,
tp_traits::DistributeRewards,
};

const SEED: u32 = 0;

fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
Expand Down Expand Up @@ -94,7 +95,18 @@ fn invulnerables<
invulnerables.into_iter().map(|(who, _)| who).collect()
}

#[benchmarks(where T: session::Config + pallet_balances::Config)]
pub type BalanceOf<T> =
<<T as crate::Config>::Currency as frame_support::traits::fungible::Inspect<
<T as frame_system::Config>::AccountId,
>>::Balance;

pub(crate) fn currency_issue<T: Config + frame_system::Config>(
amount: BalanceOf<T>,
) -> crate::CreditOf<T, T::Currency> {
<<T as crate::Config>::Currency as Balanced<T::AccountId>>::issue(amount)
}

#[benchmarks(where T: session::Config + pallet_balances::Config, BalanceOf<T>: AtLeast32BitUnsigned)]
mod benchmarks {
use super::*;

Expand All @@ -106,16 +118,14 @@ mod benchmarks {
T::UpdateOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;

let new_invulnerables = invulnerables::<T>(b);
let mut sorted_new_invulnerables = new_invulnerables.clone();
sorted_new_invulnerables.sort();

#[extrinsic_call]
_(origin as T::RuntimeOrigin, new_invulnerables);
_(origin as T::RuntimeOrigin, new_invulnerables.clone());

// assert that it comes out sorted
assert_last_event::<T>(
Event::NewInvulnerables {
invulnerables: sorted_new_invulnerables,
invulnerables: new_invulnerables,
}
.into(),
);
Expand Down Expand Up @@ -196,6 +206,27 @@ mod benchmarks {
Ok(())
}

#[benchmark]
fn reward_invulnerable(
b: Linear<{ 1 }, { T::MaxInvulnerables::get() }>,
) -> Result<(), BenchmarkError> where {
let mut invulnerables = invulnerables::<T>(b);
invulnerables.sort();
let invulnerables: frame_support::BoundedVec<_, T::MaxInvulnerables> =
frame_support::BoundedVec::try_from(invulnerables).unwrap();
<Invulnerables<T>>::put(invulnerables);
let to_reward = <Invulnerables<T>>::get().first().unwrap().clone();
// Create new supply for rewards
let new_supply = currency_issue::<T>(1000u32.into());
#[block]
{
let _ = InvulnerableRewardDistribution::<T, T::Currency, ()>::distribute_rewards(
to_reward, new_supply,
);
}

Ok(())
}
impl_benchmark_test_suite!(
InvulnerablesPallet,
crate::mock::new_test_ext(),
Expand Down
25 changes: 20 additions & 5 deletions pallets/invulnerables/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ pub mod weights;
#[frame_support::pallet]
pub mod pallet {
pub use crate::weights::WeightInfo;
#[cfg(feature = "runtime-benchmarks")]
use frame_support::traits::Currency;
use {
frame_support::{
dispatch::DispatchResultWithPostInfo,
Expand Down Expand Up @@ -92,6 +94,10 @@ pub mod pallet {

/// The weight information of this pallet.
type WeightInfo: WeightInfo;

#[cfg(feature = "runtime-benchmarks")]
type Currency: Currency<Self::AccountId>
+ frame_support::traits::fungible::Balanced<Self::AccountId>;
}

#[pallet::pallet]
Expand Down Expand Up @@ -290,6 +296,9 @@ pub struct InvulnerableRewardDistribution<Runtime, Currency, Fallback>(
PhantomData<(Runtime, Currency, Fallback)>,
);

use frame_support::pallet_prelude::Weight;
use sp_runtime::traits::Get;

type CreditOf<Runtime, Currency> =
frame_support::traits::fungible::Credit<<Runtime as frame_system::Config>::AccountId, Currency>;
pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
Expand All @@ -306,12 +315,18 @@ where
rewarded: AccountIdOf<Runtime>,
amount: CreditOf<Runtime, Currency>,
) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
let mut total_weight = Weight::zero();
// weight to read invulnerables
total_weight += Runtime::DbWeight::get().reads(1);
if !Invulnerables::<Runtime>::get().contains(&rewarded) {
return Fallback::distribute_rewards(rewarded, amount);
let post_info = Fallback::distribute_rewards(rewarded, amount)?;
if let Some(weight) = post_info.actual_weight {
total_weight += weight;
}
} else {
Currency::resolve(&rewarded, amount).map_err(|_| TokenError::NotExpendable)?;
total_weight += Runtime::WeightInfo::reward_invulnerable()
}

Currency::resolve(&rewarded, amount).map_err(|_| TokenError::NotExpendable)?;

Ok(().into())
Ok(Some(total_weight).into())
}
}
2 changes: 2 additions & 0 deletions pallets/invulnerables/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ impl Config for Test {
type CollatorIdOf = IdentityCollator;
type CollatorRegistration = IsRegistered;
type WeightInfo = ();
#[cfg(feature = "runtime-benchmarks")]
type Currency = Balances;
}

sp_runtime::impl_opaque_keys! {
Expand Down
33 changes: 33 additions & 0 deletions pallets/invulnerables/src/weights.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ pub trait WeightInfo {
fn add_invulnerable(_b: u32) -> Weight;
fn remove_invulnerable(_b: u32) -> Weight;
fn new_session(_b: u32) -> Weight;
fn reward_invulnerable() -> Weight;
}

/// Weight functions for `pallet_invulnerables`.
Expand Down Expand Up @@ -120,6 +121,22 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
.saturating_add(T::DbWeight::get().reads(2))
.saturating_add(T::DbWeight::get().writes(1))
}

/// Storage: `Invulnerables::Invulnerables` (r:1 w:0)
/// Proof: `Invulnerables::Invulnerables` (`max_values`: Some(1), `max_size`: Some(3202), added: 3697, mode: `MaxEncodedLen`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// The range of component `b` is `[1, 100]`.
fn reward_invulnerable() -> Weight {
// Proof Size summary in bytes:
// Measured: `218 + b * (33 ±0)`
// Estimated: `4687`
// Minimum execution time: 51_037_000 picoseconds.
Weight::from_parts(68_315_971, 4687)
.saturating_add(T::DbWeight::get().reads(2_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}

}

// For backwards compatibility and tests
Expand Down Expand Up @@ -187,4 +204,20 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().writes(1))
}

/// Storage: `Invulnerables::Invulnerables` (r:1 w:0)
/// Proof: `Invulnerables::Invulnerables` (`max_values`: Some(1), `max_size`: Some(3202), added: 3697, mode: `MaxEncodedLen`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// The range of component `b` is `[1, 100]`.
fn reward_invulnerable() -> Weight {
// Proof Size summary in bytes:
// Measured: `218 + b * (33 ±0)`
// Estimated: `4687`
// Minimum execution time: 51_037_000 picoseconds.
Weight::from_parts(68_315_971, 4687)
.saturating_add(RocksDbWeight::get().reads(2_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}


}
6 changes: 3 additions & 3 deletions pallets/pooled-staking/src/pools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

use {
crate::{
candidate::Candidates, Candidate, Config, CreditOf, Delegator, Error, Event, Pallet, Pools,
PoolsKey, Shares, Stake,
candidate::Candidates, weights::WeightInfo, Candidate, Config, CreditOf, Delegator, Error,
Event, Pallet, Pools, PoolsKey, Shares, Stake,
},
core::marker::PhantomData,
frame_support::{
Expand Down Expand Up @@ -472,7 +472,7 @@ pub fn distribute_rewards<T: Config>(
T::Currency::resolve(&T::StakingAccount::get(), other_rewards)
.map_err(|_| DispatchError::NoProviders)?;

Ok(().into())
Ok(Some(T::WeightInfo::distribute_rewards()).into())
}

fn distribute_rewards_inner<T: Config>(
Expand Down
6 changes: 6 additions & 0 deletions primitives/traits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ pub trait DistributeRewards<AccountId, Imbalance> {
fn distribute_rewards(rewarded: AccountId, amount: Imbalance) -> DispatchResultWithPostInfo;
}

impl<AccountId, Imbalance> DistributeRewards<AccountId, Imbalance> for () {
fn distribute_rewards(_rewarded: AccountId, _amount: Imbalance) -> DispatchResultWithPostInfo {
Ok(().into())
}
}

/// Get the current list of container chains parachain ids.
pub trait GetCurrentContainerChains {
type MaxContainerChains: Get<u32>;
Expand Down
3 changes: 3 additions & 0 deletions runtime/dancebox/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,8 @@ impl pallet_invulnerables::Config for Runtime {
type CollatorIdOf = pallet_invulnerables::IdentityCollator;
type CollatorRegistration = Session;
type WeightInfo = pallet_invulnerables::weights::SubstrateWeight<Runtime>;
#[cfg(feature = "runtime-benchmarks")]
type Currency = Balances;
}

parameter_types! {
Expand Down Expand Up @@ -1004,6 +1006,7 @@ impl frame_support::traits::OnUnbalanced<Credit<AccountId, Balances>> for OnUnba
}

impl pallet_inflation_rewards::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type ContainerChains = Registrar;
type GetSelfChainBlockAuthor = GetSelfChainBlockAuthor;
Expand Down

0 comments on commit dc42ba4

Please sign in to comment.