Skip to content

Commit

Permalink
replace proceduram macros with generic fn
Browse files Browse the repository at this point in the history
  • Loading branch information
mateuszaaa committed Sep 25, 2023
1 parent 243ce16 commit 398a0ba
Show file tree
Hide file tree
Showing 3 changed files with 166 additions and 105 deletions.
65 changes: 45 additions & 20 deletions pallets/proof-of-stake/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,38 +12,42 @@ use crate::Pallet as PoS;

const MILION: u128 = 1_000__000_000__000_000;

#[macro_export]
macro_rules! init {
() => {
frame_system::Pallet::<T>::set_block_number(1_u32.into());
pallet_issuance::Pallet::<T>::initialize();
};
fn init<T>() where
T: frame_system::Config,
T: pallet_issuance::Config,
{
frame_system::Pallet::<T>::set_block_number(1_u32.into());
pallet_issuance::Pallet::<T>::initialize();
}

#[macro_export]
macro_rules! forward_to_next_session {
() => {


fn forward_to_next_session<T>() where
T: frame_system::Config,
T: pallet_issuance::Config,
T: Config
{
let current_block: u32 = frame_system::Pallet::<T>::block_number().saturated_into::<u32>();

let blocks_per_session: u32 = PoS::<T>::rewards_period();
let target_block_nr: u32;
let target_session_nr: u32;

if (current_block == 0_u32 || current_block == 1_u32) {
if current_block == 0_u32 || current_block == 1_u32 {
target_session_nr = 1_u32;
target_block_nr = blocks_per_session;
} else {
// to fail on user trying to manage block nr on its own
assert!(current_block % blocks_per_session == 0);
target_session_nr = (current_block / blocks_per_session) + 1_u32;
target_block_nr = (target_session_nr * blocks_per_session);
target_block_nr = target_session_nr * blocks_per_session;
}

frame_system::Pallet::<T>::set_block_number(target_block_nr.into());
pallet_issuance::Pallet::<T>::compute_issuance(target_session_nr);
};
}


benchmarks! {
claim_rewards_all{
// 1. create
Expand All @@ -52,7 +56,7 @@ benchmarks! {
// 4. wait some
// 5. claim all

init!();
init::<T>();
let caller: <T as frame_system::Config>::AccountId = whitelisted_caller();
let initial_amount:mangata_types::Balance = 1000000000000000000000;
let expected_native_asset_id : TokenId = <T as Config>::NativeCurrencyId::get().into();
Expand All @@ -72,12 +76,12 @@ benchmarks! {
let half_of_minted_liquidity = total_minted_liquidity.into() / 2_u128;
let quater_of_minted_liquidity = total_minted_liquidity.into() / 4_u128;

forward_to_next_session!();
forward_to_next_session::<T>();

PoS::<T>::activate_liquidity(RawOrigin::Signed(caller.clone()).into(), liquidity_asset_id.into(), quater_of_minted_liquidity, None).unwrap();

forward_to_next_session!();
forward_to_next_session!();
forward_to_next_session::<T>();
forward_to_next_session::<T>();

assert!(PoS::<T>::calculate_rewards_amount(caller.clone(), liquidity_asset_id).unwrap() > 0);

Expand Down Expand Up @@ -113,7 +117,7 @@ benchmarks! {
// 4 wait some time
// 5 mint some

init!();
init::<T>();
let caller: <T as frame_system::Config>::AccountId = whitelisted_caller();
let initial_amount:mangata_types::Balance = 1000000000000000000000;
let expected_native_asset_id : TokenId = <T as Config>::NativeCurrencyId::get().into();
Expand All @@ -140,7 +144,7 @@ benchmarks! {
quater_of_minted_liquidity
);

forward_to_next_session!();
forward_to_next_session::<T>();

}: activate_liquidity(RawOrigin::Signed(caller.clone().into()), liquidity_asset_id.into(), quater_of_minted_liquidity, None)
verify {
Expand All @@ -158,7 +162,7 @@ benchmarks! {
// 3 mint some tokens
// deactivate some tokens (all or some - to be checked)

init!();
init::<T>();
let caller: <T as frame_system::Config>::AccountId = whitelisted_caller();
let initial_amount:mangata_types::Balance = 1000000000000000000000;
let expected_native_asset_id : TokenId = <T as Config>::NativeCurrencyId::get().into();
Expand All @@ -184,7 +188,7 @@ benchmarks! {
half_of_minted_liquidity
);

forward_to_next_session!();
forward_to_next_session::<T>();

}: deactivate_liquidity(RawOrigin::Signed(caller.clone().into()), liquidity_asset_id.into(), quater_of_minted_liquidity.into())
verify {
Expand All @@ -194,5 +198,26 @@ benchmarks! {
);
}

// reward_pool{
// // 1 crate pool
// // 2 promote pool
// // 3 mint some tokens
// // deactivate some tokens (all or some - to be checked)
//
// init::<T>();
// let caller: <T as frame_system::Config>::AccountId = whitelisted_caller();
// let initial_amount:mangata_types::Balance = 1000000000000000000000;
// let expected_native_asset_id : TokenId = <T as Config>::NativeCurrencyId::get().into();
// let native_asset_id : TokenId= <T as Config>::Currency::create(&caller, initial_amount.into()).unwrap().into();
// let non_native_asset_id : TokenId= <T as Config>::Currency::create(&caller, initial_amount.into()).unwrap().into();
// let reward_asset_id : TokenId= <T as Config>::Currency::create(&caller, ((40000000000000000000_u128/2_u128) + (60000000000000000000_u128/2_u128)).into()).unwrap().into();
//
// forward_to_next_session::<T>();
//
// }: reward_pool(RawOrigin::Signed(caller.clone().into()), (native_asset_id,non_native_asset_id), reward_asset_id.into(), 10000, 10u32.into())
// verify {
// //
// }

impl_benchmark_test_suite!(PoS, crate::mock::new_test_ext(), crate::mock::Test)
}
86 changes: 52 additions & 34 deletions pallets/proof-of-stake/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ pub mod pallet {
impl<T: Config> Hooks<T::BlockNumber> for Pallet<T> {}

#[cfg(feature = "runtime-benchmarks")]
pub trait PoSBenchmarkingConrfig: pallet_issuance::Config {}
pub trait PoSBenchmarkingConfig: pallet_issuance::Config {}
#[cfg(feature = "runtime-benchmarks")]
impl<T: pallet_issuance::Config> PoSBenchmarkingConfig for T {}

Expand Down Expand Up @@ -241,6 +241,8 @@ pub mod pallet {
TooManySchedules,
/// Too little rewards per session
TooLittleRewardsPerSession,
/// Reward token not paired with native token
RewardTokenNotPairdWithNativeToken,
}

#[pallet::event]
Expand Down Expand Up @@ -462,8 +464,9 @@ pub mod pallet {
) -> DispatchResult {
let sender = ensure_signed(origin)?;

let rewarded_token = <T as Config>::ValuationApi::get_liquidity_asset(pool.0, pool.1)
.map_err(|_| Error::<T>::PoolDoesNotExist)?;
let liquidity_token_id =
<T as Config>::ValuationApi::get_liquidity_asset(pool.0, pool.1)
.map_err(|_| Error::<T>::PoolDoesNotExist)?;

let current_session = Self::session_index();
ensure!(
Expand All @@ -477,13 +480,18 @@ pub mod pallet {
.and_then(|v| amount.checked_div(v.into()))
.ok_or(Error::<T>::MathOverflow)?;

// TODO: use valuation instead amount directly
ensure!(
amount_per_session >= T::MinRewardsPerSession::get(),
pool.0 == Self::native_token_id() || pool.1 == Self::native_token_id(),
Error::<T>::RewardTokenNotPairdWithNativeToken
);

ensure!(
<T as Config>::ValuationApi::valuate_liquidity_token(liquidity_token_id, amount) >=
T::MinRewardsPerSession::get(),
Error::<T>::TooLittleRewardsPerSession
);

RewardTokensPerPool::<T>::insert(rewarded_token, token_id, ());
RewardTokensPerPool::<T>::insert(liquidity_token_id, token_id, ());

T::Currency::transfer(
token_id.into(),
Expand All @@ -506,7 +514,7 @@ pub mod pallet {
}

map.try_insert(
(schedule_end, rewarded_token, token_id, amount_per_session, schedule_id),
(schedule_end, liquidity_token_id, token_id, amount_per_session, schedule_id),
(),
)
})
Expand Down Expand Up @@ -893,10 +901,15 @@ impl<T: Config> Pallet<T> {
},
)?;

TotalActivatedLiquidityForSchedules::<T>::mutate(liquidity_asset_id, liquidity_assets_reward, |amount| -> DispatchResult {
*amount = amount.checked_add(liquidity_assets_added).ok_or(Error::<T>::MathOverflow)?;
Ok(())
})?;
TotalActivatedLiquidityForSchedules::<T>::mutate(
liquidity_asset_id,
liquidity_assets_reward,
|amount| -> DispatchResult {
*amount =
amount.checked_add(liquidity_assets_added).ok_or(Error::<T>::MathOverflow)?;
Ok(())
},
)?;

Ok(())
}
Expand Down Expand Up @@ -967,10 +980,15 @@ impl<T: Config> Pallet<T> {
rewards_info,
);

TotalActivatedLiquidityForSchedules::<T>::try_mutate(liquidity_asset_id, reward_token, |amount| -> DispatchResult{
*amount = amount.checked_sub(liquidity_assets_burned).ok_or(Error::<T>::MathOverflow)?;
Ok(())
})?;
TotalActivatedLiquidityForSchedules::<T>::try_mutate(
liquidity_asset_id,
reward_token,
|amount| -> DispatchResult {
*amount =
amount.checked_sub(liquidity_assets_burned).ok_or(Error::<T>::MathOverflow)?;
Ok(())
},
)?;

ActivatedLiquidityForSchedules::<T>::try_mutate_exists(
(user.clone(), liquidity_asset_id, reward_token),
Expand Down Expand Up @@ -1160,11 +1178,10 @@ impl<T: Config> ProofOfStakeRewardsApi<T::AccountId> for Pallet<T> {
impl<T: Config> LiquidityMiningApi for Pallet<T> {
/// Distributs liquidity mining rewards between all the activated tokens based on their weight
fn distribute_rewards(liquidity_mining_rewards: Balance) {

// R:1 W:0
// R:1 W:0
let schedules = RewardsSchedules::<T>::get();

// R:1 W:0
// R:1 W:0
let mut pools = ScheduleRewardsPerSingleLiquidity::<T>::get();

let it =
Expand All @@ -1179,22 +1196,23 @@ impl<T: Config> LiquidityMiningApi for Pallet<T> {
});

for (staked_token, rewarded_token, amount) in it {
// R: T::RewardsSchedulesLimit - in most pesimistic case
match TotalActivatedLiquidityForSchedules::<T>::get(staked_token, rewarded_token) {
0 => {},
activated_amount => {
let activated_amount = U256::from(activated_amount);
let rewards = pools.get(&(*staked_token, *rewarded_token)).cloned().unwrap_or_default();
let rewards_for_liquidity = U256::from(*amount)
.checked_mul(U256::from(u128::MAX))
.and_then(|x| x.checked_div(activated_amount))
.and_then(|x| x.checked_add(rewards));

if let Some(val) = rewards_for_liquidity {
pools.insert((*staked_token, *rewarded_token), val);
}
},
}
// R: T::RewardsSchedulesLimit - in most pesimistic case
match TotalActivatedLiquidityForSchedules::<T>::get(staked_token, rewarded_token) {
0 => {},
activated_amount => {
let activated_amount = U256::from(activated_amount);
let rewards =
pools.get(&(*staked_token, *rewarded_token)).cloned().unwrap_or_default();
let rewards_for_liquidity = U256::from(*amount)
.checked_mul(U256::from(u128::MAX))
.and_then(|x| x.checked_div(activated_amount))
.and_then(|x| x.checked_add(rewards));

if let Some(val) = rewards_for_liquidity {
pools.insert((*staked_token, *rewarded_token), val);
}
},
}
}

ScheduleRewardsPerSingleLiquidity::<T>::put(pools);
Expand Down
Loading

0 comments on commit 398a0ba

Please sign in to comment.