Skip to content

Commit

Permalink
Merge branch 'master' into crispheaney/amm-fill-step-size
Browse files Browse the repository at this point in the history
  • Loading branch information
crispheaney authored Nov 14, 2023
2 parents b8a9382 + 7e55577 commit 0cb7e1b
Show file tree
Hide file tree
Showing 22 changed files with 359 additions and 132 deletions.
30 changes: 30 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -251,3 +251,33 @@ jobs:
with:
name: build
path: target/deploy/drift.so
code-coverage:
name: Code Coverage
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ env.RUST_TOOLCHAIN }}
profile: minimal
override: true
- name: Cache build artefacts
uses: Swatinem/rust-cache@v1
- name: Run package checks
run: cargo check # run package checks
- name: Run cargo-tarpaulin
uses: actions-rs/[email protected]
with:
version: '0.15.0'
args: '-- --test-threads 1'
- name: Upload to codecov.io
uses: codecov/[email protected]
with:
token: ${{secrets.CODECOV_TOKEN}}
- name: Archive code coverage results
uses: actions/upload-artifact@v1
with:
name: code-coverage-report
path: cobertura.xml

5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Features

- program: boost max sub accounts to 20k

### Fixes

- program: allow amm to fill step size ([#672](https://github.com/drift-labs/protocol-v2/pull/672))
- program: add add update_liquidation_margin_buffer_ratio ([#695](https://github.com/drift-labs/protocol-v2/pull/695))
- program: account for fee pool when settling positive pnl ([#687](https://github.com/drift-labs/protocol-v2/pull/687))
- sdk: fix bug which incorrectly calculated leverage after trade for a market with no position but short orders open

### Breaking

Expand Down
9 changes: 9 additions & 0 deletions codecov.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
comment:
layout: "header, diff, flags, components"

component_management:
individual_components:
- component_id: drift
name: drift
paths:
- programs/drift
4 changes: 2 additions & 2 deletions programs/drift/src/controller/insurance/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1534,7 +1534,7 @@ fn test_transfer_protocol_owned_stake() {
.unwrap();
if_balance -= amount_returned;

assert_eq!(amount_returned, (99500000000) as u64);
assert_eq!(amount_returned, 99500000000);
assert_eq!(spot_market.insurance_fund.user_shares, 0);
assert_eq!(spot_market.insurance_fund.total_shares, 21105203599);

Expand Down Expand Up @@ -1597,7 +1597,7 @@ fn test_transfer_protocol_owned_stake() {

let mut expected_if_stake_2 = InsuranceFundStake::new(Pubkey::default(), 0, 0);
expected_if_stake_2
.increase_if_shares(21105203599 as u128, &spot_market)
.increase_if_shares(21105203599, &spot_market)
.unwrap();

assert_eq!(user_stats_2.if_staked_quote_asset_amount, 99500000000);
Expand Down
18 changes: 15 additions & 3 deletions programs/drift/src/controller/pnl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,23 @@ pub fn settle_pnl(
perp_market.pnl_pool.scaled_balance,
spot_market,
perp_market.pnl_pool.balance_type(),
)?;

let fraction_of_fee_pool_token_amount = get_token_amount(
perp_market.amm.fee_pool.scaled_balance,
spot_market,
perp_market.amm.fee_pool.balance_type(),
)?
.cast()?;
.safe_div(5)?;

// add a buffer from fee pool for pnl pool balance
let pnl_tokens_available: i128 = pnl_pool_token_amount
.safe_add(fraction_of_fee_pool_token_amount)?
.cast()?;

let net_user_pnl = calculate_net_user_pnl(&perp_market.amm, oracle_price)?;
let max_pnl_pool_excess = if net_user_pnl < pnl_pool_token_amount {
pnl_pool_token_amount.safe_sub(net_user_pnl.max(0))?
let max_pnl_pool_excess = if net_user_pnl < pnl_tokens_available {
pnl_tokens_available.safe_sub(net_user_pnl.max(0))?
} else {
0
};
Expand Down
8 changes: 8 additions & 0 deletions programs/drift/src/instructions/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1937,6 +1937,14 @@ pub fn handle_update_liquidation_duration(
Ok(())
}

pub fn handle_update_liquidation_margin_buffer_ratio(
ctx: Context<AdminUpdateState>,
liquidation_margin_buffer_ratio: u32,
) -> Result<()> {
ctx.accounts.state.liquidation_margin_buffer_ratio = liquidation_margin_buffer_ratio;
Ok(())
}

pub fn handle_update_oracle_guard_rails(
ctx: Context<AdminUpdateState>,
oracle_guard_rails: OracleGuardRails,
Expand Down
2 changes: 1 addition & 1 deletion programs/drift/src/instructions/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ pub fn handle_initialize_user(
safe_increment!(state.number_of_sub_accounts, 1);

validate!(
state.number_of_sub_accounts <= 15000,
state.number_of_sub_accounts <= 20000,
ErrorCode::MaxNumberOfUsers
)?;

Expand Down
7 changes: 7 additions & 0 deletions programs/drift/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -933,6 +933,13 @@ pub mod drift {
handle_update_liquidation_duration(ctx, liquidation_duration)
}

pub fn update_liquidation_margin_buffer_ratio(
ctx: Context<AdminUpdateState>,
liquidation_margin_buffer_ratio: u32,
) -> Result<()> {
handle_update_liquidation_margin_buffer_ratio(ctx, liquidation_margin_buffer_ratio)
}

pub fn update_oracle_guard_rails(
ctx: Context<AdminUpdateState>,
oracle_guard_rails: OracleGuardRails,
Expand Down
2 changes: 1 addition & 1 deletion sdk/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.43.0-beta.6
2.43.0-beta.16
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.43.0-beta.6",
"version": "2.43.0-beta.16",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"author": "crispheaney",
Expand Down
26 changes: 20 additions & 6 deletions sdk/src/accounts/webSocketAccountSubscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export class WebSocketAccountSubscriber<T> implements AccountSubscriber<T> {
onChange: (data: T) => void;
listenerId?: number;
resubTimeoutMs?: number;
isUnsubscribing = false;

timeoutId?: NodeJS.Timeout;

receivingData: boolean;
Expand All @@ -34,7 +36,7 @@ export class WebSocketAccountSubscriber<T> implements AccountSubscriber<T> {
}

async subscribe(onChange: (data: T) => void): Promise<void> {
if (this.listenerId) {
if (this.listenerId || this.isUnsubscribing) {
return;
}

Expand Down Expand Up @@ -80,6 +82,11 @@ export class WebSocketAccountSubscriber<T> implements AccountSubscriber<T> {
throw new Error('onChange callback function must be set');
}
this.timeoutId = setTimeout(async () => {
if (this.isUnsubscribing) {
// If we are in the process of unsubscribing, do not attempt to resubscribe
return;
}

if (this.receivingData) {
console.log(
`No ws data from ${this.accountName} in ${this.resubTimeoutMs}ms, resubscribing`
Expand Down Expand Up @@ -154,13 +161,20 @@ export class WebSocketAccountSubscriber<T> implements AccountSubscriber<T> {
}

unsubscribe(): Promise<void> {
this.isUnsubscribing = true;
clearTimeout(this.timeoutId);
this.timeoutId = undefined;

if (this.listenerId) {
const promise =
this.program.provider.connection.removeAccountChangeListener(
this.listenerId
);
this.listenerId = undefined;
const promise = this.program.provider.connection
.removeAccountChangeListener(this.listenerId)
.then(() => {
this.listenerId = undefined;
this.isUnsubscribing = false;
});
return promise;
} else {
this.isUnsubscribing = false;
}
}
}
25 changes: 19 additions & 6 deletions sdk/src/accounts/webSocketProgramAccountSubscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export class WebSocketProgramAccountSubscriber<T>
onChange: (accountId: PublicKey, data: T, context: Context) => void;
listenerId?: number;
resubTimeoutMs?: number;
isUnsubscribing = false;
timeoutId?: NodeJS.Timeout;
options: { filters: MemcmpFilter[]; commitment?: Commitment };

Expand Down Expand Up @@ -48,7 +49,7 @@ export class WebSocketProgramAccountSubscriber<T>
async subscribe(
onChange: (accountId: PublicKey, data: T, context: Context) => void
): Promise<void> {
if (this.listenerId) {
if (this.listenerId || this.isUnsubscribing) {
return;
}

Expand Down Expand Up @@ -81,6 +82,11 @@ export class WebSocketProgramAccountSubscriber<T>
throw new Error('onChange callback function must be set');
}
this.timeoutId = setTimeout(async () => {
if (this.isUnsubscribing) {
// If we are in the process of unsubscribing, do not attempt to resubscribe
return;
}

if (this.receivingData) {
console.log(
`No ws data from ${this.subscriptionName} in ${this.resubTimeoutMs}ms, resubscribing`
Expand Down Expand Up @@ -140,13 +146,20 @@ export class WebSocketProgramAccountSubscriber<T>
}

unsubscribe(): Promise<void> {
this.isUnsubscribing = true;
clearTimeout(this.timeoutId);
this.timeoutId = undefined;

if (this.listenerId) {
const promise =
this.program.provider.connection.removeAccountChangeListener(
this.listenerId
);
this.listenerId = undefined;
const promise = this.program.provider.connection
.removeAccountChangeListener(this.listenerId)
.then(() => {
this.listenerId = undefined;
this.isUnsubscribing = false;
});
return promise;
} else {
this.isUnsubscribing = false;
}
}
}
14 changes: 14 additions & 0 deletions sdk/src/adminClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,20 @@ export class AdminClient extends DriftClient {
);
}

public async updateLiquidationMarginBufferRatio(
updateLiquidationMarginBufferRatio: number
): Promise<TransactionSignature> {
return await this.program.rpc.updateLiquidationMarginBufferRatio(
updateLiquidationMarginBufferRatio,
{
accounts: {
admin: this.wallet.publicKey,
state: await this.getStatePublicKey(),
},
}
);
}

public async updateOracleGuardRails(
oracleGuardRails: OracleGuardRails
): Promise<TransactionSignature> {
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 @@ -184,6 +184,16 @@ export const DevnetPerpMarkets: PerpMarketConfig[] = [
launchTs: 1698074659000,
oracleSource: OracleSource.PYTH,
},
{
fullName: 'Rollbit',
category: ['Exchange'],
symbol: 'RLB-PERP',
baseAssetSymbol: 'RLB',
marketIndex: 17,
oracle: new PublicKey('6BmJozusMugAySsfNfMFsU1YRWcGwyP3oycNX9Pv9oCz'),
launchTs: 11699265968000,
oracleSource: OracleSource.PYTH,
},
];

export const MainnetPerpMarkets: PerpMarketConfig[] = [
Expand Down Expand Up @@ -357,6 +367,16 @@ export const MainnetPerpMarkets: PerpMarketConfig[] = [
launchTs: 1698074659000,
oracleSource: OracleSource.PYTH,
},
{
fullName: 'Rollbit',
category: ['Exchange'],
symbol: 'RLB-PERP',
baseAssetSymbol: 'RLB',
marketIndex: 17,
oracle: new PublicKey('4BA3RcS4zE32WWgp49vvvre2t6nXY1W1kMyKZxeeuUey'),
launchTs: 11699265968000,
oracleSource: OracleSource.PYTH,
},
];

export const PerpMarkets: { [key in DriftEnv]: PerpMarketConfig[] } = {
Expand Down
2 changes: 2 additions & 0 deletions sdk/src/dlob/DLOB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1725,6 +1725,7 @@ export class DLOB {
return {
bids,
asks,
slot,
};
}

Expand Down Expand Up @@ -1785,6 +1786,7 @@ export class DLOB {
return {
bids,
asks,
slot,
};
}

Expand Down
3 changes: 3 additions & 0 deletions sdk/src/dlob/orderBookLevels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export type L2Level = {
export type L2OrderBook = {
asks: L2Level[];
bids: L2Level[];
slot?: number;
};

export interface L2OrderBookGenerator {
Expand All @@ -46,6 +47,7 @@ export type L3Level = {
export type L3OrderBook = {
asks: L3Level[];
bids: L3Level[];
slot?: number;
};

export const DEFAULT_TOP_OF_BOOK_QUOTE_AMOUNTS = [
Expand Down Expand Up @@ -363,6 +365,7 @@ export function groupL2(
return {
bids: groupL2Levels(l2.bids, grouping, PositionDirection.LONG, depth),
asks: groupL2Levels(l2.asks, grouping, PositionDirection.SHORT, depth),
slot: l2.slot,
};
}

Expand Down
Loading

0 comments on commit 0cb7e1b

Please sign in to comment.