Skip to content

Commit

Permalink
program: rm unused fn (#665)
Browse files Browse the repository at this point in the history
* rm unused fn

* tweak

* move calculate_funding_rate

* do controller
  • Loading branch information
crispheaney authored Oct 25, 2023
1 parent 01959d9 commit 1bd0aed
Show file tree
Hide file tree
Showing 16 changed files with 65 additions and 680 deletions.
51 changes: 2 additions & 49 deletions programs/drift/src/controller/amm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::math::amm_spread::{calculate_spread_reserves, get_spread_reserves};
use crate::math::casting::Cast;
use crate::math::constants::{
CONCENTRATION_PRECISION, FEE_POOL_TO_REVENUE_POOL_THRESHOLD, K_BPS_UPDATE_SCALE,
MAX_CONCENTRATION_COEFFICIENT, MAX_K_BPS_INCREASE, MAX_SQRT_K, PRICE_TO_PEG_PRECISION_RATIO,
MAX_CONCENTRATION_COEFFICIENT, MAX_K_BPS_INCREASE, MAX_SQRT_K,
};
use crate::math::cp_curve::get_update_k_result;
use crate::math::repeg::get_total_fee_lower_bound;
Expand Down Expand Up @@ -152,35 +152,6 @@ pub fn calculate_base_swap_output_with_spread(
))
}

#[allow(dead_code)]
fn calculate_base_swap_output_without_spread(
amm: &mut AMM,
base_asset_swap_amount: u128,
direction: SwapDirection,
) -> DriftResult<(u128, u128, u128, u128)> {
let initial_quote_asset_reserve = amm.quote_asset_reserve;
let (new_quote_asset_reserve, new_base_asset_reserve) = amm::calculate_swap_output(
base_asset_swap_amount,
amm.base_asset_reserve,
direction,
amm.sqrt_k,
)?;

let quote_asset_amount = calculate_quote_asset_amount_swapped(
initial_quote_asset_reserve,
new_quote_asset_reserve,
direction,
amm.peg_multiplier,
)?;

Ok((
new_base_asset_reserve,
new_quote_asset_reserve,
quote_asset_amount,
0,
))
}

pub fn update_spread_reserves(amm: &mut AMM) -> DriftResult {
let (new_ask_base_asset_reserve, new_ask_quote_asset_reserve) =
calculate_spread_reserves(amm, PositionDirection::Long)?;
Expand Down Expand Up @@ -382,6 +353,7 @@ pub fn get_fee_pool_tokens(
)?
.cast()
}

