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: add pool ids to spot market #1250

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@
"prettify": "prettier --check './sdk/src/**/*.ts' './tests/**.ts' './cli/**.ts'",
"prettify:fix": "prettier --write './sdk/src/**/*.ts' './tests/**.ts' './cli/**.ts'",
"lint": "eslint . --ext ts --quiet",
"lint:fix": "eslint . --ext ts --fix"
"lint:fix": "eslint . --ext ts --fix",
"update-idl": "cp target/idl/drift.json sdk/src/idl/drift.json"
},
"engines": {
"node": ">=12"
Expand Down
44 changes: 44 additions & 0 deletions programs/drift/src/controller/liquidation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,13 @@ pub fn liquidate_perp(
"liquidator bankrupt",
)?;

validate!(
liquidator.pool_id == 0,
ErrorCode::InvalidPoolId,
"liquidator pool id ({}) != 0",
liquidator.pool_id
)?;

let market = perp_market_map.get_ref(&market_index)?;

validate!(
Expand Down Expand Up @@ -690,6 +697,13 @@ pub fn liquidate_perp_with_fill(
"user bankrupt",
)?;

validate!(
liquidator.pool_id == 0,
ErrorCode::InvalidPoolId,
"liquidator pool id ({}) != 0",
liquidator.pool_id
)?;

validate!(
!liquidator.is_bankrupt(),
ErrorCode::UserBankrupt,
Expand Down Expand Up @@ -1155,6 +1169,14 @@ pub fn liquidate_spot(
asset_market_index
)?;

validate!(
liquidator.pool_id == asset_spot_market.pool_id,
ErrorCode::InvalidPoolId,
"liquidator pool id ({}) != asset spot market pool id ({})",
liquidator.pool_id,
asset_spot_market.pool_id
)?;

drop(asset_spot_market);

let liability_spot_market = spot_market_map.get_ref(&liability_market_index)?;
Expand All @@ -1166,6 +1188,14 @@ pub fn liquidate_spot(
liability_market_index
)?;

validate!(
liquidator.pool_id == liability_spot_market.pool_id,
ErrorCode::InvalidPoolId,
"liquidator pool id ({}) != liablity spot market pool id ({})",
liquidator.pool_id,
liability_spot_market.pool_id
)?;

drop(liability_spot_market);

// validate user and liquidator have spot balances
Expand Down Expand Up @@ -1687,6 +1717,13 @@ pub fn liquidate_borrow_for_perp_pnl(
"liquidator bankrupt",
)?;

validate!(
liquidator.pool_id == 0,
ErrorCode::InvalidPoolId,
"liquidator pool id ({}) != 0",
liquidator.pool_id
)?;

let perp_market = perp_market_map.get_ref(&perp_market_index)?;

validate!(
Expand Down Expand Up @@ -2156,6 +2193,13 @@ pub fn liquidate_perp_pnl_for_deposit(
"liquidator bankrupt",
)?;

validate!(
liquidator.pool_id == 0,
ErrorCode::InvalidPoolId,
"liquidator pool id ({}) != 0",
liquidator.pool_id
)?;

let asset_spot_market = spot_market_map.get_ref(&asset_market_index)?;

validate!(
Expand Down
30 changes: 30 additions & 0 deletions programs/drift/src/controller/orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,13 @@ pub fn place_perp_order(
"Market is being initialized"
)?;

validate!(
user.pool_id == 0,
ErrorCode::InvalidPoolId,
"user pool id ({}) != 0",
user.pool_id
)?;

validate!(
!market.is_in_settlement(now),
ErrorCode::MarketPlaceOrderPaused,
Expand Down Expand Up @@ -1199,6 +1206,14 @@ pub fn fill_perp_order(
let is_filler_maker = makers_and_referrer.0.contains_key(&filler_key);
let (mut filler, mut filler_stats) = if !is_filler_maker && !is_filler_taker {
let filler = load_mut!(filler)?;

validate!(
filler.pool_id == 0,
ErrorCode::InvalidPoolId,
"filler pool id ({}) != 0",
filler.pool_id
)?;

if filler.authority != user.authority {
(Some(filler), Some(load_mut!(filler_stats)?))
} else {
Expand Down Expand Up @@ -3465,6 +3480,13 @@ pub fn place_spot_order(
let force_reduce_only = spot_market.is_reduce_only();
let step_size = spot_market.order_step_size;

validate!(
user.pool_id == 0,
ErrorCode::InvalidPoolId,
"user pool id ({}) != 0",
user.pool_id
)?;

validate!(
!matches!(spot_market.status, MarketStatus::Initialized),
ErrorCode::MarketBeingInitialized,
Expand Down Expand Up @@ -3746,6 +3768,14 @@ pub fn fill_spot_order(
let is_filler_maker = makers_and_referrer.0.contains_key(&filler_key);
let (mut filler, mut filler_stats) = if !is_filler_maker && !is_filler_taker {
let filler = load_mut!(filler)?;

validate!(
filler.pool_id == 0,
ErrorCode::InvalidPoolId,
"filler pool id ({}) != 0",
filler.pool_id
)?;

if filler.authority != user.authority {
(Some(filler), Some(load_mut!(filler_stats)?))
} else {
Expand Down
2 changes: 2 additions & 0 deletions programs/drift/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,8 @@ pub enum ErrorCode {
InvalidRFQOrder,
#[msg("RFQ matches must be valid")]
InvalidRFQMatch,
#[msg("Invalid pool id")]
InvalidPoolId,
}

#[macro_export]
Expand Down
32 changes: 24 additions & 8 deletions programs/drift/src/instructions/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,12 +157,6 @@ pub fn handle_initialize_spot_market(
ErrorCode::InvalidSpotMarketInitialization,
"For OracleSource::QuoteAsset, oracle must be default public key"
)?;

validate!(
spot_market_index == QUOTE_SPOT_MARKET_INDEX,
ErrorCode::InvalidSpotMarketInitialization,
"For OracleSource::QuoteAsset, spot_market_index must be QUOTE_SPOT_MARKET_INDEX"
)?;
} else {
OracleMap::validate_oracle_account_info(&ctx.accounts.oracle)?;
}
Expand Down Expand Up @@ -314,7 +308,8 @@ pub fn handle_initialize_spot_market(
fuel_boost_maker: 0,
fuel_boost_insurance: 0,
token_program,
padding: [0; 41],
pool_id: 0,
padding: [0; 40],
insurance_fund: InsuranceFund {
vault: *ctx.accounts.insurance_fund_vault.to_account_info().key,
unstaking_period: THIRTEEN_DAY,
Expand All @@ -327,6 +322,27 @@ pub fn handle_initialize_spot_market(
Ok(())
}

#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_pool_id(
ctx: Context<AdminUpdateSpotMarket>,
pool_id: u8,
) -> Result<()> {
let mut spot_market = load_mut!(ctx.accounts.spot_market)?;
msg!("updating spot market {} expiry", spot_market.market_index);

validate!(
spot_market.status == MarketStatus::Initialized,
ErrorCode::DefaultError,
"Market must be just initialized to update pool"
)?;

spot_market.pool_id = pool_id;

Ok(())
}

pub fn handle_initialize_serum_fulfillment_config(
ctx: Context<InitializeSerumFulfillmentConfig>,
market_index: u16,
Expand Down Expand Up @@ -858,7 +874,7 @@ pub fn handle_initialize_perp_market(
fuel_boost_position: 0,
fuel_boost_taker: 0,
fuel_boost_maker: 0,
padding1: 0,
pool_id: 0,
high_leverage_margin_ratio_initial: 0,
high_leverage_margin_ratio_maintenance: 0,
padding: [0; 38],
Expand Down
52 changes: 52 additions & 0 deletions programs/drift/src/instructions/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,14 @@ pub fn handle_deposit<'c: 'info, 'info>(
let mut spot_market = spot_market_map.get_ref_mut(&market_index)?;
let oracle_price_data = &oracle_map.get_price_data(&spot_market.oracle)?.clone();

validate!(
user.pool_id == spot_market.pool_id,
ErrorCode::InvalidPoolId,
"user pool id ({}) != market pool id ({})",
user.pool_id,
spot_market.pool_id
)?;

validate!(
!matches!(spot_market.status, MarketStatus::Initialized),
ErrorCode::MarketBeingInitialized,
Expand Down Expand Up @@ -703,6 +711,14 @@ pub fn handle_transfer_deposit<'c: 'info, 'info>(
{
let spot_market = &mut spot_market_map.get_ref_mut(&market_index)?;

validate!(
from_user.pool_id == spot_market.pool_id,
ErrorCode::InvalidPoolId,
"user pool id ({}) != market pool id ({})",
from_user.pool_id,
spot_market.pool_id
)?;

from_user.increment_total_withdraws(
amount,
oracle_price,
Expand Down Expand Up @@ -770,6 +786,14 @@ pub fn handle_transfer_deposit<'c: 'info, 'info>(
{
let spot_market = &mut spot_market_map.get_ref_mut(&market_index)?;

validate!(
to_user.pool_id == spot_market.pool_id,
ErrorCode::InvalidPoolId,
"user pool id ({}) != market pool id ({})",
to_user.pool_id,
spot_market.pool_id
)?;

to_user.increment_total_deposits(
amount,
oracle_price,
Expand Down Expand Up @@ -2054,6 +2078,34 @@ pub fn handle_update_user_margin_trading_enabled<'c: 'info, 'info>(
Ok(())
}

pub fn handle_update_user_pool_id<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateUser<'info>>,
_sub_account_id: u16,
pool_id: u8,
) -> Result<()> {
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
..
} = load_maps(
remaining_accounts_iter,
&MarketSet::new(),
&MarketSet::new(),
Clock::get()?.slot,
None,
)?;

let mut user = load_mut!(ctx.accounts.user)?;
user.pool_id = pool_id;

// will throw if user has deposits/positions in other pools
meets_initial_margin_requirement(&user, &perp_market_map, &spot_market_map, &mut oracle_map)?;

Ok(())
}

pub fn handle_update_user_delegate(
ctx: Context<UpdateUser>,
_sub_account_id: u16,
Expand Down
15 changes: 15 additions & 0 deletions programs/drift/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,14 @@ pub mod drift {
handle_update_user_margin_trading_enabled(ctx, _sub_account_id, margin_trading_enabled)
}

pub fn update_user_pool_id<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateUser<'info>>,
_sub_account_id: u16,
pool_id: u8,
) -> Result<()> {
handle_update_user_pool_id(ctx, _sub_account_id, pool_id)
}

pub fn update_user_delegate(
ctx: Context<UpdateUser>,
_sub_account_id: u16,
Expand Down Expand Up @@ -970,6 +978,13 @@ pub mod drift {
handle_update_insurance_fund_unstaking_period(ctx, insurance_fund_unstaking_period)
}

pub fn update_spot_market_pool_id(
ctx: Context<AdminUpdateSpotMarket>,
pool_id: u8,
) -> Result<()> {
handle_update_spot_market_pool_id(ctx, pool_id)
}

pub fn update_spot_market_liquidation_fee(
ctx: Context<AdminUpdateSpotMarket>,
liquidator_fee: u32,
Expand Down
17 changes: 17 additions & 0 deletions programs/drift/src/math/margin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ pub fn calculate_margin_requirement_and_total_collateral_and_liability_info(
0_u32
};

let user_pool_id = user.pool_id;
let user_high_leverage_mode = user.is_high_leverage_mode();

for spot_position in user.spot_positions.iter() {
Expand All @@ -265,6 +266,14 @@ pub fn calculate_margin_requirement_and_total_collateral_and_liability_info(
spot_market.get_max_confidence_interval_multiplier()?,
)?;

validate!(
user_pool_id == spot_market.pool_id,
ErrorCode::InvalidPoolId,
"user pool id ({}) == spot market pool id ({})",
user_pool_id,
spot_market.pool_id,
)?;

calculation.update_all_oracles_valid(is_oracle_valid_for_action(
oracle_validity,
Some(DriftAction::MarginCalc),
Expand Down Expand Up @@ -447,6 +456,14 @@ pub fn calculate_margin_requirement_and_total_collateral_and_liability_info(

let market = &perp_market_map.get_ref(&market_position.market_index)?;

validate!(
user_pool_id == market.pool_id,
ErrorCode::InvalidPoolId,
"user pool id ({}) == perp market pool id ({})",
user_pool_id,
market.pool_id,
)?;

let quote_spot_market = spot_market_map.get_ref(&market.quote_spot_market_index)?;
let (quote_oracle_price_data, quote_oracle_validity) = oracle_map
.get_price_data_and_validity(
Expand Down
Loading
Loading