Skip to content

Commit 6e6813a

Browse files
Nour/address comments (#1715)
* low hanging fruit comments * remove pda checks and store lp pool on zero copy accounts * parameterize depeg threshold * make description in lp pool event * update idl for event change
1 parent 99b52ac commit 6e6813a

File tree

13 files changed

+122
-114
lines changed

13 files changed

+122
-114
lines changed

programs/drift/src/instructions/admin.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4732,20 +4732,23 @@ pub fn handle_initialize_lp_pool(
47324732
};
47334733

47344734
let amm_constituent_mapping = &mut ctx.accounts.amm_constituent_mapping;
4735+
amm_constituent_mapping.lp_pool = ctx.accounts.lp_pool.key();
47354736
amm_constituent_mapping.bump = ctx.bumps.amm_constituent_mapping;
47364737
amm_constituent_mapping
47374738
.weights
47384739
.resize_with(0 as usize, AmmConstituentDatum::default);
47394740
amm_constituent_mapping.validate()?;
47404741

47414742
let constituent_target_base = &mut ctx.accounts.constituent_target_base;
4743+
constituent_target_base.lp_pool = ctx.accounts.lp_pool.key();
47424744
constituent_target_base.bump = ctx.bumps.constituent_target_base;
47434745
constituent_target_base
47444746
.targets
47454747
.resize_with(0 as usize, TargetsDatum::default);
47464748
constituent_target_base.validate()?;
47474749

47484750
let consituent_correlations = &mut ctx.accounts.constituent_correlations;
4751+
consituent_correlations.lp_pool = ctx.accounts.lp_pool.key();
47494752
consituent_correlations.bump = ctx.bumps.constituent_correlations;
47504753
consituent_correlations.correlations.resize(0 as usize, 0);
47514754
consituent_correlations.validate()?;
@@ -5005,6 +5008,7 @@ pub fn handle_initialize_constituent<'info>(
50055008
oracle_staleness_threshold: u64,
50065009
cost_to_trade_bps: i32,
50075010
constituent_derivative_index: Option<i16>,
5011+
constituent_derivative_depeg_threshold: u64,
50085012
derivative_weight: u64,
50095013
volatility: u64,
50105014
gamma_execution: u8,
@@ -5056,6 +5060,7 @@ pub fn handle_initialize_constituent<'info>(
50565060
constituent.constituent_index = (constituent_target_base.targets.len() - 1) as u16;
50575061
constituent.next_swap_id = 1;
50585062
constituent.constituent_derivative_index = constituent_derivative_index.unwrap_or(-1);
5063+
constituent.constituent_derivative_depeg_threshold = constituent_derivative_depeg_threshold;
50595064
constituent.derivative_weight = derivative_weight;
50605065
constituent.volatility = volatility;
50615066
constituent.gamma_execution = gamma_execution;

programs/drift/src/instructions/keeper.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,6 @@ use crate::math::constants::QUOTE_PRECISION;
3131
use crate::math::constants::QUOTE_SPOT_MARKET_INDEX;
3232
use crate::math::constants::SPOT_BALANCE_PRECISION;
3333
use crate::math::margin::{calculate_user_equity, meets_settle_pnl_maintenance_margin_requirement};
34-
use crate::math::oracle::is_oracle_valid_for_action;
35-
use crate::math::oracle::DriftAction;
3634
use crate::math::orders::{estimate_price_from_side, find_bids_and_asks_from_users};
3735
use crate::math::position::calculate_base_asset_value_and_pnl_with_oracle_price;
3836
use crate::math::safe_math::SafeMath;
@@ -3311,7 +3309,7 @@ pub struct UpdateAmmCache<'info> {
33113309
pub amm_cache: AccountInfo<'info>,
33123310
#[account(
33133311
owner = crate::ID,
3314-
seeds = [b"spot_market", 0_u16.to_le_bytes().as_ref()],
3312+
seeds = [b"spot_market", QUOTE_SPOT_MARKET_INDEX.to_le_bytes().as_ref()],
33153313
bump,
33163314
)]
33173315
pub quote_market: AccountLoader<'info, SpotMarket>,

programs/drift/src/instructions/lp_pool.rs

Lines changed: 39 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use anchor_spl::token_interface::{Mint, TokenAccount, TokenInterface};
55

