Skip to content

Commit

Permalink
add to settle_pnl
Browse files Browse the repository at this point in the history
  • Loading branch information
crispheaney committed Jan 9, 2024
1 parent 57294b4 commit 1546850
Showing 1 changed file with 33 additions and 5 deletions.
38 changes: 33 additions & 5 deletions programs/drift/src/controller/pnl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,43 @@ pub fn settle_pnl(
let unrealized_pnl = user.perp_positions[position_index].get_unrealized_pnl(oracle_price)?;

// cannot settle negative pnl this way on a user who is in liquidation territory
if unrealized_pnl < 0
&& !meets_maintenance_margin_requirement(
if user.perp_positions[position_index].is_lp() {
let margin_calc = calculate_margin_requirement_and_total_collateral_and_liability_info(
user,
perp_market_map,
spot_market_map,
oracle_map,
)?
{
return Err(ErrorCode::InsufficientCollateralForSettlingPNL);
MarginContext::standard(MarginRequirementType::Initial).track_open_orders_fraction()?,
)?;

if !margin_calc.meets_margin_requirement() {
attempt_burn_user_lp_shares_for_risk_reduction(
state,
user,
margin_calc,
*user_key,

Check warning on line 92 in programs/drift/src/controller/pnl.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/controller/pnl.rs#L91-L92

Added lines #L91 - L92 were not covered by tests
perp_market_map,
spot_market_map,
oracle_map,
clock,
market_index,
)?;

// if the unrealized pnl is negative, return early after trying to burn shares
if unrealized_pnl < 0 {
return Ok(());

Check warning on line 102 in programs/drift/src/controller/pnl.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/controller/pnl.rs#L101-L102

Added lines #L101 - L102 were not covered by tests
}
}
} else if unrealized_pnl < 0 {
// cannot settle pnl this way on a user who is in liquidation territory
if !(meets_maintenance_margin_requirement(
user,
perp_market_map,
spot_market_map,
oracle_map,
)?) {
return Err(ErrorCode::InsufficientCollateralForSettlingPNL);
}
}

let spot_market = &mut spot_market_map.get_quote_spot_market_mut()?;
Expand Down

0 comments on commit 1546850

Please sign in to comment.