From 26247d6b4a5ad3a1180ed3ac89736126b5032179 Mon Sep 17 00:00:00 2001 From: wangjj9219 <183318287@qq.com> Date: Tue, 1 Mar 2022 17:23:04 +0800 Subject: [PATCH] Optimized calculations t avoid error caused by division missing --- modules/cdp-engine/src/lib.rs | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/modules/cdp-engine/src/lib.rs b/modules/cdp-engine/src/lib.rs index 95a48efba1..1703396a2a 100644 --- a/modules/cdp-engine/src/lib.rs +++ b/modules/cdp-engine/src/lib.rs @@ -1038,19 +1038,30 @@ impl Pallet { // update CDP state let collateral_adjustment = >::amount_try_from_balance(decrease_collateral)?.saturating_neg(); let previous_debit_value = Self::get_debit_value(currency_id, debit); - let decrease_debit_value = actual_stable_amount.min(previous_debit_value); - let refund_stable = actual_stable_amount.saturating_sub(decrease_debit_value); - let decrease_debit_balance = Self::try_convert_to_debit_balance(currency_id, decrease_debit_value) - .ok_or(Error::::ConvertDebitBalanceFailed)?; + let (decrease_debit_value, decrease_debit_balance) = if actual_stable_amount >= previous_debit_value { + // refund extra stable coin to the CDP owner + ::Currency::transfer( + stable_currency_id, + &loans_module_account, + who, + actual_stable_amount.saturating_sub(previous_debit_value), + )?; + + (previous_debit_value, debit) + } else { + ( + actual_stable_amount, + Self::try_convert_to_debit_balance(currency_id, actual_stable_amount) + .ok_or(Error::::ConvertDebitBalanceFailed)?, + ) + }; + let debit_adjustment = >::amount_try_from_balance(decrease_debit_balance)?.saturating_neg(); >::update_loan(who, currency_id, collateral_adjustment, debit_adjustment)?; // repay the debit of CDP ::CDPTreasury::burn_debit(&loans_module_account, decrease_debit_value)?; - // refund extra stable coin to the CDP owner - ::Currency::transfer(stable_currency_id, &loans_module_account, who, refund_stable)?; - // check the CDP if is still at valid risk. Self::check_position_valid( currency_id,