Skip to content

Commit

Permalink
program: openbook v2 integration (#1112)
Browse files Browse the repository at this point in the history
---------

Co-authored-by: soundsonacid <[email protected]>
Co-authored-by: Chris Heaney <[email protected]>
  • Loading branch information
3 people committed Jul 17, 2024
1 parent e91295b commit 16b5660
Show file tree
Hide file tree
Showing 30 changed files with 6,133 additions and 5 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -305,4 +305,4 @@ jobs:
uses: actions/upload-artifact@v3
with:
name: build
path: target/deploy/drift.so
path: target/deploy/drift.so
3 changes: 3 additions & 0 deletions Anchor.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
cluster = "localnet"
wallet = "~/.config/solana/id.json"

[workspace]
exclude = ["programs/openbook_v2"]

[scripts]
test = "echo" # need to call anchor test to update metadata field in idl before running tests, so just do a noop
lint = "yarn prettify:fix && cargo fmt"
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- program: track fuel for if staking ([#1127](https://github.com/drift-labs/protocol-v2/pull/1127))
- program: validate fee structure ([#1075](https://github.com/drift-labs/protocol-v2/pull/1075))
- program: check 5 min oracle twap divergence in trigger order ([#1116](https://github.com/drift-labs/protocol-v2/pull/1116))
- program: openbook v2 integration ([#1112](https://github.com/drift-labs/protocol-v2/pull/1112))

### Fixes

Expand Down
10 changes: 10 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions programs/drift/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ solana-security-txt = "1.1.0"
static_assertions = "1.1.0"
drift-macros = { git = "https://github.com/drift-labs/drift-macros.git", rev = "c57d87" }
switchboard = { path = "../switchboard", features = ["no-entrypoint"] }
openbook-v2-light = { path = "../openbook_v2", features = ["no-entrypoint"] }
ahash = "=0.8.6"
byteorder = "1.4.3"

Expand Down
6 changes: 6 additions & 0 deletions programs/drift/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,12 @@ pub enum ErrorCode {
OracleMismatchedVaaAndPriceUpdates,
#[msg("Remaining account passed is not a valid pda")]
OracleBadRemainingAccountPublicKey,
#[msg("FailedOpenbookV2CPI")]
FailedOpenbookV2CPI,
#[msg("InvalidOpenbookV2Program")]
InvalidOpenbookV2Program,
#[msg("InvalidOpenbookV2Market")]
InvalidOpenbookV2Market,
}

#[macro_export]
Expand Down
132 changes: 132 additions & 0 deletions programs/drift/src/instructions/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ use crate::math::spot_balance::get_token_amount;
use crate::math::{amm, bn};
use crate::math_error;
use crate::state::events::CurveRecord;
use crate::state::fulfillment_params::openbook_v2::{
OpenbookV2Context, OpenbookV2FulfillmentConfig,
};
use crate::state::fulfillment_params::phoenix::PhoenixMarketContext;
use crate::state::fulfillment_params::phoenix::PhoenixV1FulfillmentConfig;
use crate::state::fulfillment_params::serum::SerumContext;
Expand Down Expand Up @@ -444,6 +447,82 @@ pub fn handle_update_serum_vault(ctx: Context<UpdateSerumVault>) -> Result<()> {
Ok(())
}

pub fn handle_initialize_openbook_v2_fulfillment_config(
ctx: Context<InitializeOpenbookV2FulfillmentConfig>,
market_index: u16,
) -> Result<()> {
validate!(
market_index != QUOTE_SPOT_MARKET_INDEX,
ErrorCode::InvalidSpotMarketAccount,
"Cannot add openbook v2 market to quote asset"
)?;

let base_spot_market = load!(&ctx.accounts.base_spot_market)?;
let quote_spot_market = load!(&ctx.accounts.quote_spot_market)?;

let openbook_v2_program_id = openbook_v2_light::id();

validate!(
ctx.accounts.openbook_v2_program.key() == openbook_v2_program_id,
ErrorCode::InvalidOpenbookV2Program
)?;

let openbook_v2_market_context = OpenbookV2Context {
openbook_v2_program: &ctx.accounts.openbook_v2_program,
openbook_v2_market: &ctx.accounts.openbook_v2_market,
};
let market = openbook_v2_market_context.load_openbook_v2_market()?;
validate!(
market.base_mint == base_spot_market.mint,
ErrorCode::InvalidOpenbookV2Market,
"Invalid base mint"
)?;

validate!(
market.quote_mint == quote_spot_market.mint,
ErrorCode::InvalidOpenbookV2Market,
"Invalid quote mint"
)?;

validate!(
market.taker_fee == 0,
ErrorCode::InvalidOpenbookV2Market,
"Fee must be 0"
)?;

let market_step_size = market.base_lot_size as u64;
let valid_step_size = base_spot_market.order_step_size >= market_step_size
&& base_spot_market
.order_step_size
.rem_euclid(market_step_size)
== 0;

validate!(
valid_step_size,
ErrorCode::InvalidOpenbookV2Market,
"base market step size ({}) not a multiple of Openbook V2 base lot size ({})",
base_spot_market.order_step_size,
market_step_size
)?;

let openbook_v2_fulfillment_config_key = ctx.accounts.openbook_v2_fulfillment_config.key();
let mut openbook_v2_fulfillment_config =
ctx.accounts.openbook_v2_fulfillment_config.load_init()?;
*openbook_v2_fulfillment_config = openbook_v2_market_context
.to_openbook_v2_fulfillment_config(&openbook_v2_fulfillment_config_key, market_index)?;
Ok(())
}

pub fn handle_update_openbook_v2_fulfillment_config_status(
ctx: Context<UpdateOpenbookV2FulfillmentConfig>,
status: SpotFulfillmentConfigStatus,
) -> Result<()> {
let mut config = load_mut!(ctx.accounts.openbook_v2_fulfillment_config)?;
msg!("config.status {:?} -> {:?}", config.status, status);
config.status = status;
Ok(())
}

pub fn handle_initialize_phoenix_fulfillment_config(
ctx: Context<InitializePhoenixFulfillmentConfig>,
market_index: u16,
Expand Down Expand Up @@ -4355,6 +4434,59 @@ pub struct DeletePrelaunchOracle<'info> {
pub state: Box<Account<'info, State>>,
}

#[derive(Accounts)]
#[instruction(market_index: u16)]
pub struct InitializeOpenbookV2FulfillmentConfig<'info> {
#[account(
seeds = [b"spot_market", market_index.to_le_bytes().as_ref()],
bump,
)]
pub base_spot_market: AccountLoader<'info, SpotMarket>,
#[account(
seeds = [b"spot_market", 0_u16.to_le_bytes().as_ref()],
bump,
)]
pub quote_spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
has_one = admin
)]
pub state: Box<Account<'info, State>>,
/// CHECK: checked in ix
pub openbook_v2_program: AccountInfo<'info>,
/// CHECK: checked in ix
pub openbook_v2_market: AccountInfo<'info>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: program signer
pub drift_signer: AccountInfo<'info>,
#[account(
init,
seeds = [b"openbook_v2_fulfillment_config".as_ref(), openbook_v2_market.key.as_ref()],
space = OpenbookV2FulfillmentConfig::SIZE,
bump,
payer = admin,
)]
pub openbook_v2_fulfillment_config: AccountLoader<'info, OpenbookV2FulfillmentConfig>,
#[account(mut)]
pub admin: Signer<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct UpdateOpenbookV2FulfillmentConfig<'info> {
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub openbook_v2_fulfillment_config: AccountLoader<'info, OpenbookV2FulfillmentConfig>,
#[account(mut)]
pub admin: Signer<'info>,
}

