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

Bigz/amm repegged min max bar fix #282

Merged
merged 7 commits into from
Dec 7, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
28 changes: 20 additions & 8 deletions programs/drift/src/controller/repeg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use crate::math::casting::Cast;
use crate::math::constants::{K_BPS_UPDATE_SCALE, QUOTE_PRECISION, QUOTE_SPOT_MARKET_INDEX};
use crate::math::cp_curve;
use crate::math::cp_curve::get_update_k_result;
use crate::math::cp_curve::UpdateKResult;
use crate::math::oracle;
use crate::math::oracle::{is_oracle_valid_for_action, oracle_validity, DriftAction};
use crate::math::repeg;
Expand Down Expand Up @@ -154,6 +155,7 @@ pub fn _update_amm(
)?;

let mut amm_update_cost = 0;
let mut amm_not_successfully_updated = false;
if is_oracle_valid_for_action(oracle_validity, Some(DriftAction::UpdateAMMCurve))? {
let curve_update_intensity =
min(market.amm.curve_update_intensity, 100_u8).cast::<i128>()?;
Expand All @@ -166,16 +168,24 @@ pub fn _update_amm(
repeg::adjust_amm(market, optimal_peg, fee_budget, true)?;

let cost_applied = apply_cost_to_market(market, repegged_cost, check_lower_bound)?;

if cost_applied {
market.amm.base_asset_reserve = repegged_market.amm.base_asset_reserve;
market.amm.quote_asset_reserve = repegged_market.amm.quote_asset_reserve;
market.amm.sqrt_k = repegged_market.amm.sqrt_k;

market.amm.terminal_quote_asset_reserve =
repegged_market.amm.terminal_quote_asset_reserve;
cp_curve::update_k(
market,
&UpdateKResult {
sqrt_k: repegged_market.amm.sqrt_k,
base_asset_reserve: repegged_market.amm.base_asset_reserve,
quote_asset_reserve: repegged_market.amm.quote_asset_reserve,
},
)?;
// market.amm.base_asset_reserve = repegged_market.amm.base_asset_reserve;
// market.amm.quote_asset_reserve = repegged_market.amm.quote_asset_reserve;
// market.amm.sqrt_k = repegged_market.amm.sqrt_k;
// market.amm.terminal_quote_asset_reserve =
// repegged_market.amm.terminal_quote_asset_reserve;
market.amm.peg_multiplier = repegged_market.amm.peg_multiplier;
amm_update_cost = repegged_cost;
} else {
amm_not_successfully_updated = true;
}
}
}
Expand All @@ -195,7 +205,9 @@ pub fn _update_amm(
}

