Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

program: settle_pnls that handles invalid oracle and efficient cus #1030

Merged
merged 8 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 86 additions & 60 deletions programs/drift/src/controller/pnl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use crate::state::oracle_map::OracleMap;
use crate::state::paused_operations::PerpOperation;
use crate::state::perp_market::MarketStatus;
use crate::state::perp_market_map::PerpMarketMap;
use crate::state::settle_pnl_mode::SettlePnlMode;
use crate::state::spot_market::{SpotBalance, SpotBalanceType};
use crate::state::spot_market_map::SpotMarketMap;
use crate::state::state::State;
Expand All @@ -56,6 +57,8 @@ pub fn settle_pnl(
oracle_map: &mut OracleMap,
clock: &Clock,
state: &State,
meets_margin_requirement: Option<bool>,
mode: SettlePnlMode,
) -> DriftResult {
validate!(!user.is_bankrupt(), ErrorCode::UserBankrupt)?;
let now = clock.unix_timestamp;
Expand Down Expand Up @@ -119,14 +122,23 @@ pub fn settle_pnl(
}
}
} else if unrealized_pnl < 0 {
// may already be cached
let meets_margin_requirement = match meets_margin_requirement {
Some(meets_margin_requirement) => meets_margin_requirement,
None => meets_maintenance_margin_requirement(
user,
perp_market_map,
spot_market_map,
oracle_map,
)?,
};

// 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);
if !meets_margin_requirement {
return mode.result(
ErrorCode::InsufficientCollateralForSettlingPNL,
"Does not meet margin requirement",
);
Copy link
Member

@0xbigz 0xbigz May 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should market_index info get propagated if errors get hit for logs?

}
}

Expand All @@ -151,55 +163,63 @@ pub fn settle_pnl(
if !is_oracle_valid_for_action(oracle_validity, Some(DriftAction::SettlePnl))?
|| !perp_market.is_price_divergence_ok_for_settle_pnl(oracle_price)?
{
validate!(
perp_market.amm.last_oracle_valid,
ErrorCode::InvalidOracle,
"Oracle Price detected as invalid ({}) on last perp market update",
oracle_validity
)?;

validate!(
oracle_map.slot == perp_market.amm.last_update_slot,
ErrorCode::AMMNotUpdatedInSameSlot,
"Market={} AMM must be updated in a prior instruction within same slot (current={} != amm={}, last_oracle_valid={})",
market_index,
oracle_map.slot,
perp_market.amm.last_update_slot,
perp_market.amm.last_oracle_valid
)?;
if !perp_market.amm.last_oracle_valid {
let msg = format!(
"Oracle Price detected as invalid ({}) on last perp market update for Market = {}",
oracle_validity,
market_index
);
return mode.result(ErrorCode::InvalidOracle, &msg);
}

if oracle_map.slot != perp_market.amm.last_update_slot {
let msg = format!(
"Market={} AMM must be updated in a prior instruction within same slot (current={} != amm={}, last_oracle_valid={})",
market_index,
oracle_map.slot,
perp_market.amm.last_update_slot,
perp_market.amm.last_oracle_valid
);
return mode.result(ErrorCode::AMMNotUpdatedInSameSlot, &msg);
}
}
}
}

validate!(
!perp_market.is_operation_paused(PerpOperation::SettlePnl),
ErrorCode::InvalidMarketStatusToSettlePnl,
"Cannot settle pnl under current market = {} status",
market_index
)?;
if perp_market.is_operation_paused(PerpOperation::SettlePnl) {
let msg = format!(
"Cannot settle pnl under current market = {} status",
market_index
);
return mode.result(ErrorCode::InvalidMarketStatusToSettlePnl, &msg);
}

