Skip to content

Commit c643a50

Browse files
committed
fix expired position
1 parent e40563e commit c643a50

File tree

1 file changed

+31
-9
lines changed
  • programs/drift/src/controller

1 file changed

+31
-9
lines changed

programs/drift/src/controller/amm.rs

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -771,15 +771,15 @@ pub fn update_pool_balances(
771771

772772
pub fn update_pnl_pool_and_user_balance(
773773
market: &mut PerpMarket,
774-
bank: &mut SpotMarket,
774+
quote_spot_market: &mut SpotMarket,
775775
user: &mut User,
776776
unrealized_pnl_with_fee: i128,
777777
) -> DriftResult<i128> {
778778
let pnl_to_settle_with_user = if unrealized_pnl_with_fee > 0 {
779779
unrealized_pnl_with_fee.min(
780780
get_token_amount(
781781
market.pnl_pool.scaled_balance,
782-
bank,
782+
quote_spot_market,
783783
market.pnl_pool.balance_type(),
784784
)?
785785
.cast()?,
@@ -810,14 +810,36 @@ pub fn update_pnl_pool_and_user_balance(
810810
return Ok(0);
811811
}
812812

813-
let user_spot_position = user.get_quote_spot_position_mut();
813+
let is_isolated_position = user.get_perp_position(market.market_index)?.is_isolated();
814+
if is_isolated_position {
815+
let perp_position = user.force_get_isolated_perp_position_mut(market.market_index)?;
816+
let perp_position_token_amount = perp_position.get_isolated_token_amount(quote_spot_market)?;
817+
818+
if pnl_to_settle_with_user < 0 {
819+
validate!(
820+
perp_position_token_amount >= pnl_to_settle_with_user.unsigned_abs(),
821+
ErrorCode::InsufficientCollateral,
822+
"user has insufficient deposit for market {}",
823+
market.market_index
824+
)?;
825+
}
814826

815-
transfer_spot_balances(
816-
pnl_to_settle_with_user,
817-
bank,
818-
&mut market.pnl_pool,
819-
user_spot_position,
820-
)?;
827+
transfer_spot_balances(
828+
pnl_to_settle_with_user,
829+
quote_spot_market,
830+
&mut market.pnl_pool,
831+
perp_position,
832+
)?;
833+
} else {
834+
let user_spot_position = user.get_quote_spot_position_mut();
835+
836+
transfer_spot_balances(
837+
pnl_to_settle_with_user,
838+
quote_spot_market,
839+
&mut market.pnl_pool,
840+
user_spot_position,
841+
)?;
842+
}
821843

822844
Ok(pnl_to_settle_with_user)
823845
}

0 commit comments

Comments
 (0)