Skip to content

Feat/reward pool history #1710

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions integration-tests/capacity/staking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,13 +214,13 @@ describe("Capacity Staking Tests", function () {
});

describe("when attempting to stake below the minimum staking requirements", async function () {
it("should fail to stake for InsufficientStakingAmount", async function () {
it("should fail to stake for StakingAmountBelowMinimum", async function () {
let stakingKeys = createKeys("stakingKeys");
let providerId = await createMsaAndProvider(stakingKeys, "stakingKeys", 150n * CENTS);
let stakeAmount = 1500n;

const failStakeObj = ExtrinsicHelper.stake(stakingKeys, providerId, stakeAmount, 'MaximumCapacity');
await assert.rejects(failStakeObj.fundAndSend(), { name: "InsufficientStakingAmount" });
await assert.rejects(failStakeObj.fundAndSend(), { name: "StakingAmountBelowMinimum" });
});
});

Expand All @@ -230,7 +230,7 @@ describe("Capacity Staking Tests", function () {
let providerId = await createMsaAndProvider(stakingKeys, "stakingKeys", );

const failStakeObj = ExtrinsicHelper.stake(stakingKeys, providerId, 0, 'MaximumCapacity');
await assert.rejects(failStakeObj.fundAndSend(), { name: "ZeroAmountNotAllowed" });
await assert.rejects(failStakeObj.fundAndSend(), { name: "StakingAmountBelowMinimum" });
});
});

Expand Down
2 changes: 1 addition & 1 deletion integration-tests/package-lock.json

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

96 changes: 61 additions & 35 deletions pallets/capacity/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
rustdoc::invalid_codeblock_attributes,
missing_docs
)]
use sp_std::ops::{Add, Mul};