if user.perp_positions[position_index].base_asset_amount != 0 {
validate!(
!perp_market.is_operation_paused(PerpOperation::SettlePnlWithPosition),
ErrorCode::InvalidMarketStatusToSettlePnl,
"Cannot settle pnl with position under current market = {} operation paused",
market_index
)?;
if perp_market.is_operation_paused(PerpOperation::SettlePnlWithPosition) {
let msg = format!(
"Cannot settle pnl with position under current market = {} operation paused",
market_index
);
return mode.result(ErrorCode::InvalidMarketStatusToSettlePnl, &msg);
}

validate!(
perp_market.status == MarketStatus::Active,
ErrorCode::InvalidMarketStatusToSettlePnl,
"Cannot settle pnl with position under non-Active current market = {} status",
market_index
)?;
if perp_market.status != MarketStatus::Active {
let msg = format!(
"Cannot settle pnl with position under non-Active current market = {} status",
market_index
);
return mode.result(ErrorCode::InvalidMarketStatusToSettlePnl, &msg);
}
} else {
validate!(
perp_market.status == MarketStatus::Active
|| perp_market.status == MarketStatus::ReduceOnly,
ErrorCode::InvalidMarketStatusToSettlePnl,
"Cannot settle pnl under current market = {} status (neither Active or ReduceOnly)",
market_index
)?;
if perp_market.status != MarketStatus::Active
&& perp_market.status != MarketStatus::ReduceOnly
{
let msg = format!(
"Cannot settle pnl under current market = {} status (neither Active or ReduceOnly)",
market_index
);
return mode.result(ErrorCode::InvalidMarketStatusToSettlePnl, &msg);
}
}

