Skip to content

Commit

Permalink
feature(kensetsu): remove total hard_cap (#1038)
Browse files Browse the repository at this point in the history
* feature(kensetsu): remove total hard_cap

* feature(kensetsu): bump runtime version
  • Loading branch information
Alexey-N-Chernyshov authored May 14, 2024
1 parent 02b5eea commit 2fbc5bc
Show file tree
Hide file tree
Showing 8 changed files with 93 additions and 356 deletions.
27 changes: 0 additions & 27 deletions pallets/kensetsu/benchmarking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,6 @@ benchmarks! {
create_cdp {
initialize_liquidity_sources::<T>();
set_xor_as_collateral_type::<T>();
kensetsu::Pallet::<T>::update_hard_cap_total_supply(
RawOrigin::Root.into(),
Balance::MAX,
).expect("Shall update hard cap");
let collateral = balance!(10);
let debt = balance!(1);
assets::Pallet::<T>::update_balance(
Expand Down Expand Up @@ -265,10 +261,6 @@ benchmarks! {
borrow {
initialize_liquidity_sources::<T>();
set_xor_as_collateral_type::<T>();
kensetsu::Pallet::<T>::update_hard_cap_total_supply(
RawOrigin::Root.into(),
Balance::MAX,
).expect("Shall update hard cap");
let cdp_id = create_cdp_with_xor::<T>();
let amount = balance!(10);
deposit_xor_collateral::<T>(cdp_id, amount);
Expand All @@ -289,10 +281,6 @@ benchmarks! {
let amount = balance!(10);
deposit_xor_collateral::<T>(cdp_id, amount);
let debt = balance!(1);
kensetsu::Pallet::<T>::update_hard_cap_total_supply(
RawOrigin::Root.into(),
Balance::MAX,
).expect("Shall update hard cap");
kensetsu::Pallet::<T>::borrow(RawOrigin::Signed(caller::<T>()).into(), cdp_id, debt, debt)
.expect("Shall borrow");
}: {
Expand All @@ -310,10 +298,6 @@ benchmarks! {
let amount = balance!(100);
deposit_xor_collateral::<T>(cdp_id, amount);
let debt = balance!(50);
kensetsu::Pallet::<T>::update_hard_cap_total_supply(
RawOrigin::Root.into(),
Balance::MAX,
).expect("Shall update hard cap");
kensetsu::Pallet::<T>::borrow(RawOrigin::Signed(caller::<T>()).into(), cdp_id, debt, debt)
.expect("Shall borrow");
make_cdps_unsafe::<T>();
Expand All @@ -328,10 +312,6 @@ benchmarks! {
let amount = balance!(1000);
deposit_xor_collateral::<T>(cdp_id, amount);
let debt = balance!(100);
kensetsu::Pallet::<T>::update_hard_cap_total_supply(
RawOrigin::Root.into(),
Balance::MAX,
).expect("Shall update hard cap");
kensetsu::Pallet::<T>::borrow(
RawOrigin::Signed(caller::<T>()).into(),
cdp_id,
Expand All @@ -357,13 +337,6 @@ benchmarks! {
).unwrap();
}

update_hard_cap_total_supply {}: {
kensetsu::Pallet::<T>::update_hard_cap_total_supply(
RawOrigin::Root.into(),
balance!(1000)
).unwrap();
}

update_borrow_tax {
let new_borrow_tax = Percent::from_percent(1);
}:{
Expand Down
56 changes: 4 additions & 52 deletions pallets/kensetsu/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -343,12 +343,6 @@ pub mod pallet {
pub type CollateralInfos<T: Config> =
StorageMap<_, Identity, AssetIdOf<T>, CollateralInfo<T::Moment>>;

/// Risk parameter
/// Hard cap of KUSD may be minted by the system
#[pallet::storage]
#[pallet::getter(fn max_supply)]
pub type KusdHardCap<T> = StorageValue<_, Balance, ValueQuery>;

/// Risk parameter
/// Borrows tax to buy back and burn KEN
#[pallet::storage]
Expand Down Expand Up @@ -429,11 +423,6 @@ pub mod pallet {
collateral_asset_id: AssetIdOf<T>,
risk_parameters: CollateralRiskParameters,
},
DebtTokenHardCapUpdated {
debt_asset_id: AssetIdOf<T>,
new_hard_cap: Balance,
old_hard_cap: Balance,
},
BorrowTaxUpdated {
old_borrow_tax: Percent,
new_borrow_tax: Percent,
Expand Down Expand Up @@ -686,36 +675,13 @@ pub mod pallet {
Ok(())
}

/// Updates the hard cap for the total supply of a stablecoin.
///
/// ## Parameters
///
/// - `origin`: The origin of the transaction.
/// - `new_hard_cap`: The new hard cap value to be set for the total supply.
#[pallet::call_index(8)]
#[pallet::weight(<T as Config>::WeightInfo::update_hard_cap_total_supply())]
pub fn update_hard_cap_total_supply(
origin: OriginFor<T>,
new_hard_cap: Balance,
) -> DispatchResult {
ensure_root(origin)?;
let old_hard_cap = KusdHardCap::<T>::get();
KusdHardCap::<T>::set(new_hard_cap);
Self::deposit_event(Event::DebtTokenHardCapUpdated {
debt_asset_id: T::KusdAssetId::get(),
new_hard_cap,
old_hard_cap,
});
Ok(())
}

/// Updates the borrow tax applied during borrow.
///
/// ## Parameters
///
/// - `origin`: The origin of the transaction.
/// - `new_borrow_tax`: The new borrow tax percentage to be set.
#[pallet::call_index(9)]
#[pallet::call_index(8)]
#[pallet::weight(<T as Config>::WeightInfo::update_borrow_tax())]
pub fn update_borrow_tax(origin: OriginFor<T>, new_borrow_tax: Percent) -> DispatchResult {
ensure_root(origin)?;
Expand All @@ -735,7 +701,7 @@ pub mod pallet {
///
/// - `origin`: The origin of the transaction.
/// - `new_liquidation_penalty`: The new liquidation penalty percentage to be set.
#[pallet::call_index(10)]
#[pallet::call_index(9)]
#[pallet::weight(<T as Config>::WeightInfo::update_liquidation_penalty())]
pub fn update_liquidation_penalty(
origin: OriginFor<T>,
Expand All @@ -759,7 +725,7 @@ pub mod pallet {
/// - `origin`: The origin of the transaction.
/// - `beneficiary` : The destination account where assets will be withdrawn.
/// - `kusd_amount`: The amount of stablecoin (KUSD) to withdraw as protocol profit.
#[pallet::call_index(11)]
#[pallet::call_index(10)]
#[pallet::weight(<T as Config>::WeightInfo::withdraw_profit())]
pub fn withdraw_profit(
origin: OriginFor<T>,
Expand Down Expand Up @@ -787,7 +753,7 @@ pub mod pallet {
///
/// - `origin`: The origin of the transaction.
/// - `kusd_amount`: The amount of stablecoin (KUSD) to donate to cover bad debt.
#[pallet::call_index(12)]
#[pallet::call_index(11)]
#[pallet::weight(<T as Config>::WeightInfo::donate())]
pub fn donate(origin: OriginFor<T>, kusd_amount: Balance) -> DispatchResult {
let who = ensure_signed(origin)?;
Expand Down Expand Up @@ -935,19 +901,6 @@ pub mod pallet {
Ok(())
}

/// Ensures that new emission will not exceed system KUSD hard cap
fn ensure_protocol_cap(new_emission: Balance) -> DispatchResult {
let current_supply = T::AssetInfoProvider::total_issuance(&T::KusdAssetId::get())?;
ensure!(
current_supply
.checked_add(new_emission)
.ok_or(Error::<T>::ArithmeticError)?
<= Self::max_supply(),
Error::<T>::HardCapSupply
);
Ok(())
}

/// Deposits collateral to CDP.
/// Handles internal deposit of collateral into a Collateralized Debt Position (CDP).
///
Expand Down Expand Up @@ -1048,7 +1001,6 @@ pub mod pallet {
Self::incentivize_ken_token(borrow_tax)?;

Self::ensure_collateral_cap(cdp.collateral_asset_id, borrow_amount_with_tax)?;
Self::ensure_protocol_cap(borrow_amount_with_tax)?;
Self::mint_to(who, borrow_amount)?;
Self::increase_cdp_debt(cdp_id, borrow_amount_with_tax)?;
Self::deposit_event(Event::DebtIncreased {
Expand Down
122 changes: 15 additions & 107 deletions pallets/kensetsu/src/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,122 +98,30 @@ pub mod init {
}
}

/// Due to bug in stability fee update some extra KUSD were minted, this migration burns and sets
/// correct amounts.
pub mod stage_correction {
use crate::{BadDebt, CDPDepository, CollateralInfos, Config, Error};
use common::AssetInfoProvider;
use common::Balance;
/// Removes hard_cap. This migration for stage only, will not change storage version.
pub mod remove_hard_cap {
use crate::Config;
use core::marker::PhantomData;
use frame_support::dispatch::Weight;
use frame_support::log::error;
use frame_support::traits::OnRuntimeUpgrade;
use sp_arithmetic::traits::Zero;
use sp_core::Get;
use sp_runtime::DispatchResult;

pub struct CorrectKusdBalances<T>(PhantomData<T>);

impl<T: Config + permissions::Config + technical::Config> CorrectKusdBalances<T> {
fn runtime_upgrade_internal(weight: &mut Weight) -> DispatchResult {
let mut total_debt = Balance::zero();

for asset_id in CollateralInfos::<T>::iter_keys() {
let accumulated_debt_for_collateral = CDPDepository::<T>::iter()
.filter(|(_, cdp)| {
*weight += <T as frame_system::Config>::DbWeight::get().reads(1);
cdp.collateral_asset_id == asset_id
})
.fold(
Balance::zero(),
|accumulated_debt_for_collateral, (_, cdp)| {
accumulated_debt_for_collateral + cdp.debt
},
);

CollateralInfos::<T>::try_mutate(asset_id, |collateral_info| {
let collateral_info =
collateral_info.as_mut().ok_or(Error::<T>::CDPNotFound)?;
collateral_info.kusd_supply = accumulated_debt_for_collateral;
DispatchResult::Ok(())
})?;
*weight += <T as frame_system::Config>::DbWeight::get().writes(1);

total_debt += accumulated_debt_for_collateral;
}

let bad_debt = BadDebt::<T>::get();
total_debt += bad_debt;

// kusd supply must be equal to aggregated debt:
// kusd_supply == sum(cdp.debt) + bad_debt
let kusd_supply = T::AssetInfoProvider::total_issuance(&T::KusdAssetId::get())?;
*weight += <T as frame_system::Config>::DbWeight::get().reads(1);

let (surplus, shortage) = if kusd_supply > total_debt {
(kusd_supply - total_debt, 0)
} else {
(0, total_debt - kusd_supply)
};

let treasury_account_id = technical::Pallet::<T>::tech_account_id_to_account_id(
&T::TreasuryTechAccount::get(),
)?;
let profit =
T::AssetInfoProvider::free_balance(&T::KusdAssetId::get(), &treasury_account_id)?;
*weight += <T as frame_system::Config>::DbWeight::get().reads(1);

// burn KUSD surplus on tech acc profit or add to bad debt
if surplus > 0 {
let (to_burn, to_bad_debt) = if profit > surplus {
(surplus, 0)
} else {
(profit, surplus - profit)
};
assets::Pallet::<T>::burn_from(
&T::KusdAssetId::get(),
&treasury_account_id,
&treasury_account_id,
to_burn,
)?;
mod old {
use crate::{Config, Pallet};
use common::Balance;
use frame_support::pallet_prelude::ValueQuery;

BadDebt::<T>::set(bad_debt + to_bad_debt);

*weight += <T as frame_system::Config>::DbWeight::get().writes(2);
}

// mint KUSD shortage to tech acc or cover bad debt
if shortage > 0 {
let (from_bad_debt, to_mint) = if bad_debt > shortage {
(shortage, 0)
} else {
(bad_debt, shortage - bad_debt)
};

technical::Pallet::<T>::mint(
&T::KusdAssetId::get(),
&T::TreasuryTechAccount::get(),
to_mint,
)?;

BadDebt::<T>::set(bad_debt - from_bad_debt);

*weight += <T as frame_system::Config>::DbWeight::get().writes(2);
}

Ok(())
}
/// value to remove
#[frame_support::storage_alias]
pub type KusdHardCap<T: Config> = StorageValue<Pallet<T>, Balance, ValueQuery>;
}

impl<T: Config + permissions::Config + technical::Config> OnRuntimeUpgrade
for CorrectKusdBalances<T>
{
pub struct RemoveHardCap<T>(PhantomData<T>);

impl<T: Config + permissions::Config + technical::Config> OnRuntimeUpgrade for RemoveHardCap<T> {
fn on_runtime_upgrade() -> Weight {
let mut weight = Weight::zero();
Self::runtime_upgrade_internal(&mut weight).unwrap_or_else(|err| {
error!("Runtime upgrade error {:?}", err);
});
weight
old::KusdHardCap::<T>::kill();
<T as frame_system::Config>::DbWeight::get().writes(1)
}
}
}
1 change: 0 additions & 1 deletion pallets/kensetsu/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ pub fn set_xor_as_collateral_type(
minimal_collateral_deposit,
}
));
KusdHardCap::<TestRuntime>::set(hard_cap);
}

/// Makes CDPs unsafe by changing liquidation ratio.
Expand Down
Loading

0 comments on commit 2fbc5bc

Please sign in to comment.