Skip to content

Commit

Permalink
Merge pull request #14 from blockworks-foundation/borrow_rounding
Browse files Browse the repository at this point in the history
Fixed settle borrow rounding error
  • Loading branch information
dafyddd committed Apr 22, 2021
2 parents bed8980 + a28d392 commit 896a3c6
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 16 deletions.
2 changes: 1 addition & 1 deletion cli/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion program/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion program/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "mango"
version = "0.2.4"
version = "0.2.5"
authors = ["blockworks"]
edition = "2018"

Expand Down
28 changes: 15 additions & 13 deletions program/src/processor.rs
Expand Up @@ -1548,21 +1548,23 @@ fn settle_borrow_unchecked(
token_index: usize,
quantity: u64
) -> MangoResult<()> {
let index: &MangoIndex = &mango_group.indexes[token_index];

let native_borrow = margin_account.get_native_borrow(index, token_index);
let native_deposit = margin_account.get_native_deposit(index, token_index);

let quantity = cmp::min(cmp::min(quantity, native_borrow), native_deposit);

let borr_settle = U64F64::from_num(quantity) / index.borrow;
let dep_settle = U64F64::from_num(quantity) / index.deposit;

checked_sub_deposit(mango_group, margin_account, token_index, dep_settle)?;
checked_sub_borrow(mango_group, margin_account, token_index, borr_settle)?;
let deposit_index = mango_group.indexes[token_index].deposit;
let borrow_index = mango_group.indexes[token_index].borrow;
let native_borrow: U64F64 = margin_account.borrows[token_index] * borrow_index;
let native_deposit: U64F64 = margin_account.deposits[token_index] * deposit_index;
let quantity = U64F64::from_num(quantity);

let quantity = min(quantity, native_deposit);
if quantity >= native_borrow { // Reduce borrows to 0 to prevent rounding related dust
// NOTE: native_borrow / index.borrow is same as margin_account.borrows[token_index]
checked_sub_deposit(mango_group, margin_account, token_index, native_borrow / deposit_index)?;
checked_sub_borrow(mango_group, margin_account, token_index, margin_account.borrows[token_index])?;
} else {
checked_sub_deposit(mango_group, margin_account, token_index, quantity / deposit_index)?;
checked_sub_borrow(mango_group, margin_account, token_index, quantity / borrow_index)?;
}

// No need to check collateralization ratio or deposits/borrows validity

Ok(())

}
Expand Down

0 comments on commit 896a3c6

Please sign in to comment.