#[derive(Accounts)]
#[instruction(feed_id : [u8; 32])]
pub struct InitPythPullPriceFeed<'info> {
Expand Down
13 changes: 13 additions & 0 deletions programs/drift/src/instructions/keeper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::math::spot_withdraw::validate_spot_market_vault_amount;
use crate::optional_accounts::update_prelaunch_oracle;
use crate::state::fill_mode::FillMode;
use crate::state::fulfillment_params::drift::MatchFulfillmentParams;
use crate::state::fulfillment_params::openbook_v2::OpenbookV2FulfillmentParams;
use crate::state::fulfillment_params::phoenix::PhoenixFulfillmentParams;
use crate::state::fulfillment_params::serum::SerumFulfillmentParams;
use crate::state::insurance_fund_stake::InsuranceFundStake;
Expand Down Expand Up @@ -147,6 +148,7 @@ pub enum SpotFulfillmentType {
SerumV3,
Match,
PhoenixV1,
OpenbookV2,
}

#[access_control(
Expand Down Expand Up @@ -233,6 +235,17 @@ fn fill_spot_order<'c: 'info, 'info>(
&quote_market,
)?)
}
SpotFulfillmentType::OpenbookV2 => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(OpenbookV2FulfillmentParams::new(
remaining_accounts_iter,
&ctx.accounts.state,
&base_market,
&quote_market,
clock.unix_timestamp,
)?)
}
SpotFulfillmentType::Match => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Expand Down
23 changes: 23 additions & 0 deletions programs/drift/src/instructions/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ use crate::state::events::{
};
use crate::state::fill_mode::FillMode;
use crate::state::fulfillment_params::drift::MatchFulfillmentParams;
use crate::state::fulfillment_params::openbook_v2::OpenbookV2FulfillmentParams;
use crate::state::fulfillment_params::phoenix::PhoenixFulfillmentParams;
use crate::state::fulfillment_params::serum::SerumFulfillmentParams;
use crate::state::oracle::StrictOraclePrice;
Expand Down Expand Up @@ -1443,6 +1444,17 @@ pub fn handle_place_and_take_spot_order<'c: 'info, 'info>(
&quote_market,
)?)
}
SpotFulfillmentType::OpenbookV2 => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(OpenbookV2FulfillmentParams::new(
remaining_accounts_iter,
&ctx.accounts.state,
&base_market,
&quote_market,
clock.unix_timestamp,
)?)
}
SpotFulfillmentType::Match => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Expand Down Expand Up @@ -1573,6 +1585,17 @@ pub fn handle_place_and_make_spot_order<'c: 'info, 'info>(
&quote_market,
)?)
}
SpotFulfillmentType::OpenbookV2 => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(OpenbookV2FulfillmentParams::new(
remaining_accounts_iter,
&ctx.accounts.state,
&base_market,
&quote_market,
clock.unix_timestamp,
)?)
}
SpotFulfillmentType::Match => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Expand Down
13 changes: 13 additions & 0 deletions programs/drift/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,19 @@ pub mod drift {
handle_update_serum_fulfillment_config_status(ctx, status)
}

pub fn initialize_openbook_v2_fulfillment_config(
ctx: Context<InitializeOpenbookV2FulfillmentConfig>,
market_index: u16,
) -> Result<()> {
handle_initialize_openbook_v2_fulfillment_config(ctx, market_index)
}

pub fn openbook_v2_fulfillment_config_status(
ctx: Context<UpdateOpenbookV2FulfillmentConfig>,
status: SpotFulfillmentConfigStatus,
) -> Result<()> {
handle_update_openbook_v2_fulfillment_config_status(ctx, status)
}
pub fn initialize_phoenix_fulfillment_config(
ctx: Context<InitializePhoenixFulfillmentConfig>,
market_index: u16,
Expand Down
1 change: 1 addition & 0 deletions programs/drift/src/state/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@ pub enum OrderActionExplanation {
OrderFilledWithAMMJitLPSplit,
OrderFilledWithLPJit,
DeriskLp,
OrderFilledWithOpenbookV2,
}

#[event]
Expand Down
1 change: 1 addition & 0 deletions programs/drift/src/state/fulfillment_params/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod drift;
pub mod openbook_v2;
pub mod phoenix;
pub mod serum;
Loading

0 comments on commit 16b5660

Please sign in to comment.