Skip to content

Commit

Permalink
Merge branch 'master' into nick/order-tx-updates
Browse files Browse the repository at this point in the history
  • Loading branch information
lowkeynicc committed Jan 6, 2024
2 parents ac639c2 + 1e2d0ab commit 8bce146
Show file tree
Hide file tree
Showing 10 changed files with 323 additions and 39 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- sdk: add ability to do placeAndTake order with bracket orders attached
- sdk: add option to cancel existing orders in market for place and take order

- program: increase full perp liquidation threshold ([#807](https://github.com/drift-labs/protocol-v2/pull/807))
- program: remove spot fee pool transfer ([#800](https://github.com/drift-labs/protocol-v2/pull/800))
- program: increase insurance tier max ([#784](https://github.com/drift-labs/protocol-v2/pull/784))

### Fixes

- ts-sdk: contract tier funding rate clamp ([#785](https://github.com/drift-labs/protocol-v2/pull/785))
- ts-sdk: fix oracle is valid ([#806](https://github.com/drift-labs/protocol-v2/pull/806))

### Breaking


Expand Down
4 changes: 2 additions & 2 deletions programs/drift/src/controller/liquidation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -367,8 +367,8 @@ pub fn liquidate_perp(
calculate_base_asset_value_with_oracle_price(user_base_asset_amount.cast()?, oracle_price)?
.cast::<u64>()?;

// if position is less than $10, liquidator can liq all of it
let min_base_asset_amount = if base_asset_value > 10 * QUOTE_PRECISION_U64 {
// if position is less than $50, liquidator can liq all of it
let min_base_asset_amount = if base_asset_value > 50 * QUOTE_PRECISION_U64 {
0_u64
} else {
user_base_asset_amount
Expand Down
28 changes: 2 additions & 26 deletions programs/drift/src/controller/orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ use crate::controller::position::{
PositionDirection,
};
use crate::controller::spot_balance::{
transfer_spot_balance_to_revenue_pool, update_spot_balances,
update_spot_market_cumulative_interest,
update_spot_balances, update_spot_market_cumulative_interest,
};
use crate::controller::spot_position::{
decrease_spot_open_bids_and_asks, increase_spot_open_bids_and_asks,
Expand All @@ -31,8 +30,7 @@ use crate::math::amm_jit::calculate_amm_jit_liquidity;
use crate::math::auction::{calculate_auction_params_for_trigger_order, calculate_auction_prices};
use crate::math::casting::Cast;
use crate::math::constants::{
BASE_PRECISION_U64, FEE_POOL_TO_REVENUE_POOL_THRESHOLD, FIVE_MINUTE, ONE_HOUR, PERP_DECIMALS,
QUOTE_SPOT_MARKET_INDEX,
BASE_PRECISION_U64, FIVE_MINUTE, ONE_HOUR, PERP_DECIMALS, QUOTE_SPOT_MARKET_INDEX,
};
use crate::math::fees::{determine_user_fee_tier, ExternalFillFees, FillFees};
use crate::math::fulfillment::{
Expand Down Expand Up @@ -4122,20 +4120,6 @@ pub fn fulfill_spot_order_with_match(
false,
)?;

let fee_pool_amount = get_token_amount(
base_market.spot_fee_pool.scaled_balance,
quote_market,
&SpotBalanceType::Deposit,
)?;

if fee_pool_amount > FEE_POOL_TO_REVENUE_POOL_THRESHOLD * 2 {
transfer_spot_balance_to_revenue_pool(
fee_pool_amount - FEE_POOL_TO_REVENUE_POOL_THRESHOLD,
quote_market,
&mut base_market.spot_fee_pool,
)?;
}

let fill_record_id = get_then_update_id!(base_market, next_fill_record_id);
let order_action_explanation = if maker.orders[maker_order_index].is_jit_maker() {
OrderActionExplanation::OrderFilledWithMatchJit
Expand Down Expand Up @@ -4327,14 +4311,6 @@ pub fn fulfill_spot_order_with_external_market(
&SpotBalanceType::Deposit,
)?;

if fee_pool_amount > FEE_POOL_TO_REVENUE_POOL_THRESHOLD * 2 {
transfer_spot_balance_to_revenue_pool(
fee_pool_amount - FEE_POOL_TO_REVENUE_POOL_THRESHOLD,
quote_market,
&mut base_market.spot_fee_pool,
)?;
}

let ExternalFillFees {
user_fee: taker_fee,
fee_to_market,
Expand Down
4 changes: 2 additions & 2 deletions programs/drift/src/math/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,8 @@ pub const TWO_HUNDRED_FIFTY_QUOTE: u64 = 250_u64 * QUOTE_PRECISION_U64;

// INSURANCE TIERS
pub const INSURANCE_A_MAX: u64 = ONE_HUNDRED_MILLION_QUOTE as u64;
pub const INSURANCE_B_MAX: u64 = ONE_HUNDRED_THOUSAND_QUOTE as u64;
pub const INSURANCE_C_MAX: u64 = TWENTY_FIVE_THOUSAND_QUOTE as u64;
pub const INSURANCE_B_MAX: u64 = ONE_MILLION_QUOTE as u64;
pub const INSURANCE_C_MAX: u64 = ONE_HUNDRED_THOUSAND_QUOTE as u64;
pub const INSURANCE_SPECULATIVE_MAX: u64 = 0;

// QUOTE THRESHOLDS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ export class PollingInsuranceFundStakeAccountSubscriber

await this.addToAccountLoader();

await this.fetchIfUnloaded();
if (this.doesAccountExist()) {
this.eventEmitter.emit('update');
}
Expand Down
2 changes: 1 addition & 1 deletion sdk/src/jupiter/jupiterClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ export interface QuoteResponse {
* @type {string}
* @memberof QuoteResponse
*/
error?: string
error?: string;
}

export class JupiterClient {
Expand Down
31 changes: 29 additions & 2 deletions sdk/src/math/funding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import {
ONE,
FUNDING_RATE_OFFSET_DENOMINATOR,
} from '../constants/numericConstants';
import { PerpMarketAccount, isVariant } from '../types';
import { ContractTier, PerpMarketAccount, isVariant } from '../types';

Check failure on line 10 in sdk/src/math/funding.ts

View workflow job for this annotation

GitHub Actions / yarn-lint

'ContractTier' is defined but never used. Allowed unused vars must match /^_/u
import { OraclePriceData } from '../oracles/types';
import { calculateBidAskPrice } from './amm';
import { calculateLiveOracleTwap } from './oracles';
import { clampBN } from './utils';

function calculateLiveMarkTwap(
market: PerpMarketAccount,
Expand Down Expand Up @@ -160,8 +161,15 @@ export async function calculateAllEstimatedFundingRate(
const twapSpreadWithOffset = twapSpread.add(
oracleTwap.abs().div(FUNDING_RATE_OFFSET_DENOMINATOR)
);
const maxSpread = getMaxPriceDivergenceForFundingRate(market, oracleTwap);

const twapSpreadPct = twapSpreadWithOffset
const clampedSpreadWithOffset = clampBN(
twapSpreadWithOffset,
maxSpread.mul(new BN(-1)),
maxSpread
);

const twapSpreadPct = clampedSpreadWithOffset
.mul(PRICE_PRECISION)
.mul(new BN(100))
.div(oracleTwap);
Expand Down Expand Up @@ -234,6 +242,25 @@ export async function calculateAllEstimatedFundingRate(
return [markTwap, oracleTwap, lowerboundEst, cappedAltEst, interpEst];
}

function getMaxPriceDivergenceForFundingRate(
market: PerpMarketAccount,
oracleTwap: BN
) {
if (isVariant(market.contractTier, 'a')) {
return oracleTwap.divn(33);
} else if (isVariant(market.contractTier, 'b')) {
return oracleTwap.divn(33);
} else if (isVariant(market.contractTier, 'c')) {
return oracleTwap.divn(20);
} else if (isVariant(market.contractTier, 'speculative')) {
return oracleTwap.divn(10);
} else if (isVariant(market.contractTier, 'isolated')) {
return oracleTwap.divn(10);
} else {
return oracleTwap.divn(10);
}
}

/**
*
* @param market
Expand Down
4 changes: 2 additions & 2 deletions sdk/src/math/oracles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ export function isOracleValid(
.div(oraclePriceData.price)
.gt(oracleGuardRails.validity.confidenceIntervalMaxSize);

const oracleIsStale = oraclePriceData.slot
.sub(new BN(slot))
const oracleIsStale = new BN(slot)
.sub(oraclePriceData.slot)
.gt(oracleGuardRails.validity.slotsBeforeStaleForAmm);

return !(
Expand Down
4 changes: 3 additions & 1 deletion sdk/src/math/superStake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,9 @@ export async function calculateSolEarned({
const now = Date.now() / 1000;
const timestamps: number[] = [
now,
...depositRecords.map((r) => r.ts.toNumber()),
...depositRecords
.filter((r) => r.marketIndex === marketIndex)
.map((r) => r.ts.toNumber()),
];

let lstRatios = new Map<number, number>();
Expand Down
Loading

0 comments on commit 8bce146

Please sign in to comment.