let pnl_pool_token_amount = get_token_amount(
Expand Down Expand Up @@ -237,25 +257,31 @@ pub fn settle_pnl(
user_unsettled_pnl,
now,
)?;

if user_unsettled_pnl == 0 {
msg!("User has no unsettled pnl for market {}", market_index);
return Ok(());
let msg = format!("User has no unsettled pnl for market {}", market_index);
return mode.result(ErrorCode::NoUnsettledPnl, &msg);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it bad these dont always return OK? do we need update_pool_balances to go through above?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only the 'MUST' will cause update_pool_balances to not go through? think its fine to just have 'TRY' allow that

} else if pnl_to_settle_with_user == 0 {
msg!(
let msg = format!(
"Pnl Pool cannot currently settle with user for market {}",
market_index
);
return Ok(());
return mode.result(ErrorCode::PnlPoolCantSettleUser, &msg);
}

validate!(
pnl_to_settle_with_user < 0
|| max_pnl_pool_excess > 0
|| (pnl_to_settle_with_user > 0 && user.is_being_liquidated())
|| (user.authority.eq(authority) || user.delegate.eq(authority)),
ErrorCode::UserMustSettleTheirOwnPositiveUnsettledPNL,
"User must settle their own unsettled pnl when its positive and pnl pool not in excess"
)?;
let user_must_settle_themself = pnl_to_settle_with_user > 0
&& max_pnl_pool_excess < 0
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this be <=

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. low chance excess is exactly = 0, even so not sure its necessary since theres no incentive for settle run

&& !user.is_being_liquidated()
&& !user.authority.eq(authority)
&& !user.delegate.eq(authority);

if user_must_settle_themself {
let msg = format!(
"Market = {} user must settle their own unsettled pnl when its positive and pnl pool not in excess",
market_index
);
return mode.result(ErrorCode::UserMustSettleTheirOwnPositiveUnsettledPNL, &msg);
}

update_spot_balances(
pnl_to_settle_with_user.unsigned_abs(),
Expand Down
4 changes: 4 additions & 0 deletions programs/drift/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,10 @@ pub enum ErrorCode {
CantReclaimRent,
#[msg("InsuranceFundOperationPaused")]
InsuranceFundOperationPaused,
#[msg("NoUnsettledPnl")]
NoUnsettledPnl,
#[msg("PnlPoolCantSettleUser")]
PnlPoolCantSettleUser,
}

#[macro_export]
Expand Down
94 changes: 92 additions & 2 deletions programs/drift/src/instructions/keeper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::instructions::constraints::*;
use crate::instructions::optional_accounts::{load_maps, AccountMaps};
use crate::math::constants::QUOTE_SPOT_MARKET_INDEX;
use crate::math::insurance::if_shares_to_vault_amount;
use crate::math::margin::calculate_user_equity;
use crate::math::margin::{calculate_user_equity, meets_maintenance_margin_requirement};
use crate::math::orders::{estimate_price_from_side, find_bids_and_asks_from_users};
use crate::math::spot_withdraw::validate_spot_market_vault_amount;
use crate::optional_accounts::update_prelaunch_oracle;
Expand All @@ -20,8 +20,9 @@ use crate::state::paused_operations::PerpOperation;
use crate::state::perp_market::{MarketStatus, PerpMarket};
use crate::state::perp_market_map::{
get_market_set_for_user_positions, get_market_set_from_list, get_writable_perp_market_set,
MarketSet, PerpMarketMap,
get_writable_perp_market_set_from_vec, MarketSet, PerpMarketMap,
};
use crate::state::settle_pnl_mode::SettlePnlMode;
use crate::state::spot_fulfillment_params::SpotFulfillmentParams;
use crate::state::spot_market::SpotMarket;
use crate::state::spot_market_map::{
Expand Down Expand Up @@ -463,6 +464,8 @@ pub fn handle_settle_pnl(ctx: Context<SettlePNL>, market_index: u16) -> Result<(
&mut oracle_map,
&clock,
state,
None,
SettlePnlMode::MustSettle,
)
.map(|_| ErrorCode::InvalidOracleForSettlePnl)?;

Expand All @@ -475,6 +478,93 @@ pub fn handle_settle_pnl(ctx: Context<SettlePNL>, market_index: u16) -> Result<(
Ok(())
}

#[access_control(
settle_pnl_not_paused(&ctx.accounts.state)
)]
pub fn handle_settle_pnls(
ctx: Context<SettlePNL>,
market_indexes: Vec<u16>,
mode: SettlePnlMode,
) -> Result<()> {
let clock = Clock::get()?;
let state = &ctx.accounts.state;

let user_key = ctx.accounts.user.key();
let user = &mut load_mut!(ctx.accounts.user)?;

let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&get_writable_perp_market_set_from_vec(&market_indexes),
&get_writable_spot_market_set(QUOTE_SPOT_MARKET_INDEX),
clock.slot,
Some(state.oracle_guard_rails),
)?;

let meets_margin_requirement = meets_maintenance_margin_requirement(
0xbigz marked this conversation as resolved.
Show resolved Hide resolved
user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
)?;

for market_index in market_indexes.iter() {
let market_in_settlement =
perp_market_map.get_ref(market_index)?.status == MarketStatus::Settlement;

if market_in_settlement {
amm_not_paused(state)?;

controller::pnl::settle_expired_position(
*market_index,
user,
&user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
&clock,
state,
)?;

user.update_last_active_slot(clock.slot);
} else {
controller::repeg::update_amm(
*market_index,
&perp_market_map,
&mut oracle_map,
state,
&clock,
)
.map(|_| ErrorCode::InvalidOracleForSettlePnl)?;

controller::pnl::settle_pnl(
*market_index,
user,
ctx.accounts.authority.key,
&user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
&clock,
state,
Some(meets_margin_requirement),
mode,
)
.map(|_| ErrorCode::InvalidOracleForSettlePnl)?;

user.update_last_active_slot(clock.slot);
}
}

let spot_market = spot_market_map.get_quote_spot_market()?;
validate_spot_market_vault_amount(&spot_market, ctx.accounts.spot_market_vault.amount)?;

Ok(())
}

#[access_control(
funding_not_paused(&ctx.accounts.state)
)]
Expand Down
1 change: 1 addition & 0 deletions programs/drift/src/state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub mod order_params;
pub mod paused_operations;
pub mod perp_market;
pub mod perp_market_map;
pub mod settle_pnl_mode;
pub mod spot_fulfillment_params;
pub mod spot_market;
pub mod spot_market_map;
Expand Down
8 changes: 8 additions & 0 deletions programs/drift/src/state/perp_market_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,14 @@ pub fn get_writable_perp_market_set(market_index: u16) -> MarketSet {
writable_markets
}

pub fn get_writable_perp_market_set_from_vec(market_indexes: &Vec<u16>) -> MarketSet {
let mut writable_markets = MarketSet::new();
for market_index in market_indexes.iter() {
writable_markets.insert(*market_index);
}
writable_markets
}

pub fn get_market_set_from_list(market_indexes: [u16; 5]) -> MarketSet {
let mut writable_markets = MarketSet::new();
for market_index in market_indexes.iter() {
Expand Down
33 changes: 33 additions & 0 deletions programs/drift/src/state/settle_pnl_mode.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use crate::error::{DriftResult, ErrorCode};
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::msg;
use std::panic::Location;

#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq)]
pub enum SettlePnlMode {
MustSettle,
TrySettle,
}

impl SettlePnlMode {
#[track_caller]
#[inline(always)]
pub fn result(self, error_code: ErrorCode, msg: &str) -> DriftResult {
let caller = Location::caller();
msg!(msg);
msg!(
"Error {:?} at {}:{}",
error_code,
caller.file(),
caller.line()
);
match self {
SettlePnlMode::MustSettle => {
return Err(error_code);
}
SettlePnlMode::TrySettle => {
return Ok(());
}
}
}
}
Loading