fn calculate_revenue_pool_transfer(
market: &PerpMarket,
spot_market: &SpotMarket,
Expand Down Expand Up @@ -764,22 +736,3 @@ pub fn move_price(

Ok(())
}

#[allow(dead_code)]
pub fn move_to_price(amm: &mut AMM, target_price: u128) -> DriftResult {
let sqrt_k = bn::U256::from(amm.sqrt_k);
let k = sqrt_k.safe_mul(sqrt_k)?;

let new_base_asset_amount_squared = k
.safe_mul(bn::U256::from(amm.peg_multiplier))?
.safe_mul(bn::U256::from(PRICE_TO_PEG_PRECISION_RATIO))?
.safe_div(bn::U256::from(target_price))?;

let new_base_asset_amount = new_base_asset_amount_squared.integer_sqrt();
let new_quote_asset_amount = k.safe_div(new_base_asset_amount)?;

amm.base_asset_reserve = new_base_asset_amount.try_to_u128()?;
amm.quote_asset_reserve = new_quote_asset_amount.try_to_u128()?;

Ok(())
}
19 changes: 1 addition & 18 deletions programs/drift/src/controller/spot_balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::math::stats::{calculate_new_twap, calculate_weighted_average};

use crate::state::events::SpotInterestRecord;
use crate::state::oracle::OraclePriceData;
use crate::state::perp_market::{MarketStatus, PerpMarket};
use crate::state::perp_market::MarketStatus;
use crate::state::spot_market::{SpotBalance, SpotBalanceType, SpotMarket};
use crate::validate;

Expand Down Expand Up @@ -378,23 +378,6 @@ pub fn transfer_spot_balance_to_revenue_pool(
Ok(())
}

pub fn check_perp_market_valid(
perp_market: &PerpMarket,
spot_market: &SpotMarket,
spot_balance: &mut dyn SpotBalance,
current_slot: u64,
) -> DriftResult {
// todo

if perp_market.amm.oracle == spot_market.oracle
&& spot_balance.balance_type() == &SpotBalanceType::Borrow
&& (perp_market.amm.last_update_slot != current_slot || !perp_market.amm.last_oracle_valid)
{
return Err(ErrorCode::InvalidOracle);
}

Ok(())
}
pub fn update_spot_market_and_check_validity(
spot_market: &mut SpotMarket,
oracle_price_data: &OraclePriceData,
Expand Down
18 changes: 18 additions & 0 deletions programs/drift/src/controller/spot_balance/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,24 @@ use crate::state::user::{Order, PerpPosition, SpotPosition, User};
use crate::test_utils::*;
use crate::test_utils::{get_pyth_price, get_spot_positions};

pub fn check_perp_market_valid(
perp_market: &PerpMarket,
spot_market: &SpotMarket,
spot_balance: &mut dyn SpotBalance,
current_slot: u64,
) -> DriftResult {
// todo

if perp_market.amm.oracle == spot_market.oracle
&& spot_balance.balance_type() == &SpotBalanceType::Borrow
&& (perp_market.amm.last_update_slot != current_slot || !perp_market.amm.last_oracle_valid)
{
return Err(ErrorCode::InvalidOracle);
}

Ok(())
}

#[test]
fn test_daily_withdraw_limits() {
let now = 0_i64;
Expand Down
1 change: 1 addition & 0 deletions programs/drift/src/controller/spot_position.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ pub fn update_spot_balances_and_cumulative_deposits_with_limits(
Ok(())
}

#[cfg(test)]
pub fn transfer_spot_position_deposit(
token_amount: i128,
spot_market: &mut SpotMarket,
Expand Down
20 changes: 0 additions & 20 deletions programs/drift/src/math/amm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,26 +62,6 @@ pub fn calculate_bid_ask_bounds(
Ok((bid_bounded_base, ask_bounded_base))
}

pub fn calculate_terminal_price(amm: &mut AMM) -> DriftResult<u64> {
let swap_direction = if amm.base_asset_amount_with_amm > 0 {
SwapDirection::Add
} else {
SwapDirection::Remove
};
let (new_quote_asset_amount, new_base_asset_amount) = calculate_swap_output(
amm.base_asset_amount_with_amm.unsigned_abs(),
amm.base_asset_reserve,
swap_direction,
amm.sqrt_k,
)?;

calculate_price(
new_quote_asset_amount,
new_base_asset_amount,
amm.peg_multiplier,
)
}

pub fn calculate_market_open_bids_asks(amm: &AMM) -> DriftResult<(i128, i128)> {
let base_asset_reserve = amm.base_asset_reserve;
let min_base_asset_reserve = amm.min_base_asset_reserve;
Expand Down
18 changes: 0 additions & 18 deletions programs/drift/src/math/auction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,24 +194,6 @@ fn calculate_auction_price_for_oracle_offset_auction(
Ok(price)
}

pub fn does_auction_satisfy_maker_order(
maker_order: &Order,
taker_order: &Order,
auction_price: u64,
) -> bool {
// TODO more conditions to check?
if maker_order.direction == taker_order.direction
|| maker_order.market_index != taker_order.market_index
{
return false;
}

match maker_order.direction {
PositionDirection::Long => auction_price <= maker_order.price,
PositionDirection::Short => auction_price >= maker_order.price,
}
}

pub fn is_auction_complete(order_slot: u64, auction_duration: u8, slot: u64) -> DriftResult<bool> {
if auction_duration == 0 {
return Ok(true);
Expand Down
8 changes: 4 additions & 4 deletions programs/drift/src/math/cp_curve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::math::constants::{
AMM_RESERVE_PRECISION, AMM_TO_QUOTE_PRECISION_RATIO_I128, K_BPS_UPDATE_SCALE,
MAX_K_BPS_DECREASE, MAX_SQRT_K, PEG_PRECISION, PERCENTAGE_PRECISION_I128, QUOTE_PRECISION,
};
use crate::math::position::{_calculate_base_asset_value_and_pnl, calculate_base_asset_value};
use crate::math::position::{calculate_base_asset_value, calculate_base_asset_value_and_pnl};
use crate::math::safe_math::SafeMath;

use crate::state::perp_market::{MarketStatus, PerpMarket};
Expand Down Expand Up @@ -175,7 +175,7 @@ pub fn adjust_k_cost(
let mut market_clone = *market;

// Find the net market value before adjusting k
let (current_net_market_value, _) = _calculate_base_asset_value_and_pnl(
let (current_net_market_value, _) = calculate_base_asset_value_and_pnl(
market_clone.amm.base_asset_amount_with_amm,
0,
&market_clone.amm,
Expand All @@ -184,7 +184,7 @@ pub fn adjust_k_cost(

update_k(&mut market_clone, update_k_result)?;

let (_new_net_market_value, cost) = _calculate_base_asset_value_and_pnl(
let (_new_net_market_value, cost) = calculate_base_asset_value_and_pnl(
market_clone.amm.base_asset_amount_with_amm,
current_net_market_value,
&market_clone.amm,
Expand All @@ -207,7 +207,7 @@ pub fn adjust_k_cost_and_update(

update_k(market, update_k_result)?;

let (_new_net_market_value, cost) = _calculate_base_asset_value_and_pnl(
let (_new_net_market_value, cost) = calculate_base_asset_value_and_pnl(
market.amm.base_asset_amount_with_amm,
current_net_market_value,
&market.amm,
Expand Down
29 changes: 2 additions & 27 deletions programs/drift/src/math/funding.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::cmp::{max, min};
use std::cmp::max;

use solana_program::msg;

Expand All @@ -7,7 +7,7 @@ use crate::math::bn;
use crate::math::casting::Cast;
use crate::math::constants::{
AMM_TO_QUOTE_PRECISION_RATIO, AMM_TO_QUOTE_PRECISION_RATIO_I128, FUNDING_RATE_BUFFER,
ONE_HOUR_I128, PRICE_PRECISION, QUOTE_TO_BASE_AMT_FUNDING_PRECISION,
PRICE_PRECISION, QUOTE_TO_BASE_AMT_FUNDING_PRECISION,
};
use crate::math::repeg::{calculate_fee_pool, get_total_fee_lower_bound};
use crate::math::safe_math::SafeMath;
Expand All @@ -18,31 +18,6 @@ use crate::state::user::PerpPosition;
#[cfg(test)]
mod tests;

pub fn calculate_funding_rate(
mid_price_twap: u128,
oracle_price_twap: i128,
funding_period: i64,
) -> DriftResult<i128> {
// funding period = 1 hour, window = 1 day
// low periodicity => quickly updating/settled funding rates
// => lower funding rate payment per interval
let period_adjustment = (24_i128)
.safe_mul(ONE_HOUR_I128)?
.safe_div(max(ONE_HOUR_I128, funding_period as i128))?;

let price_spread = mid_price_twap.cast::<i128>()?.safe_sub(oracle_price_twap)?;

// clamp price divergence to 3% for funding rate calculation
let max_price_spread = oracle_price_twap.safe_div(33)?; // 3%
let clamped_price_spread = max(-max_price_spread, min(price_spread, max_price_spread));

let funding_rate = clamped_price_spread
.safe_mul(FUNDING_RATE_BUFFER.cast()?)?
.safe_div(period_adjustment.cast()?)?;

Ok(funding_rate)
}

/// With a virtual AMM, there can be an imbalance between longs and shorts and thus funding can be asymmetric.
/// To account for this, amm keeps track of the cumulative funding rate for both longs and shorts.
/// When there is a period with asymmetric funding, the protocol will pay/receive funding from/to it's collected fees.
Expand Down
28 changes: 27 additions & 1 deletion programs/drift/src/math/funding/tests.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
use crate::math::constants::{
AMM_RESERVE_PRECISION, PRICE_PRECISION, PRICE_PRECISION_U64, QUOTE_PRECISION,
AMM_RESERVE_PRECISION, ONE_HOUR_I128, PRICE_PRECISION, PRICE_PRECISION_U64, QUOTE_PRECISION,
};
use crate::math::funding::*;
use crate::state::oracle::HistoricalOracleData;
use crate::state::perp_market::{PerpMarket, AMM};
use std::cmp::min;

fn calculate_funding_rate(
mid_price_twap: u128,
oracle_price_twap: i128,
funding_period: i64,
) -> DriftResult<i128> {
// funding period = 1 hour, window = 1 day
// low periodicity => quickly updating/settled funding rates
// => lower funding rate payment per interval
let period_adjustment = (24_i128)
.safe_mul(ONE_HOUR_I128)?
.safe_div(max(ONE_HOUR_I128, funding_period as i128))?;

let price_spread = mid_price_twap.cast::<i128>()?.safe_sub(oracle_price_twap)?;

// clamp price divergence to 3% for funding rate calculation
let max_price_spread = oracle_price_twap.safe_div(33)?; // 3%
let clamped_price_spread = max(-max_price_spread, min(price_spread, max_price_spread));

let funding_rate = clamped_price_spread
.safe_mul(FUNDING_RATE_BUFFER.cast()?)?
.safe_div(period_adjustment.cast()?)?;

Ok(funding_rate)
}

#[test]
fn balanced_funding_test() {
Expand Down
1 change: 1 addition & 0 deletions programs/drift/src/math/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ pub fn on_the_hour_update(now: i64, last_update_ts: i64, update_period: i64) ->
Ok(time_remaining_until_update)
}

#[cfg(test)]
#[allow(clippy::comparison_chain)]
pub fn log10(n: u128) -> u128 {
if n < 10 {
Expand Down
8 changes: 0 additions & 8 deletions programs/drift/src/math/liquidation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,14 +208,6 @@ pub fn is_user_being_liquidated(
Ok(is_being_liquidated)
}

pub fn get_margin_requirement_plus_buffer(
margin_requirement: u128,
liquidation_margin_buffer_ratio: u8,
) -> DriftResult<u128> {
margin_requirement
.safe_add(margin_requirement.safe_div(liquidation_margin_buffer_ratio as u128)?)
}

pub fn validate_user_not_being_liquidated(
user: &mut User,
market_map: &PerpMarketMap,
Expand Down
12 changes: 2 additions & 10 deletions programs/drift/src/math/margin/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ mod test {
QUOTE_PRECISION_I64, SPOT_IMF_PRECISION,
};
use crate::math::margin::{calculate_perp_position_value_and_pnl, MarginRequirementType};
use crate::math::position::{
calculate_base_asset_value_and_pnl_with_oracle_price, calculate_position_pnl,
};
use crate::math::position::calculate_base_asset_value_and_pnl_with_oracle_price;
use crate::state::oracle::{OraclePriceData, StrictOraclePrice};
use crate::state::perp_market::{ContractTier, PerpMarket, AMM};
use crate::state::spot_market::{AssetTier, SpotMarket};
Expand Down Expand Up @@ -226,16 +224,11 @@ mod test {

let margin_requirement_type = MarginRequirementType::Initial;

let position_unrealized_pnl =
calculate_position_pnl(&market_position, &market.amm, false).unwrap();

assert_eq!(position_unrealized_pnl, 22699050905);

// sqrt of oracle price = 149
market.unrealized_pnl_imf_factor = market.imf_factor;

let uaw = market
.get_unrealized_asset_weight(position_unrealized_pnl, MarginRequirementType::Initial)
.get_unrealized_asset_weight(22699050905, MarginRequirementType::Initial)
.unwrap();
assert_eq!(uaw, 9559);

Expand All @@ -251,7 +244,6 @@ mod test {
.unwrap();

assert_eq!(upnl, 100000000);
assert!(upnl < position_unrealized_pnl); // margin system discounts

assert!(pmr > 0);
assert_eq!(pmr, 13555327867);
Expand Down
Loading

0 comments on commit 1bd0aed

Please sign in to comment.