Skip to content

Commit

Permalink
cleanup code a bit
Browse files Browse the repository at this point in the history
  • Loading branch information
xlc committed Dec 18, 2019
1 parent c77bf6a commit f36df9d
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 57 deletions.
4 changes: 2 additions & 2 deletions modules/auction_manager/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ impl<T: Trait> AuctionHandler<T::AccountId, T::Balance, T::BlockNumber, AuctionI
.and_then(|n| n.checked_div(&new_bid.1))
.unwrap_or(auction_item.amount);

let deduct_amount = auction_item.amount.checked_sub(&new_amount).unwrap_or(0.into());
let deduct_amount = auction_item.amount.checked_sub(&new_amount).unwrap_or_default();

// ensure have sufficient collateral in auction module
if Self::total_collateral_in_auction(auction_item.currency_id) >= deduct_amount {
Expand Down Expand Up @@ -215,7 +215,7 @@ impl<T: Trait> AuctionManager<T::AccountId> for Module<T> {
type Balance = T::Balance;

fn new_collateral_auction(
who: T::AccountId,
who: &T::AccountId,
currency_id: Self::CurrencyId,
amount: Self::Balance,
target: Self::Balance,
Expand Down
10 changes: 5 additions & 5 deletions modules/cdp_engine/src/debit_exchange_rate_convertor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ where
T: Trait,
{
fn convert(a: (CurrencyIdOf<T>, DebitBalanceOf<T>)) -> BalanceOf<T> {
let balance = TryInto::<BalanceOf<T>>::try_into(TryInto::<u128>::try_into(a.1).unwrap_or(u128::max_value()))
.unwrap_or(BalanceOf::<T>::max_value());
<Module<T>>::debit_exchange_rate(a.0)
let (currency_id, balance) = a;
let balance: u128 = balance.unique_saturated_into();
let balance: BalanceOf<T> = balance.unique_saturated_into();
<Module<T>>::debit_exchange_rate(currency_id)
.unwrap_or(T::DefaulDebitExchangeRate::get())
.checked_mul_int(&balance)
.unwrap_or(BalanceOf::<T>::max_value())
.saturating_mul_int(&balance)
}
}
55 changes: 17 additions & 38 deletions modules/cdp_engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use frame_support::{decl_error, decl_event, decl_module, decl_storage, ensure, t
use orml_traits::{arithmetic::Signed, MultiCurrency, MultiCurrencyExtended, PriceProvider};
use orml_utilities::FixedU128;
use rstd::{convert::TryInto, marker, prelude::*, result};
use sp_runtime::traits::{Bounded, CheckedAdd, CheckedSub, Convert};
use sp_runtime::traits::{CheckedAdd, CheckedSub, Convert, Saturating, UniqueSaturatedInto, Zero};
use support::{AuctionManager, CDPTreasury, ExchangeRate, Price, Rate, Ratio, RiskManager};
use system::ensure_root;

Expand Down Expand Up @@ -131,18 +131,20 @@ decl_module! {
// handle all kinds of collateral type
for currency_id in T::CollateralCurrencyIds::get() {
let debit_exchange_rate = Self::debit_exchange_rate(currency_id).unwrap_or(T::DefaulDebitExchangeRate::get());
let stability_fee_rate = Self::stability_fee(currency_id).unwrap_or(Rate::from_parts(0)).checked_add(&global_stability_fee).unwrap_or(Rate::max_value());
let stability_fee_rate = Self::stability_fee(currency_id)
.unwrap_or_default()
.saturating_add(global_stability_fee);
let total_debits = <vaults::Module<T>>::total_debits(currency_id);
if stability_fee_rate > Rate::from_parts(0) && total_debits > 0.into() {
let debit_exchange_rate_increment = debit_exchange_rate.checked_mul(&stability_fee_rate).unwrap_or(ExchangeRate::max_value());
if !stability_fee_rate.is_zero() && !total_debits.is_zero() {
let debit_exchange_rate_increment = debit_exchange_rate.saturating_mul(stability_fee_rate);

// update exchange rate
let new_debit_exchange_rate = debit_exchange_rate.checked_add(&debit_exchange_rate_increment).unwrap_or(ExchangeRate::max_value());
let new_debit_exchange_rate = debit_exchange_rate.saturating_add(debit_exchange_rate_increment);
<DebitExchangeRate<T>>::insert(currency_id, new_debit_exchange_rate);

// issue stablecoin to surplus pool
let total_debit_value = DebitExchangeRateConvertor::<T>::convert((currency_id, total_debits));
let issued_stable_coin_balance = debit_exchange_rate_increment.checked_mul_int(&total_debit_value).unwrap_or(BalanceOf::<T>::max_value());
let issued_stable_coin_balance = debit_exchange_rate_increment.saturating_mul_int(&total_debit_value);
T::Treasury::on_surplus(issued_stable_coin_balance);
}
}
Expand All @@ -157,15 +159,8 @@ impl<T: Trait> Module<T> {
debit_balance: DebitBalanceOf<T>,
price: Price,
) -> Ratio {
let locked_collateral_value = TryInto::<u128>::try_into(
price
.checked_mul_int(&collateral_balance)
.unwrap_or(BalanceOf::<T>::max_value()),
)
.unwrap_or(u128::max_value());
let debit_value =
TryInto::<u128>::try_into(DebitExchangeRateConvertor::<T>::convert((currency_id, debit_balance)))
.unwrap_or(u128::max_value());
let locked_collateral_value = price.saturating_mul_int(&collateral_balance);
let debit_value = DebitExchangeRateConvertor::<T>::convert((currency_id, debit_balance));

Ratio::from_rational(locked_collateral_value, debit_value)
}
Expand All @@ -177,7 +172,7 @@ impl<T: Trait> Module<T> {
}

pub fn update_position(
who: T::AccountId,
who: &T::AccountId,
currency_id: CurrencyIdOf<T>,
collateral_adjustment: AmountOf<T>,
debit_adjustment: DebitAmountOf<T>,
Expand All @@ -195,18 +190,14 @@ impl<T: Trait> Module<T> {
// TODO: how to trigger cdp liquidation
pub fn liquidate_unsafe_cdp(who: T::AccountId, currency_id: CurrencyIdOf<T>) -> result::Result<(), Error> {
let debit_balance = <vaults::Module<T>>::debits(&who, currency_id);
let collateral_balance: BalanceOf<T> = <vaults::Module<T>>::collaterals(&who, currency_id);
let collateral_balance = <vaults::Module<T>>::collaterals(&who, currency_id);

// ensure the cdp is unsafe
let feed_price = <T as Trait>::PriceSource::get_price(T::GetStableCurrencyId::get(), currency_id)
.ok_or(Error::InvalidFeedPrice)?;
let feed_price =
T::PriceSource::get_price(T::GetStableCurrencyId::get(), currency_id).ok_or(Error::InvalidFeedPrice)?;
let collateral_ratio =
Self::calculate_collateral_ratio(currency_id, collateral_balance, debit_balance, feed_price);
let liquidation_ratio = if let Some(ratio) = Self::liquidation_ratio(currency_id) {
ratio
} else {
T::DefaultLiquidationRatio::get()
};
let liquidation_ratio = Self::liquidation_ratio(currency_id).unwrap_or_else(T::DefaultLiquidationRatio::get);
ensure!(collateral_ratio < liquidation_ratio, Error::CollateralRatioStillSafe);

// grab collaterals and debits from unsafe cdp
Expand All @@ -221,21 +212,9 @@ impl<T: Trait> Module<T> {
let bad_debt = DebitExchangeRateConvertor::<T>::convert((currency_id, debit_balance));
let mut target = bad_debt;
if let Some(penalty_ratio) = Self::liquidation_penalty(currency_id) {
target = target
.checked_add(
&penalty_ratio
.checked_mul_int(&target)
.unwrap_or(BalanceOf::<T>::max_value()),
)
.unwrap_or(BalanceOf::<T>::max_value());
target = target.saturating_add(penalty_ratio.saturating_mul_int(&target));
}
T::AuctionManagerHandler::new_collateral_auction(
who.clone(),
currency_id,
collateral_balance,
target,
bad_debt,
);
T::AuctionManagerHandler::new_collateral_auction(&who, currency_id, collateral_balance, target, bad_debt);
Self::deposit_event(RawEvent::LiquidateUnsafeCdp(
currency_id,
who,
Expand Down
2 changes: 1 addition & 1 deletion modules/honzon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ decl_module! {
) {
let who = ensure_signed(origin).map_err(|_| Error::AccountUnSigned)?;

<cdp_engine::Module<T>>::update_position(who.clone(), currency_id, collateral, debit).map_err(|_| Error::UpdatePositionFailed)?;
<cdp_engine::Module<T>>::update_position(&who, currency_id, collateral, debit).map_err(|_| Error::UpdatePositionFailed)?;

Self::deposit_event(RawEvent::UpdateVault(who, currency_id, collateral, debit));
}
Expand Down
2 changes: 1 addition & 1 deletion modules/support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub trait AuctionManager<AccountId> {
type Balance;

fn new_collateral_auction(
who: AccountId,
who: &AccountId,
currency_id: Self::CurrencyId,
amount: Self::Balance,
target: Self::Balance,
Expand Down
18 changes: 9 additions & 9 deletions modules/vaults/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,46 +103,46 @@ impl<T: Trait> Module<T> {

// mulate collaterals and debits and then mulate stable coin
pub fn update_position(
who: T::AccountId,
who: &T::AccountId,
currency_id: CurrencyIdOf<T>,
collaterals: AmountOf<T>,
debits: DebitAmountOf<T>,
) -> result::Result<(), Error> {
// ensure mutate safe
Self::check_add_and_sub(&who, currency_id, collaterals, debits)?;
Self::check_add_and_sub(who, currency_id, collaterals, debits)?;

// ensure debits cap
T::RiskManager::check_debit_cap(currency_id, debits).map_err(|_| Error::ExceedDebitValueHardCap)?;

// ensure cdp safe
T::RiskManager::check_position_adjustment(&who, currency_id, collaterals, debits)
T::RiskManager::check_position_adjustment(who, currency_id, collaterals, debits)
.map_err(|_| Error::PositionWillUnsafe)?;

// ensure account has sufficient balance
Self::check_balance(&who, currency_id, collaterals)?;
Self::check_balance(who, currency_id, collaterals)?;

// amount -> balance
let collateral_balance =
TryInto::<BalanceOf<T>>::try_into(collaterals.abs()).map_err(|_| Error::AmountIntoBalanceFailed)?;

// update stable coin
T::DebitCurrency::update_balance(currency_id, &who, debits).map_err(|_| Error::UpdateStableCoinFailed)?;
T::DebitCurrency::update_balance(currency_id, who, debits).map_err(|_| Error::UpdateStableCoinFailed)?;

let module_account = Self::account_id();
// update collateral asset
if collaterals.is_positive() {
T::Currency::transfer(currency_id, &who, &module_account, collateral_balance)
T::Currency::transfer(currency_id, who, &module_account, collateral_balance)
.expect("Will never fail ensured by check_balance");
} else {
T::Currency::transfer(currency_id, &module_account, &who, collateral_balance)
T::Currency::transfer(currency_id, &module_account, who, collateral_balance)
.expect("Will never fail ensured by check_balance");
}

// mutate collaterals and debits
Self::update_vault(&who, currency_id, collaterals, debits)
Self::update_vault(who, currency_id, collaterals, debits)
.expect("Will never fail ensured by check_add_and_sub");

Self::deposit_event(RawEvent::UpdatePosition(who, currency_id, collaterals, debits));
Self::deposit_event(RawEvent::UpdatePosition(who.clone(), currency_id, collaterals, debits));

Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion orml
Submodule orml updated from 30bfc6 to cf54a9

0 comments on commit f36df9d

Please sign in to comment.