66
use crate::{
77
controller::{
8-
self, lp,
8+
self,
99
spot_balance::update_spot_balances,
1010
token::{burn_tokens, mint_tokens},
1111
},
@@ -16,7 +16,7 @@ use crate::{
1616
self,
1717
casting::Cast,
1818
constants::{
19-
BASE_PRECISION_I128, PERCENTAGE_PRECISION_I128, PERCENTAGE_PRECISION_I64,
19+
PERCENTAGE_PRECISION, PERCENTAGE_PRECISION_I128, PERCENTAGE_PRECISION_I64,
2020
PERCENTAGE_PRECISION_U64, PRICE_PRECISION_I128, QUOTE_PRECISION_I128,
2121
},
2222
oracle::{is_oracle_valid_for_action, oracle_validity, DriftAction},
@@ -25,13 +25,12 @@ use crate::{
2525
math_error, msg, safe_decrement, safe_increment,
2626
state::{
2727
constituent_map::{ConstituentMap, ConstituentSet},
28-
events::{LPMintRedeemRecord, LPSwapRecord},
28+
events::{emit_stack, LPMintRedeemRecord, LPSwapRecord},
2929
lp_pool::{
3030
calculate_target_weight, AmmConstituentDatum, AmmConstituentMappingFixed, Constituent,
3131
ConstituentCorrelationsFixed, ConstituentTargetBaseFixed, LPPool, TargetsDatum,
32-
WeightValidationFlags, CONSTITUENT_CORRELATIONS_PDA_SEED,
33-
LP_POOL_SWAP_AUM_UPDATE_DELAY, MAX_AMM_CACHE_STALENESS_FOR_TARGET_CALC,
34-
MAX_CONSTITUENT_ORACLE_SLOT_STALENESS_FOR_AUM,
32+
WeightValidationFlags, LP_POOL_SWAP_AUM_UPDATE_DELAY,
33+
MAX_AMM_CACHE_STALENESS_FOR_TARGET_CALC, MAX_CONSTITUENT_ORACLE_SLOT_STALENESS_FOR_AUM,
3534
},
3635
oracle::OraclePriceData,
3736
oracle_map::OracleMap,
@@ -40,6 +39,7 @@ use crate::{
4039
spot_market::{SpotBalanceType, SpotMarket},
4140
spot_market_map::get_writable_spot_market_set_from_many,
4241
state::State,
42+
traits::Size,
4343
user::MarketType,
4444
zero_copy::{AccountZeroCopy, AccountZeroCopyMut, ZeroCopyLoader},
4545
},
@@ -53,16 +53,14 @@ use crate::controller::spot_balance::update_spot_market_cumulative_interest;
5353
use crate::controller::token::{receive, send_from_program_vault};
5454
use crate::instructions::constraints::*;
5555
use crate::state::lp_pool::{
56-
AMM_MAP_PDA_SEED, CONSTITUENT_PDA_SEED, CONSTITUENT_TARGET_BASE_PDA_SEED,
57-
LP_POOL_TOKEN_VAULT_PDA_SEED,
56+
CONSTITUENT_PDA_SEED, CONSTITUENT_TARGET_BASE_PDA_SEED, LP_POOL_TOKEN_VAULT_PDA_SEED,
5857
};
5958

6059
pub fn handle_update_constituent_target_base<'c: 'info, 'info>(
6160
ctx: Context<'_, '_, 'c, 'info, UpdateConstituentTargetBase<'info>>,
6261
) -> Result<()> {
6362
let slot = Clock::get()?.slot;
6463

65-
let lp_pool = &ctx.accounts.lp_pool.load()?;
6664
let lp_pool_key: &Pubkey = &ctx.accounts.lp_pool.key();
6765
let amm_cache_key: &Pubkey = &ctx.accounts.amm_cache.key();
6866

@@ -87,29 +85,15 @@ pub fn handle_update_constituent_target_base<'c: 'info, 'info>(
8785
)?;
8886

8987
let state = &ctx.accounts.state;
90-
let constituent_target_base_key = &ctx.accounts.constituent_target_base.key();
91-
let amm_mapping_key = &ctx.accounts.amm_constituent_mapping.key();
92-
9388
let mut constituent_target_base: AccountZeroCopyMut<
9489
'_,
9590
TargetsDatum,
9691
ConstituentTargetBaseFixed,
9792
> = ctx.accounts.constituent_target_base.load_zc_mut()?;
98-
99-
let bump = constituent_target_base.fixed.bump;
100-
let expected_pda = &Pubkey::create_program_address(
101-
&[
102-
CONSTITUENT_TARGET_BASE_PDA_SEED.as_ref(),
103-
lp_pool.pubkey.as_ref(),
104-
bump.to_le_bytes().as_ref(),
105-
],
106-
&crate::ID,
107-
)
108-
.map_err(|_| ErrorCode::InvalidPDA)?;
10993
validate!(
110-
expected_pda.eq(constituent_target_base_key),
94+
constituent_target_base.fixed.lp_pool.eq(lp_pool_key),
11195
ErrorCode::InvalidPDA,
112-
"Constituent target weights PDA does not match expected PDA"
96+
"Constituent target base lp pool pubkey does not match lp pool pubkey",
11397
)?;
11498

11599
let num_constituents = constituent_target_base.len();
@@ -124,24 +108,18 @@ pub fn handle_update_constituent_target_base<'c: 'info, 'info>(
124108
AmmConstituentDatum,
125109
AmmConstituentMappingFixed,
126110
> = ctx.accounts.amm_constituent_mapping.load_zc()?;
127-
128-
let amm_mapping_bump = amm_constituent_mapping.fixed.bump;
129-
let expected_map_pda = &Pubkey::create_program_address(
130-
&[
131-
AMM_MAP_PDA_SEED.as_ref(),
132-
lp_pool.pubkey.as_ref(),
133-
amm_mapping_bump.to_le_bytes().as_ref(),
134-
],
135-
&crate::ID,
136-
)
137-
.map_err(|_| ErrorCode::InvalidPDA)?;
138111
validate!(
139-
expected_map_pda.eq(amm_mapping_key),
112+
amm_constituent_mapping.fixed.lp_pool.eq(lp_pool_key),
140113
ErrorCode::InvalidPDA,
141-
"Amm mapping PDA does not match expected PDA"
114+
"Amm constituent mapping lp pool pubkey does not match lp pool pubkey",
142115
)?;
143116

144-
let mut amm_inventories: Vec<(u16, i64, i64)> = vec![];
117+
let remaining_accounts = &mut ctx.remaining_accounts.iter().peekable();
118+
let constituent_map =
119+
ConstituentMap::load(&ConstituentSet::new(), &lp_pool_key, remaining_accounts)?;
120+
121+
let mut amm_inventories: Vec<(u16, i64, i64)> =
122+
Vec::with_capacity(amm_constituent_mapping.len() as usize);
145123
for (_, datum) in amm_constituent_mapping.iter().enumerate() {
146124
let cache_info = amm_cache.get(datum.perp_market_index as u32);
147125

@@ -183,11 +161,8 @@ pub fn handle_update_constituent_target_base<'c: 'info, 'info>(
183161
return Ok(());
184162
}
185163

186-
let remaining_accounts = &mut ctx.remaining_accounts.iter().peekable();
187-
let constituent_map =
188-
ConstituentMap::load(&ConstituentSet::new(), &lp_pool_key, remaining_accounts)?;
189-
190-
let mut constituent_indexes_and_decimals_and_prices: Vec<(u16, u8, i64)> = vec![];
164+
let mut constituent_indexes_and_decimals_and_prices: Vec<(u16, u8, i64)> =
165+
Vec::with_capacity(constituent_map.0.len());
191166
for (index, loader) in &constituent_map.0 {
192167
let constituent_ref = loader.load()?;
193168
constituent_indexes_and_decimals_and_prices.push((
@@ -248,25 +223,15 @@ pub fn handle_update_lp_pool_aum<'c: 'info, 'info>(
248223
"Constituent map length does not match lp pool constituent count"
249224
)?;
250225

251-
let constituent_target_base_key = &ctx.accounts.constituent_target_base.key();
252226
let mut constituent_target_base: AccountZeroCopyMut<
253227
'_,
254228
TargetsDatum,
255229
ConstituentTargetBaseFixed,
256230
> = ctx.accounts.constituent_target_base.load_zc_mut()?;
257-
let expected_pda = &Pubkey::create_program_address(
258-
&[
259-
CONSTITUENT_TARGET_BASE_PDA_SEED.as_ref(),
260-
lp_pool.pubkey.as_ref(),
261-
constituent_target_base.fixed.bump.to_le_bytes().as_ref(),
262-
],
263-
&crate::ID,
264-
)
265-
.map_err(|_| ErrorCode::InvalidPDA)?;
266231
validate!(
267-
expected_pda.eq(constituent_target_base_key),
232+
constituent_target_base.fixed.lp_pool.eq(&lp_pool.pubkey),
268233
ErrorCode::InvalidPDA,
269-
"Constituent target weights PDA does not match expected PDA"
234+
"Constituent target base lp pool pubkey does not match lp pool pubkey",
270235
)?;
271236

272237
let amm_cache_key: &Pubkey = &ctx.accounts.amm_cache.key();
@@ -417,8 +382,8 @@ pub fn handle_update_lp_pool_aum<'c: 'info, 'info>(
417382
if constituent.last_oracle_price
418383
< parent_constituent
419384
.last_oracle_price
420-
.safe_mul(9)?
421-
.safe_div(10)?
385+
.safe_mul(constituent.constituent_derivative_depeg_threshold as i64)?
386+
.safe_div(PERCENTAGE_PRECISION_I64)?
422387
{
423388
msg!(
424389
"Constituent {} last oracle price {} is too low compared to parent constituent {} last oracle price {}. Assuming depegging and setting target base to 0.",
@@ -504,40 +469,20 @@ pub fn handle_lp_pool_swap<'c: 'info, 'info>(
504469
let mut in_constituent = ctx.accounts.in_constituent.load_mut()?;
505470
let mut out_constituent = ctx.accounts.out_constituent.load_mut()?;
506471

507-
let constituent_target_base_key = &ctx.accounts.constituent_target_base.key();
508472
let constituent_target_base: AccountZeroCopy<'_, TargetsDatum, ConstituentTargetBaseFixed> =
509473
ctx.accounts.constituent_target_base.load_zc()?;
510-
let expected_pda = &Pubkey::create_program_address(
511-
&[
512-
CONSTITUENT_TARGET_BASE_PDA_SEED.as_ref(),
513-
lp_pool.pubkey.as_ref(),
514-
constituent_target_base.fixed.bump.to_le_bytes().as_ref(),
515-
],
516-
&crate::ID,
517-
)
518-
.map_err(|_| ErrorCode::InvalidPDA)?;
519474
validate!(
520-
expected_pda.eq(constituent_target_base_key),
475+
constituent_target_base.fixed.lp_pool.eq(&lp_pool.pubkey),
521476
ErrorCode::InvalidPDA,
522-
"Constituent target weights PDA does not match expected PDA"
477+
"Constituent target base lp pool pubkey does not match lp pool pubkey",
523478
)?;
524479

525-
let constituent_correlation_key = &ctx.accounts.constituent_correlations.key();
526480
let constituent_correlations: AccountZeroCopy<'_, i64, ConstituentCorrelationsFixed> =
527481
ctx.accounts.constituent_correlations.load_zc()?;
528-
let expected_correlation_pda = &Pubkey::create_program_address(
529-
&[
530-
CONSTITUENT_CORRELATIONS_PDA_SEED.as_ref(),
531-
lp_pool.pubkey.as_ref(),
532-
constituent_correlations.fixed.bump.to_le_bytes().as_ref(),
533-
],
534-
&crate::ID,
535-
)
536-
.map_err(|_| ErrorCode::InvalidPDA)?;
537482
validate!(
538-
expected_correlation_pda.eq(constituent_correlation_key),
483+
constituent_correlations.fixed.lp_pool.eq(&lp_pool.pubkey),
539484
ErrorCode::InvalidPDA,
540-
"Constituent correlations PDA does not match expected PDA"
485+
"Constituent correlations lp pool pubkey does not match lp pool pubkey",
541486
)?;
542487

543488
let AccountMaps {
@@ -665,7 +610,7 @@ pub fn handle_lp_pool_swap<'c: 'info, 'info>(
665610
let in_swap_id = get_then_update_id!(in_constituent, next_swap_id);
666611
let out_swap_id = get_then_update_id!(out_constituent, next_swap_id);
667612

668-
emit!(LPSwapRecord {
613+
emit_stack::<_, { LPSwapRecord::SIZE }>(LPSwapRecord {
669614
ts: now,
670615
slot,
671616
authority: ctx.accounts.authority.key(),
@@ -687,19 +632,19 @@ pub fn handle_lp_pool_swap<'c: 'info, 'info>(
687632
in_oracle.price,
688633
&in_spot_market,
689634
0,
690-
lp_pool.last_aum
635+
lp_pool.last_aum,
691636
)?,
692637
in_market_target_weight: in_target_weight,
693638
out_market_current_weight: out_constituent.get_weight(
694639
out_oracle.price,
695640
&out_spot_market,
696641
0,
697-
lp_pool.last_aum
642+
lp_pool.last_aum,
698643
)?,
699644
out_market_target_weight: out_target_weight,
700645
in_swap_id,
701646
out_swap_id,
702-
});
647+
})?;
703648

704649
receive(
705650
&ctx.accounts.token_program,
@@ -896,11 +841,11 @@ pub fn handle_lp_pool_add_liquidity<'c: 'info, 'info>(
896841
};
897842

898843
let mint_redeem_id = get_then_update_id!(lp_pool, next_mint_redeem_id);
899-
emit!(LPMintRedeemRecord {
844+
emit_stack::<_, { LPMintRedeemRecord::SIZE }>(LPMintRedeemRecord {
900845
ts: now,
901846
slot,
902847
authority: ctx.accounts.authority.key(),
903-
is_minting: true,
848+
description: 1,
904849
amount: in_amount,
905850
fee: in_fee_amount,
906851
spot_market_index: in_market_index,
@@ -918,10 +863,10 @@ pub fn handle_lp_pool_add_liquidity<'c: 'info, 'info>(
918863
in_oracle.price,
919864
&in_spot_market,
920865
0,
921-
lp_pool.last_aum
866+
lp_pool.last_aum,
922867
)?,
923868
in_market_target_weight: in_target_weight,
924-
});
869+
})?;
925870

926871
Ok(())
927872
}
@@ -1093,11 +1038,11 @@ pub fn handle_lp_pool_remove_liquidity<'c: 'info, 'info>(
10931038
};
10941039

10951040
let mint_redeem_id = get_then_update_id!(lp_pool, next_mint_redeem_id);
1096-
emit!(LPMintRedeemRecord {
1041+
emit_stack::<_, { LPMintRedeemRecord::SIZE }>(LPMintRedeemRecord {
10971042
ts: now,
10981043
slot,
10991044
authority: ctx.accounts.authority.key(),
1100-
is_minting: false,
1045+
description: 0,
11011046
amount: out_amount,
11021047
fee: out_fee_amount,
11031048
spot_market_index: out_market_index,
@@ -1115,10 +1060,10 @@ pub fn handle_lp_pool_remove_liquidity<'c: 'info, 'info>(
11151060
out_oracle.price,
11161061
&out_spot_market,
11171062
0,
1118-
lp_pool.last_aum
1063+
lp_pool.last_aum,
11191064
)?,
11201065
in_market_target_weight: out_target_weight,
1121-
});
1066+
})?;
11221067

11231068
Ok(())
11241069
}

programs/drift/src/instructions/optional_accounts.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
use crate::error::{DriftResult, ErrorCode};
2-
use crate::state::constituent_map::ConstituentSet;
32
use crate::state::high_leverage_mode_config::HighLeverageModeConfig;
43
use std::cell::RefMut;
54
use std::convert::TryFrom;

programs/drift/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1820,6 +1820,7 @@ pub mod drift {
18201820
oracle_staleness_threshold: u64,
18211821
cost_to_trade: i32,
18221822
constituent_derivative_index: Option<i16>,
1823+
constituent_derivative_depeg_threshold: u64,
18231824
derivative_weight: u64,
18241825
volatility: u64,
18251826
gamma_execution: u8,
@@ -1837,6 +1838,7 @@ pub mod drift {
18371838
oracle_staleness_threshold,
18381839
cost_to_trade,
18391840
constituent_derivative_index,
1841+
constituent_derivative_depeg_threshold,
18401842
derivative_weight,
18411843
volatility,
18421844
gamma_execution,

0 commit comments

Comments
 (0)