use frame_support::{
dispatch::DispatchResult,
Expand All @@ -60,7 +61,6 @@ use sp_runtime::{
traits::{CheckedAdd, CheckedDiv, One, Saturating, Zero},
ArithmeticError, DispatchError, Perbill,
};
use sp_std::ops::Mul;

pub use common_primitives::{
capacity::{Nontransferable, Replenishable, TargetValidator},
Expand Down Expand Up @@ -90,12 +90,12 @@ type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;

const STAKING_ID: LockIdentifier = *b"netstkng";

#[frame_support::pallet]
pub mod pallet {
use super::*;
use codec::EncodeLike;

use common_primitives::capacity::StakingType;
use frame_support::{pallet_prelude::*, Twox64Concat};
use frame_system::pallet_prelude::*;
use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeDisplay};
Expand Down Expand Up @@ -177,7 +177,7 @@ pub mod pallet {

/// The maximum number of eras over which one can claim rewards
#[pallet::constant]
type StakingRewardsPastErasMax: Get<u32>;
type StakingRewardsPastErasMax: Get<Self::RewardEra>;

/// The StakingRewardsProvider used by this pallet in a given runtime
type RewardsProvider: StakingRewardsProvider<Self>;
Expand All @@ -186,7 +186,7 @@ pub mod pallet {
/// thaw chunk to expire. If the staker has called change_staking_target MaxUnlockingChunks
/// times, then at least one of the chunks must have expired before the next call
/// will succeed.
type ChangeStakingTargetThawEras: Get<u32>;
type ChangeStakingTargetThawEras: Get<Self::RewardEra>;
}

/// Storage for keeping a ledger of staked token amounts for accounts.
Expand Down Expand Up @@ -242,8 +242,9 @@ pub mod pallet {
pub type EpochLength<T: Config> =
StorageValue<_, T::BlockNumber, ValueQuery, EpochLengthDefault<T>>;

/// Information about the current staking reward era.
/// Information about the current staking reward era. Checked every block.
#[pallet::storage]
#[pallet::whitelist_storage]
#[pallet::getter(fn get_current_era)]
pub type CurrentEraInfo<T: Config> =
StorageValue<_, RewardEraInfo<T::RewardEra, T::BlockNumber>, ValueQuery>;
Expand All @@ -252,10 +253,8 @@ pub mod pallet {
#[pallet::storage]
#[pallet::getter(fn get_reward_pool_for_era)]
pub type StakingRewardPool<T: Config> =
StorageMap<_, Twox64Concat, T::RewardEra, RewardPoolInfo<BalanceOf<T>>>;
CountedStorageMap<_, Twox64Concat, T::RewardEra, RewardPoolInfo<BalanceOf<T>>>;

// Simple declaration of the `Pallet` type. It is placeholder we use to implement traits and
// method.
#[pallet::pallet]
pub struct Pallet<T>(_);

Expand Down Expand Up @@ -356,6 +355,8 @@ pub mod pallet {
IneligibleForPayoutInEraRange,
/// Attempted to retarget but from and to Provider MSA Ids were the same
CannotRetargetToSameProvider,
/// Rewards were already paid out this era
AlreadyClaimedRewardsThisEra,
}

#[pallet::hooks]
Expand Down Expand Up @@ -448,10 +449,9 @@ pub mod pallet {
requested_amount: BalanceOf<T>,
) -> DispatchResult {
let unstaker = ensure_signed(origin)?;
Self::ensure_can_unstake(&unstaker)?;

ensure!(requested_amount > Zero::zero(), Error::<T>::UnstakedAmountIsZero);

Self::ensure_can_unstake(&unstaker)?;
let actual_amount = Self::decrease_active_staking_balance(&unstaker, requested_amount)?;
let capacity_reduction = Self::reduce_capacity(&unstaker, target, actual_amount)?;

Expand Down Expand Up @@ -487,13 +487,16 @@ pub mod pallet {
/// This adds a chunk to `StakingAccountDetails.stake_change_unlocking chunks`, up to `T::MaxUnlockingChunks`.
/// The staked amount and Capacity generated by `amount` originally targeted to the `from` MSA Id is reassigned to the `to` MSA Id.
/// Does not affect unstaking process or additional stake amounts.
/// Changing a staking target to a Provider when Origin has nothing staked them will retain the staking type.
/// Changing a staking target to a Provider when Origin has any amount staked to them will error if the staking types are not the same.
/// ### Errors
/// - [`Error::NotAStakingAccount`] if origin does not have a staking account
/// - [`Error::MaxUnlockingChunksExceeded`] if `stake_change_unlocking_chunks` == `T::MaxUnlockingChunks`
/// - [`Error::StakerTargetRelationshipNotFound`] if `from` is not a target for Origin's staking account.
/// - [`Error::StakingAmountBelowMinimum`] if `amount` to retarget is below the minimum staking amount.
/// - [`Error::InsufficientStakingBalance`] if `amount` to retarget exceeds what the staker has targeted to `from` MSA Id.
/// - [`Error::InvalidTarget`] if `to` does not belong to a registered Provider.
/// - [`Error::CannotChangeStakingType`] if origin already has funds staked for `to` and the staking type for `from` is different.
#[pallet::call_index(4)]
#[pallet::weight(T::WeightInfo::unstake())]
pub fn change_staking_target(
Expand Down Expand Up @@ -764,18 +767,41 @@ impl<T: Config> Pallet<T> {
}

fn start_new_reward_era_if_needed(current_block: T::BlockNumber) -> Weight {
let current_era_info: RewardEraInfo<T::RewardEra, T::BlockNumber> = Self::get_current_era();
let current_era_info: RewardEraInfo<T::RewardEra, T::BlockNumber> = Self::get_current_era(); // 1r

if current_block.saturating_sub(current_era_info.started_at) >= T::EraLength::get().into() {
CurrentEraInfo::<T>::set(RewardEraInfo {
let new_era_info = RewardEraInfo {
era_index: current_era_info.era_index.saturating_add(One::one()),
started_at: current_block,
});
// TODO: modify reads/writes as needed when RewardPoolInfo stuff is added
};

let current_reward_pool_info =
Self::get_reward_pool_for_era(current_era_info.era_index).unwrap_or_default(); // 1r

let past_eras_max = T::StakingRewardsPastErasMax::get();
let entries: u32 = StakingRewardPool::<T>::count(); // 1r

if past_eras_max.eq(&entries.into()) {
let earliest_era =
current_era_info.era_index.saturating_sub(past_eras_max).add(One::one());
StakingRewardPool::<T>::remove(earliest_era); // 1w
}
CurrentEraInfo::<T>::set(new_era_info); // 1w

let total_reward_pool =
T::RewardsProvider::reward_pool_size(current_reward_pool_info.total_staked_token);
let new_reward_pool = RewardPoolInfo {
total_staked_token: current_reward_pool_info.total_staked_token,
total_reward_pool,
unclaimed_balance: total_reward_pool,
};
StakingRewardPool::<T>::insert(new_era_info.era_index, new_reward_pool); // 1w

T::WeightInfo::on_initialize()
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(3))
} else {
T::DbWeight::get().reads(2).saturating_add(RocksDbWeight::get().writes(1))
T::DbWeight::get().reads(1)
}
}

Expand All @@ -796,7 +822,7 @@ impl<T: Config> Pallet<T> {
Self::get_staking_account_for(staker).ok_or(Error::<T>::NotAStakingAccount)?;

let current_era: T::RewardEra = Self::get_current_era().era_index;
let thaw_at = current_era.saturating_add(T::ChangeStakingTargetThawEras::get().into());
let thaw_at = current_era.saturating_add(T::ChangeStakingTargetThawEras::get());
staking_account_details.update_stake_change_unlocking(amount, &thaw_at, &current_era)?;
Self::set_staking_account(staker, &staking_account_details);
Ok(())
Expand All @@ -814,15 +840,22 @@ impl<T: Config> Pallet<T> {
let capacity_withdrawn = Self::reduce_capacity(staker, *from_msa, *amount)?;

let mut to_msa_target = Self::get_target_for(staker, to_msa).unwrap_or_default();

if to_msa_target.amount.is_zero() {
// it's a new StakingTargetDetails record.
to_msa_target.staking_type = staking_type.clone();
} else {
// make sure they are not retargeting to a StakingTargetDetails with a different staking
// type, otherwise it could interfere with staking rewards.
ensure!(
to_msa_target.staking_type.eq(staking_type),
Error::<T>::CannotChangeStakingType
);
}
to_msa_target
.deposit(*amount, capacity_withdrawn)
.ok_or(ArithmeticError::Overflow)?;

// TODO: document
// if someone wants to switch staking type they must unstake completely and restake regardless of
// whether it is with an existing or new provider.
to_msa_target.staking_type = staking_type.clone();

let mut capacity_details = Self::get_capacity_for(to_msa).unwrap_or_default();
capacity_details
.deposit(amount, &capacity_withdrawn)
Expand Down Expand Up @@ -925,19 +958,13 @@ impl<T: Config> StakingRewardsProvider<T> for Pallet<T> {

// Calculate the size of the reward pool for the current era, based on current staked token
// and the other determined factors of the current economic model
fn reward_pool_size() -> Result<BalanceOf<T>, DispatchError> {
let current_era_info = CurrentEraInfo::<T>::get();
let current_staked =
StakingRewardPool::<T>::get(current_era_info.era_index).unwrap_or_default();
if current_staked.total_staked_token.is_zero() {
return Ok(BalanceOf::<T>::zero())
fn reward_pool_size(total_staked: BalanceOf<T>) -> BalanceOf<T> {
if total_staked.is_zero() {
return BalanceOf::<T>::zero()
}

// For now reward pool size is set to 10% of total staked token
Ok(current_staked
.total_staked_token
.checked_div(&BalanceOf::<T>::from(10u8))
.unwrap_or_default())
total_staked.checked_div(&BalanceOf::<T>::from(10u8)).unwrap_or_default()
}

// Performs range checks plus a reward calculation based on economic model for the era range
Expand All @@ -946,9 +973,8 @@ impl<T: Config> StakingRewardsProvider<T> for Pallet<T> {
from_era: T::RewardEra,
to_era: T::RewardEra,
) -> Result<BalanceOf<T>, DispatchError> {
let max_eras = T::RewardEra::from(T::StakingRewardsPastErasMax::get());
let era_range = from_era.saturating_sub(to_era);
ensure!(era_range.le(&max_eras), Error::<T>::EraOutOfRange);
ensure!(era_range.le(&T::StakingRewardsPastErasMax::get()), Error::<T>::EraOutOfRange);
ensure!(from_era.le(&to_era), Error::<T>::EraOutOfRange);
let current_era_info = Self::get_current_era();
ensure!(to_era.lt(&current_era_info.era_index), Error::<T>::EraOutOfRange);
Expand Down
23 changes: 6 additions & 17 deletions pallets/capacity/src/tests/change_staking_target_tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use super::{mock::*, testing_utils::*};
use super::{
mock::*,
testing_utils::{setup_provider, staking_events},
};
use crate::{
BalanceOf, CapacityDetails, Config, CurrentEraInfo, Error, Event, RewardEraInfo,
StakingAccountDetails, StakingAccountLedger, StakingTargetDetails,
Expand All @@ -13,22 +16,6 @@ use common_primitives::{
use frame_support::{assert_noop, assert_ok, traits::Get};

// staker is unused unless amount > 0
fn setup_provider(staker: &u64, target: &MessageSourceId, amount: &u64, staking_type: StakingType) {
let provider_name = String::from("Cst-") + target.to_string().as_str();
register_provider(*target, provider_name);
if amount.gt(&0u64) {
assert_ok!(Capacity::stake(
RuntimeOrigin::signed(staker.clone()),
*target,
*amount,
staking_type.clone()
));
let target = Capacity::get_target_for(staker, target).unwrap();
assert_eq!(target.amount, *amount);
assert_eq!(target.staking_type, staking_type);
}
}

type TestCapacityDetails = CapacityDetails<BalanceOf<Test>, u32>;
type TestTargetDetails = StakingTargetDetails<Test>;

Expand Down Expand Up @@ -60,6 +47,7 @@ fn assert_target_details(
let from_target_details = Capacity::get_target_for(staker, msa_id).unwrap();
assert_eq!(from_target_details, expected_from_target_details);
}

#[test]
fn do_retarget_happy_path() {
new_test_ext().execute_with(|| {
Expand Down Expand Up @@ -160,6 +148,7 @@ fn assert_total_capacity(msas: Vec<MessageSourceId>, total: u64) {
.fold(0, |a, b| a + b);
assert_eq!(total, sum);
}

#[test]
fn check_retarget_multiple_stakers() {
new_test_ext().execute_with(|| {
Expand Down
Loading