Skip to content

Commit

Permalink
Merge branch 'master' into wphan/helius_fee-api
Browse files Browse the repository at this point in the history
  • Loading branch information
wphan committed Jan 26, 2024
2 parents 21d3370 + fbd5d6a commit 98602e5
Show file tree
Hide file tree
Showing 19 changed files with 758 additions and 20 deletions.
22 changes: 20 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Breaking

## [2.55.0] - 2023-01-18
## [2.57.0] - 2023-01-25

## [Unreleased]
### Features

- program: add recenter amm ix ([#836](https://github.com/drift-labs/protocol-v2/pull/836))

### Fixes

### Breaking

## [2.56.0] - 2023-01-24

### Features

### Fixes

- program: enable jit maker to fill same slot as taker placed ([#835](https://github.com/drift-labs/protocol-v2/pull/835))

### Breaking

## [2.55.0] - 2023-01-18

### Features

Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion programs/drift/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "drift"
version = "2.55.0"
version = "2.57.0"
description = "Created with Anchor"
edition = "2018"

Expand Down
53 changes: 53 additions & 0 deletions programs/drift/src/controller/amm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -745,10 +745,63 @@ pub fn move_price(
validate!(
(quote_asset_reserve.cast::<i128>()? - amm.quote_asset_reserve.cast::<i128>()?).abs() < 100,
ErrorCode::InvalidAmmDetected,
"quote_asset_reserve passed doesnt reconcile enough {} vs {}",
quote_asset_reserve.cast::<i128>()?,
amm.quote_asset_reserve.cast::<i128>()?

Check warning on line 750 in programs/drift/src/controller/amm.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/controller/amm.rs#L749-L750

Added lines #L749 - L750 were not covered by tests
)?;

amm.sqrt_k = sqrt_k;

let (_, terminal_quote_reserves, terminal_base_reserves) =
amm::calculate_terminal_price_and_reserves(amm)?;
amm.terminal_quote_asset_reserve = terminal_quote_reserves;

let (min_base_asset_reserve, max_base_asset_reserve) =
amm::calculate_bid_ask_bounds(amm.concentration_coef, terminal_base_reserves)?;

amm.max_base_asset_reserve = max_base_asset_reserve;
amm.min_base_asset_reserve = min_base_asset_reserve;

let reserve_price_after = amm.reserve_price()?;
update_spreads(amm, reserve_price_after)?;

Ok(())
}

// recenter peg with balanced terminal reserves
pub fn recenter_perp_market_amm(amm: &mut AMM, peg_multiplier: u128, sqrt_k: u128) -> DriftResult {
// calculate base/quote reserves for balanced terminal reserves
let swap_direction = if amm.base_asset_amount_with_amm > 0 {
SwapDirection::Remove
} else {
SwapDirection::Add
};
let (new_quote_asset_amount, new_base_asset_amount) = amm::calculate_swap_output(
amm.base_asset_amount_with_amm.unsigned_abs(),
sqrt_k,
swap_direction,
sqrt_k,
)?;

amm.base_asset_reserve = new_base_asset_amount;

let k = bn::U256::from(sqrt_k).safe_mul(bn::U256::from(sqrt_k))?;

amm.quote_asset_reserve = k
.safe_div(bn::U256::from(new_base_asset_amount))?
.try_to_u128()?;

Check warning on line 792 in programs/drift/src/controller/amm.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/controller/amm.rs#L792

Added line #L792 was not covered by tests

validate!(

Check warning on line 794 in programs/drift/src/controller/amm.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/controller/amm.rs#L794

Added line #L794 was not covered by tests
(new_quote_asset_amount.cast::<i128>()? - amm.quote_asset_reserve.cast::<i128>()?).abs()
< 100,
ErrorCode::InvalidAmmDetected,

Check warning on line 797 in programs/drift/src/controller/amm.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/controller/amm.rs#L797

Added line #L797 was not covered by tests
"quote_asset_reserve passed doesnt reconcile enough"
)?;

amm.sqrt_k = sqrt_k;
// todo: could calcualte terminal state cost for altering sqrt_k

amm.peg_multiplier = peg_multiplier;

let (_, terminal_quote_reserves, terminal_base_reserves) =
amm::calculate_terminal_price_and_reserves(amm)?;
Expand Down
319 changes: 313 additions & 6 deletions programs/drift/src/controller/position/tests.rs

Large diffs are not rendered by default.

17 changes: 16 additions & 1 deletion programs/drift/src/instructions/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,21 @@ pub fn handle_move_amm_price(
Ok(())
}

#[access_control(

Check warning on line 870 in programs/drift/src/instructions/admin.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/instructions/admin.rs#L870

Added line #L870 was not covered by tests
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_recenter_perp_market_amm(

Check warning on line 873 in programs/drift/src/instructions/admin.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/instructions/admin.rs#L873

Added line #L873 was not covered by tests
ctx: Context<AdminUpdatePerpMarket>,
peg_multiplier: u128,
sqrt_k: u128,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
controller::amm::recenter_perp_market_amm(&mut perp_market.amm, peg_multiplier, sqrt_k)?;
validate_perp_market(perp_market)?;

Check warning on line 880 in programs/drift/src/instructions/admin.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/instructions/admin.rs#L878-L880

Added lines #L878 - L880 were not covered by tests

Ok(())

Check warning on line 882 in programs/drift/src/instructions/admin.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/instructions/admin.rs#L882

Added line #L882 was not covered by tests
}

#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
Expand Down Expand Up @@ -1166,7 +1181,7 @@ pub fn handle_update_k(ctx: Context<AdminUpdateK>, sqrt_k: u128) -> Result<()> {

let update_k_result = get_update_k_result(perp_market, new_sqrt_k_u192, true)?;

let adjustment_cost = math::cp_curve::adjust_k_cost(perp_market, &update_k_result)?;
let adjustment_cost: i128 = math::cp_curve::adjust_k_cost(perp_market, &update_k_result)?;

Check warning on line 1184 in programs/drift/src/instructions/admin.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/instructions/admin.rs#L1184

Added line #L1184 was not covered by tests

math::cp_curve::update_k(perp_market, &update_k_result)?;

Expand Down
8 changes: 8 additions & 0 deletions programs/drift/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,14 @@ pub mod drift {
handle_move_amm_price(ctx, base_asset_reserve, quote_asset_reserve, sqrt_k)
}

pub fn recenter_perp_market_amm(

Check warning on line 629 in programs/drift/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/lib.rs#L629

Added line #L629 was not covered by tests
ctx: Context<AdminUpdatePerpMarket>,
peg_multiplier: u128,
sqrt_k: u128,
) -> Result<()> {
handle_recenter_perp_market_amm(ctx, peg_multiplier, sqrt_k)

Check warning on line 634 in programs/drift/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/lib.rs#L634

Added line #L634 was not covered by tests
}

pub fn update_perp_market_expiry(
ctx: Context<AdminUpdatePerpMarket>,
expiry_ts: i64,
Expand Down
2 changes: 1 addition & 1 deletion programs/drift/src/math/matching.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub fn is_maker_for_taker(
slot: u64,
) -> DriftResult<bool> {
// Maker and taker order not allowed to match if both were placed in the current slot
if slot == maker_order.slot && slot == taker_order.slot {
if slot == maker_order.slot && slot == taker_order.slot && !maker_order.is_jit_maker() {
return Ok(false);
};

Expand Down
5 changes: 4 additions & 1 deletion programs/drift/src/math/repeg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,11 +284,14 @@ pub fn adjust_amm(
let adjustment_cost: i128 = if adjust_k && can_lower_k {
// TODO can be off by 1?

// always let protocol-owned sqrt_k be either least .1% of lps or the base amount / min order
let new_sqrt_k_lower_bound = market.amm.get_lower_bound_sqrt_k()?;

let new_sqrt_k = market
.amm
.sqrt_k
.safe_sub(market.amm.sqrt_k.safe_div(1000)?)?
.max(market.amm.user_lp_shares.safe_add(1)?);
.max(new_sqrt_k_lower_bound);

let update_k_result =
cp_curve::get_update_k_result(market, bn::U192::from(new_sqrt_k), true)?;
Expand Down
9 changes: 9 additions & 0 deletions programs/drift/src/state/perp_market.rs
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,15 @@ impl AMM {
}
}

pub fn get_lower_bound_sqrt_k(self) -> DriftResult<u128> {
Ok(self.sqrt_k.min(
self.user_lp_shares
.safe_add(self.user_lp_shares.safe_div(1000)?)?
.max(self.min_order_size.cast()?)
.max(self.base_asset_amount_with_amm.unsigned_abs().cast()?),
))
}

pub fn get_protocol_owned_position(self) -> DriftResult<i64> {
self.base_asset_amount_with_amm
.safe_add(self.base_asset_amount_with_unsettled_lp)?
Expand Down
5 changes: 5 additions & 0 deletions programs/drift/src/validation/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,11 @@ fn validate_post_only_order(
valid_oracle_price: Option<i64>,
slot: u64,
) -> DriftResult {
// jit maker can fill against amm
if order.is_jit_maker() {
return Ok(());

Check warning on line 225 in programs/drift/src/validation/order.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/validation/order.rs#L224-L225

Added lines #L224 - L225 were not covered by tests
}

let limit_price =
order.force_get_limit_price(valid_oracle_price, None, slot, market.amm.order_tick_size)?;

Expand Down
2 changes: 1 addition & 1 deletion sdk/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.56.0-beta.0
2.58.0-beta.0
2 changes: 1 addition & 1 deletion sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@drift-labs/sdk",
"version": "2.56.0-beta.0",
"version": "2.58.0-beta.0",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"author": "crispheaney",
Expand Down
26 changes: 26 additions & 0 deletions sdk/src/adminClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,32 @@ export class AdminClient extends DriftClient {
return txSig;
}

public async recenterPerpMarketAmm(
perpMarketIndex: number,
pegMultiplier: BN,
sqrtK: BN
): Promise<TransactionSignature> {
const marketPublicKey = await getPerpMarketPublicKey(
this.program.programId,
perpMarketIndex
);

const tx = await this.program.transaction.recenterPerpMarketAmm(
pegMultiplier,
sqrtK,
{
accounts: {
state: await this.getStatePublicKey(),
admin: this.wallet.publicKey,
perpMarket: marketPublicKey,
},
}
);

const { txSig } = await this.sendTransaction(tx, [], this.opts);
return txSig;
}

public async updatePerpMarketConcentrationScale(
perpMarketIndex: number,
concentrationScale: BN
Expand Down
20 changes: 20 additions & 0 deletions sdk/src/constants/perpMarkets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,16 @@ export const DevnetPerpMarkets: PerpMarketConfig[] = [
launchTs: 1704209558000,
oracleSource: OracleSource.PYTH,
},
// {
// fullName: 'WIF',
// category: ['Meme', 'Dog'],
// symbol: 'WIF-PERP',
// baseAssetSymbol: 'WIF',
// marketIndex: 23,
// oracle: new PublicKey('5i1sz2QQjCQt9PnhuPvqbiYUAYCgjdRnza1JbiH2qRCo'),
// launchTs: 1706219971000,
// oracleSource: OracleSource.PYTH,
// },
];

export const MainnetPerpMarkets: PerpMarketConfig[] = [
Expand Down Expand Up @@ -477,6 +487,16 @@ export const MainnetPerpMarkets: PerpMarketConfig[] = [
launchTs: 1704209558000,
oracleSource: OracleSource.PYTH,
},
{
fullName: 'WIF',
category: ['Meme', 'Dog'],
symbol: 'WIF-PERP',
baseAssetSymbol: 'WIF',
marketIndex: 23,
oracle: new PublicKey('6ABgrEZk8urs6kJ1JNdC1sspH5zKXRqxy8sg3ZG2cQps'),
launchTs: 1706219971000,
oracleSource: OracleSource.PYTH,
},
];

export const PerpMarkets: { [key in DriftEnv]: PerpMarketConfig[] } = {
Expand Down
10 changes: 10 additions & 0 deletions sdk/src/constants/spotMarkets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,16 @@ export const MainnetSpotMarkets: SpotMarketConfig[] = [
precisionExp: NINE,
serumMarket: new PublicKey('H87FfmHABiZLRGrDsXRZtqq25YpARzaokCzL1vMYGiep'),
},
{
symbol: 'WIF',
marketIndex: 10,
oracle: new PublicKey('6ABgrEZk8urs6kJ1JNdC1sspH5zKXRqxy8sg3ZG2cQps'),
oracleSource: OracleSource.PYTH,
mint: new PublicKey('EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm'),
precision: new BN(10).pow(SIX),
precisionExp: SIX,
serumMarket: new PublicKey('2BtDHBTCTUxvdur498ZEcMgimasaFrY5GzLv8wS8XgCb'),
},
];

export const SpotMarkets: { [key in DriftEnv]: SpotMarketConfig[] } = {
Expand Down
8 changes: 5 additions & 3 deletions sdk/src/driftClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2690,9 +2690,11 @@ export class DriftClient {
txKeys
);

const { txSig, slot } = await this.txSender.sendRawTransaction(
signedVersionedMarketOrderTx.serialize(),
this.opts
const { txSig, slot } = await this.sendTransaction(
signedVersionedMarketOrderTx,
[],
this.opts,
true
);
this.perpMarketLastSlotCache.set(orderParams.marketIndex, slot);

Expand Down
32 changes: 31 additions & 1 deletion sdk/src/idl/drift.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "2.55.0",
"version": "2.57.0",
"name": "drift",
"instructions": [
{
Expand Down Expand Up @@ -2972,6 +2972,36 @@
}
]
},
{
"name": "recenterPerpMarketAmm",
"accounts": [
{
"name": "admin",
"isMut": false,
"isSigner": true
},
{
"name": "state",
"isMut": false,
"isSigner": false
},
{
"name": "perpMarket",
"isMut": true,
"isSigner": false
}
],
"args": [
{
"name": "pegMultiplier",
"type": "u128"
},
{
"name": "sqrtK",
"type": "u128"
}
]
},
{
"name": "updatePerpMarketExpiry",
"accounts": [
Expand Down
Loading

0 comments on commit 98602e5

Please sign in to comment.