Skip to content

Instantly share code, notes, and snippets.

@Henry-E
Created July 12, 2021 14:43
Show Gist options
  • Save Henry-E/6d252c65fdff9979d9d991fe6820780d to your computer and use it in GitHub Desktop.
Save Henry-E/6d252c65fdff9979d9d991fe6820780d to your computer and use it in GitHub Desktop.
Serum New Order CPI
const BASE: u128 = 1_000_000
// Assumes limit price and coin amount have 6 decimals and the u64 int contains all decimal places
fn new_order(
&self,
side: Side,
limit_price: u64,
coin_amount: u64,
order_type: OrderType,
) -> ProgramResult {
let (price_lots, coin_lots, pc_lot_size) = {
let market = MarketState::load(&self.market.market, &dex::ID)?;
(limit_price.checked_mul(market.coin_lot_size).unwrap()
.checked_div(market.pc_lot_size).unwrap()
.checked_div(BASE as u64).unwrap(),
coin_amount.checked_div(market.coin_lot_size).unwrap(),
market.pc_lot_size)
};
let max_native_pc_qty = price_lots.checked_mul(coin_lots).unwrap().checked_mul(pc_lot_size).unwrap();
// Client order id is only used for cancels. Not used here so hardcode.
let client_order_id = 0;
// Limit is the dex's custom compute budge parameter, setting an upper
// bound on the number of matching cycles the program can perform
// before giving up and posting the remaining unmatched order.
let limit = 65535;
let short_name = self.prediction_market_account.short_name.as_ref().clone();
let seeds = &[
short_name.trim_ascii_whitespace(),
&[self.prediction_market_account.nonce],
];
let signer = &[&seeds[..]];
let dex_accs = dex::NewOrderV3 {
market: self.market.market.clone(),
open_orders: self.market.open_orders.clone(),
request_queue: self.market.request_queue.clone(),
event_queue: self.market.event_queue.clone(),
market_bids: self.market.bids.clone(),
market_asks: self.market.asks.clone(),
order_payer_token_account: self.market.order_payer_token_account.clone(),
open_orders_authority: self.prediction_market_account.to_account_info(),
coin_vault: self.market.coin_vault.clone(),
pc_vault: self.market.pc_vault.clone(),
token_program: self.token_program.clone(),
rent: self.rent.clone(),
};
let ctx = CpiContext::new_with_signer(self.dex_program.clone(), dex_accs, signer);
// if let Some(referral) = referral {
// ctx = ctx.with_remaining_accounts(vec![referral]);
// }
dex::new_order_v3(
ctx,
side.into(),
NonZeroU64::new(price_lots).unwrap(),
NonZeroU64::new(coin_lots).unwrap(),
NonZeroU64::new(max_native_pc_qty).unwrap(),
SelfTradeBehavior::DecrementTake,
order_type,
client_order_id,
limit,
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment