Skip to content

Commit

Permalink
Bigz/perp lp jit (#448)
Browse files Browse the repository at this point in the history
* bigz/perp-lp-jit

* sdk: add updatePerpMarketTargetBaseAssetAmountPerLP

* init tests (wip)

* todo: start split_with_lps tests

* fix test

* controller/orders.rs: split out to calculate_amm_jit_liquidity

* split out with split_with_lps param in calculate_jit_amount

* fix idl

* update idl

* fix greater/less than on target lp amount

* wip test

* working basic tests

* wip, working typescript tests and functions

* fix tests/perpLpJit.ts

* fix test

* add LP split OrderActionExplanation, linter

* fix prettier

* address feedback p1

* add amm_lp_wants_to_jit_make functions

* cleanup logs, add intuition comment

* improve amm_lp_allowed_to_jit_make compute

* cargo fmt --

* revert split_with_lps fee_to_market

* use AMMLiquiditySplit

* use protocol_owned_min_side_liquidity for amm_lp_allowed_to_jit_make

* wip lp-owned fill

* cargo fmt --, fix test

* data check inside update_lp_market_position

* update_lp_market_position: comb early return

* incorp most of feedback-p2

* working LPOwned fills

* fix comment

* add some perp_market precisions

* tests/perpLpJit.ts: add asserts

* tests/perpLpJit.ts: add btc test

* wip more asserts for tests/perpLpJit.ts

* tests/perpLpJit.ts: expanded

* tests: remove assert from spotSwap test causing race conditions

* sdk: update spl-token dependency to 0.3.7 (#465)

* sdk: start spl-token dependency upgrade

* update tests to use spl-token 0.3.7

* fix driftClient test

* fix whitelist test

* fix unused import

* sdk: tweaks to make driftClient.swap work

* sdk: add ability to pass in route to driftClient.swap

* sdk: supporting changes for jupiterClient (#466)

* sdk: add IVersionedWallet, rename jupiter args, make loadKeypair support more private key types

* dlob: add estimateFillWithExactBaseAmount

* jupiter client decompile message fix

* fix docstring

* estimateFillWithExactBaseAmount to return QUOTE_PRECISION

* program: add swap reduce only (#468)

* init msol config (#467)

* init msol config

* rm devnet, decimals=9

* update changelog.md

* sdk: spotBalance.ts docs

* sdk: make ts BN for swaprecords

* v2.30.0

* update changelog

---------

Co-authored-by: Chris Heaney <[email protected]>
Co-authored-by: wphan <[email protected]>
Co-authored-by: lowkeynicc <[email protected]>
  • Loading branch information
4 people committed May 19, 2023
1 parent e811ccd commit 72efda4
Show file tree
Hide file tree
Showing 18 changed files with 5,164 additions and 103 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]

### Features
- program: add user perp lp jit liquidity toward a target base (([#448](https://github.com/drift-labs/protocol-v2/pull/448)))

### Fixes

Expand Down
99 changes: 49 additions & 50 deletions programs/drift/src/controller/orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use crate::error::DriftResult;
use crate::error::ErrorCode;
use crate::instructions::OrderParams;
use crate::load_mut;
use crate::math::amm_jit::calculate_amm_jit_liquidity;
use crate::math::auction::calculate_auction_prices;
use crate::math::casting::Cast;
use crate::math::constants::{
Expand Down Expand Up @@ -57,7 +58,7 @@ use crate::state::events::{OrderAction, OrderActionExplanation};
use crate::state::fulfillment::{PerpFulfillmentMethod, SpotFulfillmentMethod};
use crate::state::oracle::OraclePriceData;
use crate::state::oracle_map::OracleMap;
use crate::state::perp_market::{MarketStatus, PerpMarket};
use crate::state::perp_market::{AMMLiquiditySplit, MarketStatus, PerpMarket};
use crate::state::perp_market_map::PerpMarketMap;
use crate::state::spot_fulfillment_params::{ExternalSpotFill, SpotFulfillmentParams};
use crate::state::spot_market::{SpotBalanceType, SpotMarket};
Expand All @@ -79,6 +80,8 @@ mod tests;

#[cfg(test)]
mod amm_jit_tests;
#[cfg(test)]
mod amm_lp_jit_tests;

pub fn place_perp_order(
state: &State,
Expand Down Expand Up @@ -1505,7 +1508,7 @@ fn fulfill_perp_order(
fee_structure,
None,
*maker_price,
true,
AMMLiquiditySplit::Shared,
)?;

(fill_base_asset_amount, fill_quote_asset_amount)
Expand Down Expand Up @@ -1703,7 +1706,7 @@ pub fn fulfill_perp_order_with_amm(
fee_structure: &FeeStructure,
override_base_asset_amount: Option<u64>,
override_fill_price: Option<u64>,
split_with_lps: bool,
liquidity_split: AMMLiquiditySplit,
) -> DriftResult<(u64, u64)> {
let position_index = get_position_index(&user.perp_positions, market.market_index)?;

Expand Down Expand Up @@ -1819,8 +1822,13 @@ pub fn fulfill_perp_order_with_amm(
let user_position_delta =
get_position_delta_for_fill(base_asset_amount, quote_asset_amount, order_direction)?;

if split_with_lps {
update_lp_market_position(market, &user_position_delta, fee_to_market_for_lp.cast()?)?;
if liquidity_split != AMMLiquiditySplit::ProtocolOwned {
update_lp_market_position(
market,
&user_position_delta,
fee_to_market_for_lp.cast()?,
liquidity_split,
)?;
}

if market.amm.user_lp_shares > 0 {
Expand Down Expand Up @@ -1915,12 +1923,10 @@ pub fn fulfill_perp_order_with_amm(
get_taker_and_maker_for_order_record(user_key, &user.orders[order_index]);

let fill_record_id = get_then_update_id!(market, next_fill_record_id);
let order_action_explanation =
if override_base_asset_amount.is_some() && override_fill_price.is_some() {
OrderActionExplanation::OrderFilledWithAMMJit
} else {
OrderActionExplanation::OrderFilledWithAMM
};
let order_action_explanation = match (override_base_asset_amount, override_fill_price) {
(Some(_), Some(_)) => liquidity_split.get_order_action_explanation(),
_ => OrderActionExplanation::OrderFilledWithAMM,
};
let order_action_record = get_order_action_record(
now,
OrderAction::Fill,
Expand Down Expand Up @@ -2053,51 +2059,44 @@ pub fn fulfill_perp_order_with_match(
sanitize_clamp_denominator,
)?;

let amm_wants_to_make = match taker_direction {
PositionDirection::Long => market.amm.base_asset_amount_with_amm < 0,
PositionDirection::Short => market.amm.base_asset_amount_with_amm > 0,
} && market.amm.amm_jit_is_active();
let mut total_quote_asset_amount = 0_u64;

// taker has_limit_price = false means (limit price = 0 AND auction is complete) so
// market order will always land and fill on amm next round
let amm_will_fill_next_round = !taker.orders[taker_order_index].has_limit_price(slot)?
&& maker_base_asset_amount < taker_base_asset_amount;
let (jit_base_asset_amount, amm_liquidity_split) = calculate_amm_jit_liquidity(
market,
taker_direction,
maker_price,
valid_oracle_price,
base_asset_amount,
taker_base_asset_amount,
maker_base_asset_amount,
taker.orders[taker_order_index].has_limit_price(slot)?,
)?;

let mut total_quote_asset_amount = 0_u64;
if amm_wants_to_make && !amm_will_fill_next_round {
let jit_base_asset_amount = crate::math::amm_jit::calculate_jit_base_asset_amount(
if jit_base_asset_amount > 0 {
let (_, quote_asset_amount_filled_by_amm) = fulfill_perp_order_with_amm(
taker,
taker_stats,
taker_order_index,
market,
base_asset_amount,
maker_price,
oracle_map,
reserve_price_before,
now,
slot,
valid_oracle_price,
taker_direction,
taker_key,
filler_key,
filler,
filler_stats,
&mut None,
&mut None,
fee_structure,
Some(jit_base_asset_amount),
Some(maker_price), // match the makers price
amm_liquidity_split,
)?;

if jit_base_asset_amount > 0 {
let (_, quote_asset_amount_filled_by_amm) = fulfill_perp_order_with_amm(
taker,
taker_stats,
taker_order_index,
market,
oracle_map,
reserve_price_before,
now,
slot,
valid_oracle_price,
taker_key,
filler_key,
filler,
filler_stats,
&mut None,
&mut None,
fee_structure,
Some(jit_base_asset_amount),
Some(maker_price), // match the makers price
false, // dont split with the lps
)?;
total_quote_asset_amount = quote_asset_amount_filled_by_amm;
};
};
total_quote_asset_amount = quote_asset_amount_filled_by_amm
}

let taker_existing_position = taker
.get_perp_position(market.market_index)?
Expand Down
Loading

0 comments on commit 72efda4

Please sign in to comment.