if is_oracle_valid_for_action(oracle_validity, Some(DriftAction::FillOrderAmm))? {
market.amm.last_update_slot = clock_slot;
if !amm_not_successfully_updated {
market.amm.last_update_slot = clock_slot;
}
market.amm.last_oracle_valid = true;
} else {
market.amm.last_oracle_valid = false;
Expand Down
92 changes: 68 additions & 24 deletions programs/drift/src/controller/repeg/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ pub fn update_amm_test() {
base_spread: 250,
curve_update_intensity: 100,
max_spread: 55500,
concentration_coef: 1020710,

..AMM::default()
},
status: MarketStatus::Initialized,
Expand Down Expand Up @@ -93,7 +95,7 @@ pub fn update_amm_test() {
== OracleValidity::Valid;

let reserve_price_after_prepeg = market.amm.reserve_price().unwrap();
assert_eq!(reserve_price_after_prepeg, 12744099999);
assert_eq!(reserve_price_after_prepeg, 12743902020);
assert_eq!(
market.amm.historical_oracle_data.last_oracle_price,
12400000000
Expand All @@ -116,7 +118,7 @@ pub fn update_amm_test() {
Some(reserve_price_after_prepeg),
)
.unwrap();
assert_eq!(oracle_reserve_price_spread_pct_before, -330349);
assert_eq!(oracle_reserve_price_spread_pct_before, -330370);
let too_diverge = amm::is_oracle_mark_too_divergent(
oracle_reserve_price_spread_pct_before,
&state.oracle_guard_rails.price_divergence,
Expand All @@ -129,8 +131,8 @@ pub fn update_amm_test() {
assert_eq!(-cost_of_update, profit);
assert!(is_oracle_valid);
assert!(profit < 0);
assert_eq!(profit, -6158311901);
assert_eq!(peg, 13_145_464_477);
assert_eq!(peg, 13145260263);
assert_eq!(profit, -6158609290);

let reserve_price = market.amm.reserve_price().unwrap();
let (bid, ask) = market.amm.bid_ask_price(reserve_price).unwrap();
Expand All @@ -142,12 +144,12 @@ pub fn update_amm_test() {
(market.margin_ratio_initial * 100) as u32
);

assert_eq!(bid, 12039058154);
assert_eq!(bid, 12038871128);
assert!(bid < (oracle_price_data.price as u64));
assert_eq!(reserve_price, 12744099999);
assert_eq!(ask, 12746355704);
assert_eq!(reserve_price, 12743902020);
assert_eq!(ask, 12746157690);
assert!(ask >= (oracle_price_data.price as u64));
//(12746355704-12039058154)/12746355704 == .05547 (max spread=.0555)
assert!((ask - bid) * 1000000 / reserve_price < market.amm.max_spread as u64);
}

#[test]
Expand All @@ -162,6 +164,7 @@ pub fn update_amm_test_bad_oracle() {
base_asset_amount_with_amm: -(AMM_RESERVE_PRECISION as i128),
mark_std: PRICE_PRECISION as u64,
last_mark_price_twap_ts: 0,
concentration_coef: 1020710,
historical_oracle_data: HistoricalOracleData {
last_oracle_price_twap: 19_400 * PRICE_PRECISION_I64,
..HistoricalOracleData::default()
Expand Down Expand Up @@ -348,6 +351,7 @@ pub fn update_amm_larg_conf_w_neg_tfmd_test() {
let slot = 81680085;

let mut market = PerpMarket::default_btc_test();
market.amm.concentration_coef = 1414213;
market.amm.total_fee_minus_distributions = -(10000 * QUOTE_PRECISION as i128);
assert_eq!(market.amm.base_asset_amount_with_amm, -1000000000);

Expand Down Expand Up @@ -378,11 +382,32 @@ pub fn update_amm_larg_conf_w_neg_tfmd_test() {
};
assert_eq!(market.amm.long_spread, 0);
assert_eq!(market.amm.short_spread, 0);
assert_eq!(market.amm.last_update_slot, 0);
assert_eq!(market.amm.sqrt_k, 64000000000);
let prev_peg_multiplier = market.amm.peg_multiplier;
let prev_total_fee_minus_distributions = market.amm.total_fee_minus_distributions;

let cost_of_update = _update_amm(&mut market, &oracle_price_data, &state, now, slot).unwrap();
assert_eq!(cost_of_update, -42992787); // amm wins when price increases
assert_eq!(market.amm.long_spread, 390);
assert_eq!(market.amm.short_spread, 975 - 390);
assert_eq!(market.amm.sqrt_k, 64000000000);
assert_eq!(market.amm.base_asset_reserve, 65000000000);
assert_eq!(market.amm.quote_asset_reserve, 63015384615);
assert_eq!(market.amm.terminal_quote_asset_reserve, 64000000000);
assert_eq!(market.amm.min_base_asset_reserve, 45254851991);
assert_eq!(market.amm.max_base_asset_reserve, 90509632000);
assert_eq!(market.amm.peg_multiplier, 19443664550);
assert_eq!(market.amm.peg_multiplier > prev_peg_multiplier, true);
assert_eq!(market.amm.total_fee_minus_distributions, -9957007213);
assert_eq!(
market.amm.total_fee_minus_distributions > prev_total_fee_minus_distributions,
true
);

assert_eq!(market.amm.last_oracle_valid, true);
assert_eq!(market.amm.last_update_slot, slot);

assert_eq!(market.amm.long_spread, 389);
assert_eq!(market.amm.short_spread, 975 - 389);

let reserve_price_after = market.amm.reserve_price().unwrap();
assert_eq!(reserve_price_after, 18849999999);
Expand All @@ -402,14 +427,15 @@ pub fn update_amm_larg_conf_w_neg_tfmd_test() {
let mrk = market.amm.reserve_price().unwrap();
let (bid, ask) = market.amm.bid_ask_price(mrk).unwrap();

assert_eq!(bid, 18838972749);
assert_eq!(bid, 18838953899);
assert_eq!(mrk, 18849999999);
assert_eq!(ask, 18857351498);
assert_eq!(ask, 18857332648);

assert_eq!(market.amm.long_spread, 390);
assert_eq!(market.amm.short_spread, 585);
assert_eq!(market.amm.long_spread, 389);
assert_eq!(market.amm.short_spread, 586);

// add move lower
msg!("SHOULD LOWER K");
let oracle_price_data = OraclePriceData {
price: (18_820 * PRICE_PRECISION) as i64,
confidence: 100 * PRICE_PRECISION_U64,
Expand All @@ -433,20 +459,38 @@ pub fn update_amm_larg_conf_w_neg_tfmd_test() {
let optimal_peg_cost = calculate_repeg_cost(&market.amm, optimal_peg).unwrap();
assert_eq!(optimal_peg_cost, 30468749);

let prev_peg_multiplier = market.amm.peg_multiplier;
let prev_total_fee_minus_distributions = market.amm.total_fee_minus_distributions;
let cost_of_update = _update_amm(&mut market, &oracle_price_data, &state, now, slot).unwrap();
assert_eq!(cost_of_update, 21160200);
assert_eq!(market.amm.peg_multiplier, 19422173721);
assert_eq!(cost_of_update, 21459607); // amm loses when price decreases (given users are net short)
assert_eq!(market.amm.sqrt_k, 63936000000); // k lowered since cost_of_update is positive and total_fee_minus_distributions negative
assert_eq!(market.amm.base_asset_reserve, 64935000000);
assert_eq!(market.amm.quote_asset_reserve, 62952369231);
assert_eq!(market.amm.terminal_quote_asset_reserve, 63937000015);
assert_eq!(market.amm.min_base_asset_reserve, 45208890032);
assert_eq!(market.amm.max_base_asset_reserve, 90417708155);
assert_eq!(market.amm.peg_multiplier, 19421869977);
assert_eq!(market.amm.peg_multiplier < prev_peg_multiplier, true);
// assert_eq!(market.amm.total_fee_minus_distributions, -9978167413);
assert_eq!(
market.amm.total_fee_minus_distributions < prev_total_fee_minus_distributions,
true
);

assert_eq!(market.amm.last_oracle_valid, true);
assert_eq!(market.amm.last_update_slot, slot);

assert_eq!(market.amm.long_spread, 369);
assert_eq!(market.amm.short_spread, 975 - 369);

let mrk = market.amm.reserve_price().unwrap();
let (bid, ask) = market.amm.bid_ask_price(mrk).unwrap();

let orc = oracle_price_data.price as u64;
assert_eq!(bid, 18817754864);
assert_eq!(bid, 18817460574);
assert_eq!(orc, 18820000000);
assert_eq!(mrk, 18829165339);
assert_eq!(ask, 18836113301);
assert_eq!(mrk, 18828870870);
assert_eq!(ask, 18835818723);

assert_eq!(bid <= orc, true);

Expand All @@ -460,15 +504,15 @@ pub fn update_amm_larg_conf_w_neg_tfmd_test() {

let cost_of_update = _update_amm(&mut market, &oracle_price_data, &state, now, slot).unwrap();
assert_eq!(cost_of_update, 0);
assert_eq!(market.amm.long_spread, 378);
assert_eq!(market.amm.short_spread, 975 - 378);
assert_eq!(market.amm.long_spread, 377);
assert_eq!(market.amm.short_spread, 975 - 377);

let mrk = market.amm.reserve_price().unwrap();
let (bid, ask) = market.amm.bid_ask_price(mrk).unwrap();

assert_eq!(bid, 18817924327);
assert_eq!(mrk, 18829165339);
assert_eq!(ask, 18836282763);
assert_eq!(bid, 18817611205);
assert_eq!(mrk, 18828870870);
assert_eq!(ask, 18835969354);
assert_eq!((oracle_price_data.price as u64) > bid, true);
assert_eq!((oracle_price_data.price as u64) < ask, true);
}
28 changes: 21 additions & 7 deletions programs/drift/src/math/repeg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,17 +252,25 @@ pub fn calculate_per_peg_cost(
terminal_quote_asset_reserve: u128,
) -> DriftResult<i128> {
// returns a signed per_peg_cost relative to delta peg
// signed means that "cost" to amm is influenced whether delta_peg is the same sign

let per_peg_cost = if quote_asset_reserve != terminal_quote_asset_reserve {
quote_asset_reserve
.cast::<i128>()?
.safe_sub(terminal_quote_asset_reserve.cast::<i128>()?)?
.safe_div(AMM_RESERVE_PRECISION_I128 / PEG_PRECISION_I128)?
.safe_add(1)?
.safe_div_ceil(AMM_RESERVE_PRECISION_I128 / PEG_PRECISION_I128)?
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@crispheaney this will make negative number "larger negative" than otherwise?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it rounds to positive infinity

} else {
0
};

Ok(per_peg_cost)
// round to make magnitude higher
Ok(if per_peg_cost > 0 {
per_peg_cost.safe_add(1)?
} else if per_peg_cost < 0 {
per_peg_cost.safe_sub(1)?
} else {
per_peg_cost
})
}

pub fn adjust_amm(
Expand Down Expand Up @@ -302,9 +310,12 @@ pub fn adjust_amm(
budget_delta_peg_magnitude = budget_delta_peg.unsigned_abs();
}

if (per_peg_cost == 0 || per_peg_cost > 0 && delta_peg < 0 || per_peg_cost < 0 && delta_peg > 0)
|| (budget_delta_peg_magnitude > delta_peg.unsigned_abs())
{
let use_optimal_peg = (per_peg_cost == 0 // if per peg cost is 0 => free
|| per_peg_cost > 0 && delta_peg < 0 // or if per peg positive and the direction is down => revenue
|| per_peg_cost < 0 && delta_peg > 0) // or if per peg negative and the direction is up => revenue
|| (budget_delta_peg_magnitude > delta_peg.unsigned_abs()); // the peg movement from full budget usage exceeds delta to optimal

if use_optimal_peg {
// use optimal peg
new_peg = optimal_peg;
cost = calculate_repeg_cost(&market_clone.amm, new_peg)?;
Expand Down Expand Up @@ -342,6 +353,7 @@ pub fn adjust_amm(
market_clone.amm.quote_asset_reserve,
market_clone.amm.terminal_quote_asset_reserve,
)?;

adjustment_cost
} else {
0
Expand Down Expand Up @@ -370,7 +382,6 @@ pub fn adjust_amm(

cost = calculate_repeg_cost(&market_clone.amm, new_peg)?;
}

market_clone.amm.peg_multiplier = new_peg;

Ok((market_clone, cost))
Expand All @@ -394,6 +405,7 @@ pub fn calculate_optimal_peg_and_budget(
let optimal_peg_cost = calculate_repeg_cost(&market.amm, optimal_peg)?;

let mut check_lower_bound = true;

if fee_budget < max(0, optimal_peg_cost).cast()? {
let half_max_price_spread = target_price
.cast::<u128>()?
Expand Down Expand Up @@ -421,7 +433,9 @@ pub fn calculate_optimal_peg_and_budget(
market.amm.base_asset_reserve,
target_price.cast()?,
)?;

fee_budget = calculate_repeg_cost(&market.amm, optimal_peg)?.cast::<u128>()?;

check_lower_bound = false;
}
}
Expand Down
8 changes: 4 additions & 4 deletions tests/imbalancePerpPnl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@ describe('imbalanced large perp pnl w/ borrow hitting limits', () => {
oraclePriceData00Again
);
console.log('bid0After:', bid0After.toString(), ask0After.toString());
assert(bid0After.eq(new BN(254194605)));
assert(bid0After.eq(new BN(254194105)));
assert(
oraclePriceData00Again.price.eq(
new BN(260.5 * PRICE_PRECISION.toNumber())
Expand Down Expand Up @@ -756,7 +756,7 @@ describe('imbalanced large perp pnl w/ borrow hitting limits', () => {
console.log(prepegAMM.pegMultiplier.toString());
console.log(bid.toString());
console.log(ask.toString());
assert(bid.eq(new BN('254194605')));
assert(bid.eq(new BN('254194105')));
assert(prepegAMM.pegMultiplier.eq(new BN('254313113')));
assert(oraclePriceData0.price.eq(new BN('260500000')));
assert(ask.eq(new BN('266567441')));
Expand Down Expand Up @@ -882,8 +882,8 @@ describe('imbalanced large perp pnl w/ borrow hitting limits', () => {
);

console.log('pnlimbalance:', imbalance.toString());
assert(imbalance.lt(new BN(44454586870 + 20000))); //44k still :o
assert(imbalance.gt(new BN(44454586870 - 20000))); //44k still :o
assert(imbalance.lt(new BN(44454575549 + 20000))); //44k still :o
assert(imbalance.gt(new BN(44454575549 - 20000))); //44k still :o

console.log(
'revenueWithdrawSinceLastSettle:',
Expand Down