Skip to content

Commit

Permalink
fix division_by_zero issue
Browse files Browse the repository at this point in the history
  • Loading branch information
lemunozm committed May 23, 2024
1 parent 967584d commit 2a691e9
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
6 changes: 6 additions & 0 deletions pallets/loans/src/entities/pricing/external.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,12 @@ impl<T: Config> ExternalActivePricing<T> {
price_last_updated: Seconds,
) -> Result<T::Balance, DispatchError> {
if self.info.with_linear_pricing {
if min(price_last_updated, maturity) == maturity {
// We can not have 2 'xs' with different 'y' in a rect.
// That only happens at maturity
return Ok(self.info.notional);
}

Ok(cfg_utils::math::y_coord_in_rect(
(min(price_last_updated, maturity), price),
(maturity, self.info.notional),
Expand Down
2 changes: 1 addition & 1 deletion pallets/loans/src/tests/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ pub const POLICY_PERCENTAGE: f64 = 0.5;
pub const POLICY_PENALTY: f64 = 0.5;
pub const REGISTER_PRICE_ID: PriceId = 42;
pub const UNREGISTER_PRICE_ID: PriceId = 88;
pub const PRICE_VALUE: Balance = 998;
pub const PRICE_VALUE: Balance = 980;
pub const NOTIONAL: Balance = 1000;
pub const QUANTITY: Quantity = Quantity::from_rational(12, 1);
pub const CHANGE_ID: ChangeId = H256::repeat_byte(0x42);
Expand Down
21 changes: 19 additions & 2 deletions pallets/loans/src/tests/repay_loan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -814,9 +814,13 @@ fn with_unregister_price_id_and_oracle_not_required() {
}

#[test]
fn with_external_pricing_and_overdue() {
fn with_external_pricing() {
new_test_ext().execute_with(|| {
let loan_id = util::create_loan(LoanInfo {
pricing: Pricing::External(ExternalPricing {
price_id: UNREGISTER_PRICE_ID,
..util::base_external_pricing()
}),
..util::base_external_loan()
});

Expand All @@ -839,8 +843,21 @@ fn with_external_pricing_and_overdue() {
.unwrap()
};

// Repay and check time without advance time
assert_ok!(Loans::repay(
RuntimeOrigin::signed(BORROWER),
POOL_A,
loan_id,
repay_amount.clone()
));
assert_eq!(current_price(), PRICE_VALUE);

// In the middle of the line
advance_time(YEAR / 2);
assert_eq!(current_price(), PRICE_VALUE + (NOTIONAL - PRICE_VALUE) / 2);

// BEFORE: the loan not yet overdue
advance_time(YEAR - DAY);
advance_time(YEAR / 2 - DAY);
assert_ok!(Loans::repay(
RuntimeOrigin::signed(BORROWER),
POOL_A,
Expand Down

0 comments on commit 2a691e9

Please sign in to comment.