Skip to content

Commit b177280

Browse files
lowkeyniccjackwallergithub-actions[bot]wphanLukasDeco
authored
Nick/add scale orders ix (#2101)
* chore: update yellowstone to rust bindings version * sdk: release v2.153.0-beta.2 * Nick/external init account support (#2067) * wip: add external signer support for init account, stats account, swift account * updates * fix prettify * sdk: release v2.153.0-beta.3 * Revert "chore: update yellowstone to rust bindings version" * sdk: release v2.153.0-beta.4 * chore: update for channelOption changes * v2.154.0 * sdk: release v2.155.0-beta.0 * chore: add changelog * fix: lint * sdk: release v2.155.0-beta.1 * Revert "Jack/updated triton grpc" * sdk: release v2.155.0-beta.2 * refactor: replace pyth-solana-receiver with copied over code (#2068) * refactor: replace pyth-solana-receiver with copied over code * fix: use forked pyth IDL * fix: adjust wormhole IDL * fix: import pyth types locally pythPullClient * fix: prettier * fix: no pyth-solana-receiver in protocol * sdk: release v2.155.0-beta.3 * ui: reduce param checking for titan swaps (#2074) * ui: reduce param checking for titan swaps * cleanup titan usage and types * fix lint * prettify * sdk: release v2.155.0-beta.4 * lukas/isolated positions sdk (#1965) * program: make lp shares reduce only * init * rm more fields * make tests build * start sdk changes * init new margin calc * deposit and transfer into * add settle pnl * program: add withdraw * add more ix * add new meets withdraw req fn * enter/exit liquidation logic * moar * start liquidation logic * other liquidation fns * make build work * more updates * always calc isolated pos * rm isolated position market index logic * moar * program: rm the isolated position market index * some tweaks * rm some old margin code * tweak meets withdraw requirements * rm liquidation mode changing context * handle liquidation id and bit flags * more liquidation changes * clean * fix force cancel orders * update validate liquidation * moar * rename is_being_liquidated * start adding test * program: add validate for liq borrow for perp pnl * program: add test for isolated margin calc * is bankrupt test * fix cancel orders * fix set liquidation status * more tweaks * clean up naming * update last active slot for isolated position liq * another liquidation review * add test * cargo fmt -- * tweak naming * add test to make sure false liquidaiton wont be triggered * test meets withdraw * change is bankrupt * more * update uses of exit isolated liquidaiton * moar * moar * reduce diff * moar * modularize some for tests * add tests for the pnl for deposit liquidation * tests for isolated position transfer * test for update spot balance * test for settle pnl * add perp position max margin * program: test for custom perp position margin ratio * add test for margin calc for disable hlm * update test name * make max margin ratio persist * add liquidation mode test * more tests to make sure liqudiations dont bleed over * change test name * fix broken cargo tests * cargo fmt -- * first ts test * isolatedPositionLiquidatePerp test * isolatedPositionLiquidatePerpwithFill test * fix expired position * cargo fmt -- * feat: initial SDK Changes for iso pos * feat: margin calc unit tests * temp * feat: finally - parity with on-chain cargo test * fix: PR feedback and cleanup + decoding position flag wrong * feat: deposit into iso position ixs * temp: pr feedback nother round * feat: per perp pos max margin ratio * feat: additional ixs for transfer into iso + update perp margin ratio * feat: revamp liquidation checker functions for cross vs iso margin * fix: adjust health getter for user * fix: liq statuses add to return signature * chore: post rebase cleaner upper * fix: missing params from per market lev * feat: zero out account withdraw from perp position * fix: available positions logic update for iso * feat: iso position txs cleanup + ix ordering * feat: onchain props for signed msg orders + idl update * feat: cancels withdraw from iso pos * fix: only settle if needed iso withdraw + i64 min * feat: improvements to single grpc test * feat: buffer on margin deposits to avoid insuff collat err * feat: helpful scripts for testing/manipulating iso positions * chore: re organizing some user sdk funcs * fix: bug with max amount withdrawal for transfer iso perp * fix: post merge dupe field on swift * feat: min and max 64 constants * fix: bug with margin removal * fix: missing swift iso deposit from idl * fix: lint and prettify * feat: increased buffer on isolated deposit opening position * fix: missing check on order increasing size for depositing margin place + take * feat: settle pnl when trying to transfer to cross * fix: incorrect iso bankruptcy flag * feat: new margin calc logic * fix: broken test helpers * feat: buffer adjustments * fix: add missing swap ix update * fix: undefined this on isoalted free collateral * fix: prettier broke * fix: handle perp buying power on new iso position * fix: try/catch wrap on user isolated get free collat * feat: try settle flag for transfer to iso perp * fix: properly handle perp buying power existing iso position increase * feat: alpha npm version * fix: decoding isolated scaled balance incorrectly maybe * fix: build error rm lp field * feat: publish isPerpPositionIsolated as public method * sdk: add ix for token 2022 init account deposits (#2050) * add ix for token 2022 init account deposits * only call checkAccountExists if token2022 * update changelog * sdk: release v2.152.0-beta.3 * program: add bit_flags in preparation for iso pos (#2053) * program: add bit_flags in preparation for iso pos * CHANGELOG * program: base-spread-validate-buffer (#2052) * program: base-spread-validate-buffer * CHANGELOG --------- Co-authored-by: Chris Heaney <chrisheaney30@gmail.com> * v2.152.0 * ui: save titan tx when quoted and reuse on swap (#2055) * fix titan quoting for dsol * fix dsol instant unstake * feat: minified with esbuild (#2056) * feat: minified with esbuild * fix: rm webpack * fix: prettier titanClient * ui: fix falsely failing quotes from titan (#2058) * ui: fix falsely failing quotes from titan * prettify * check feed id after pyth pull atomic update * fix: many null checks fixed (#2059) * fix: many null checks fixed * fix: prettier * feat: get active markets helpers * fix: prettier * fix: README on margin calc was incorrect * fix: prettier and lint * fix: rm weird program diff * fix: rm weird program diff 2 * fix: rm weird empty file = * fix: rm useless diffs * refactor: remove unused fields a bunch on margin calc * fix: rebuild idl * fix: prevent unnecessary excpetion on liq price if free collat delta not computed * program: delete sereum/ob configs ix (#2066) * hot wallet update config stats * add delete for serum * delete ob config * CHANGELOG * sdk: release v2.153.0-beta.2 * Nick/external init account support (#2067) * wip: add external signer support for init account, stats account, swift account * updates * fix prettify * sdk: release v2.153.0-beta.3 * fix: user fastDecode check iso deposit and pos flag * fix: broken tests and PR cleanup * fix: final anchor tests fix? --------- Co-authored-by: Chris Heaney <chrisheaney30@gmail.com> Co-authored-by: lowkeynicc <85139158+lowkeynicc@users.noreply.github.com> Co-authored-by: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: bigz_Pubkey <83473873+0xbigz@users.noreply.github.com> Co-authored-by: wphan <6348407+wphan@users.noreply.github.com> Co-authored-by: chakos <chrishakos@lunoho.company> * sdk: release v2.155.0-beta.5 * migrate spot assets (#2057) * migrate spot assets * weth * weth again * prettify * sdk: release v2.155.0-beta.6 * program: more logging for amm trading (#2078) * more logging for amm trading * tweak logging * one more logging * CHANGELOG * crate msg * cargo fmt -- * program: allow delegate to transfer isolated pos deposit in sub account (#2079) * program: allow delegate to transfer isolated pos deposit in sub account * CHANGELOG * program: use load_maps in update_amms (#2081) * program: use load_maps in update_amms * fix build * CHANGELOG * v2.155.0 * sdk: release v2.156.0-beta.0 * fix: buggy getHealth for iso positions (#2083) * feat: pyth lazer subscriber with better resiliency (#2073) * feat: pyth lazer subscriber with better resiliency * fix: missing exports * feat: upgrade pyth lazer sdk * feat: bump sdk to node 24 * fix: node 24 in verify sdk ci pipeline * fix: anchor tests node 24 * sdk: release v2.156.0-beta.1 * fix: ci jobs missing node 24 (#2084) * fix: ci jobs missing node 24 * feat: jsdoc on pyth lazer sub to retrigger sdk release * sdk: release v2.156.0-beta.2 * fix: sdk version tag release error (#2085) * sdk: release v2.156.0-beta.3 * sdk: support jupiter api key (#2086) * sdk: release v2.156.0-beta.4 * add other funxyz address (#2089) * fix: use latest tag for our beta versions for now (#2090) * sdk: release v2.156.0-beta.5 * feat: more pyth type exports (#2091) * sdk: release v2.156.0-beta.6 * v2.156.0 * sdk: release v2.157.0-beta.0 * add scale orders ix * fix tests * allow up to 32 orders * flip start/end price logic * cleanup * add spot * refactor * address feedback --------- Co-authored-by: Jack Waller <jack.waller94@gmail.com> Co-authored-by: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: wphan <6348407+wphan@users.noreply.github.com> Co-authored-by: LukasDeco <ldeconantsesznak@gmail.com> Co-authored-by: chakos <chrishakos@lunoho.company> Co-authored-by: Chris Heaney <chrisheaney30@gmail.com> Co-authored-by: bigz_Pubkey <83473873+0xbigz@users.noreply.github.com> Co-authored-by: moosecat <14929853+moosecat2@users.noreply.github.com>
1 parent 4b48dee commit b177280

File tree

13 files changed

+2049
-11
lines changed

13 files changed

+2049
-11
lines changed

programs/drift/src/error.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -696,6 +696,10 @@ pub enum ErrorCode {
696696
MarketIndexNotFoundAmmCache,
697697
#[msg("Invalid Isolated Perp Market")]
698698
InvalidIsolatedPerpMarket,
699+
#[msg("Invalid scale order count - must be between 2 and 10")]
700+
InvalidOrderScaleOrderCount,
701+
#[msg("Invalid scale order price range")]
702+
InvalidOrderScalePriceRange,
699703
}
700704

701705
#[macro_export]

programs/drift/src/instructions/user.rs

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ use crate::state::order_params::{
8181
PlaceOrderOptions, PostOnlyParam,
8282
};
8383
use crate::state::paused_operations::{PerpOperation, SpotOperation};
84+
use crate::state::scale_order_params::ScaleOrderParams;
8485
use crate::state::perp_market::MarketStatus;
8586
use crate::state::perp_market_map::{get_writable_perp_market_set, MarketSet};
8687
use crate::state::protected_maker_mode_config::ProtectedMakerModeConfig;
@@ -2606,6 +2607,31 @@ pub fn handle_modify_order_by_user_order_id<'c: 'info, 'info>(
26062607
pub fn handle_place_orders<'c: 'info, 'info>(
26072608
ctx: Context<'_, '_, 'c, 'info, PlaceOrder>,
26082609
params: Vec<OrderParams>,
2610+
) -> Result<()> {
2611+
place_orders(&ctx, PlaceOrdersInput::Orders(params))
2612+
}
2613+
2614+
#[access_control(
2615+
exchange_not_paused(&ctx.accounts.state)
2616+
)]
2617+
pub fn handle_place_scale_orders<'c: 'info, 'info>(
2618+
ctx: Context<'_, '_, 'c, 'info, PlaceOrder>,
2619+
params: ScaleOrderParams,
2620+
) -> Result<()> {
2621+
place_orders(&ctx, PlaceOrdersInput::ScaleOrders(params))
2622+
}
2623+
2624+
/// Input for place_orders - either direct OrderParams or ScaleOrderParams to expand
2625+
enum PlaceOrdersInput {
2626+
Orders(Vec<OrderParams>),
2627+
ScaleOrders(ScaleOrderParams),
2628+
}
2629+
2630+
/// Internal implementation for placing multiple orders.
2631+
/// Used by both handle_place_orders and handle_place_scale_orders.
2632+
fn place_orders<'c: 'info, 'info>(
2633+
ctx: &Context<'_, '_, 'c, 'info, PlaceOrder>,
2634+
input: PlaceOrdersInput,
26092635
) -> Result<()> {
26102636
let clock = &Clock::get()?;
26112637
let state = &ctx.accounts.state;
@@ -2625,17 +2651,40 @@ pub fn handle_place_orders<'c: 'info, 'info>(
26252651

26262652
let high_leverage_mode_config = get_high_leverage_mode_config(&mut remaining_accounts)?;
26272653

2654+
// Convert input to order params, expanding scale orders if needed
2655+
let order_params = match input {
2656+
PlaceOrdersInput::Orders(params) => params,
2657+
PlaceOrdersInput::ScaleOrders(scale_params) => {
2658+
let order_step_size = match scale_params.market_type {
2659+
MarketType::Perp => {
2660+
let market = perp_market_map.get_ref(&scale_params.market_index)?;
2661+
market.amm.order_step_size
2662+
}
2663+
MarketType::Spot => {
2664+
let market = spot_market_map.get_ref(&scale_params.market_index)?;
2665+
market.order_step_size
2666+
}
2667+
};
2668+
2669+
scale_params.expand_to_order_params(order_step_size)
2670+
.map_err(|e| {
2671+
msg!("Failed to expand scale order params: {:?}", e);
2672+
ErrorCode::InvalidOrder
2673+
})?
2674+
}
2675+
};
2676+
26282677
validate!(
2629-
params.len() <= 32,
2678+
order_params.len() <= 32,
26302679
ErrorCode::DefaultError,
26312680
"max 32 order params"
26322681
)?;
26332682

26342683
let user_key = ctx.accounts.user.key();
26352684
let mut user = load_mut!(ctx.accounts.user)?;
26362685

2637-
let num_orders = params.len();
2638-
for (i, params) in params.iter().enumerate() {
2686+
let num_orders = order_params.len();
2687+
for (i, params) in order_params.iter().enumerate() {
26392688
validate!(
26402689
!params.is_immediate_or_cancel(),
26412690
ErrorCode::InvalidOrderIOC,
@@ -2654,7 +2703,7 @@ pub fn handle_place_orders<'c: 'info, 'info>(
26542703

26552704
if params.market_type == MarketType::Perp {
26562705
controller::orders::place_perp_order(
2657-
&ctx.accounts.state,
2706+
state,
26582707
&mut user,
26592708
user_key,
26602709
&perp_market_map,
@@ -2668,7 +2717,7 @@ pub fn handle_place_orders<'c: 'info, 'info>(
26682717
)?;
26692718
} else {
26702719
controller::orders::place_spot_order(
2671-
&ctx.accounts.state,
2720+
state,
26722721
&mut user,
26732722
user_key,
26742723
&perp_market_map,

programs/drift/src/lib.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use crate::controller::position::PositionDirection;
1313
use crate::state::if_rebalance_config::IfRebalanceConfigParams;
1414
use crate::state::oracle::PrelaunchOracleParams;
1515
use crate::state::order_params::{ModifyOrderParams, OrderParams};
16+
use crate::state::scale_order_params::ScaleOrderParams;
1617
use crate::state::perp_market::{ContractTier, MarketStatus};
1718
use crate::state::settle_pnl_mode::SettlePnlMode;
1819
use crate::state::spot_market::AssetTier;
@@ -367,6 +368,13 @@ pub mod drift {
367368
handle_place_orders(ctx, params)
368369
}
369370

371+
pub fn place_scale_orders<'c: 'info, 'info>(
372+
ctx: Context<'_, '_, 'c, 'info, PlaceOrder>,
373+
params: ScaleOrderParams,
374+
) -> Result<()> {
375+
handle_place_scale_orders(ctx, params)
376+
}
377+
370378
pub fn begin_swap<'c: 'info, 'info>(
371379
ctx: Context<'_, '_, 'c, 'info, Swap<'info>>,
372380
in_market_index: u16,

programs/drift/src/state/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ pub mod oracle;
1515
pub mod oracle_map;
1616
pub mod order_params;
1717
pub mod paused_operations;
18+
pub mod scale_order_params;
1819
pub mod perp_market;
1920
pub mod perp_market_map;
2021
pub mod protected_maker_mode_config;

programs/drift/src/state/order_params.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1027,3 +1027,4 @@ pub fn parse_optional_params(optional_params: Option<u32>) -> (u8, u8) {
10271027
None => (0, 100),
10281028
}
10291029
}
1030+

0 commit comments

Comments
 (0)