Skip to content

Commit

Permalink
create update and quote fn
Browse files Browse the repository at this point in the history
  • Loading branch information
binyebarwe committed Jul 11, 2023
1 parent 6aceb78 commit d6e1958
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 39 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

11 changes: 6 additions & 5 deletions lib/client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,25 @@ version = "0.3.0"
doctest = false

[dependencies]
anchor-client = { workspace = true }
anchor-lang = { workspace = true }
anchor-spl = { workspace = true }
anchor-client = {workspace = true}
anchor-lang = {workspace = true}
anchor-spl = {workspace = true}
anyhow = "1.0"
async-channel = "1.6"
async-once-cell = {version = "0.4.2", features = ["unpin"]}
async-trait = "0.1.52"
base64 = "0.13.0"
bincode = "1.3.3"
fixed = { workspace = true, features = ["serde", "borsh"] }
fixed = {workspace = true, features = ["serde", "borsh"]}
futures = "0.3.25"
itertools = "0.10.3"
jsonrpc-core = "18.0.0"
jsonrpc-core-client = {version = "18.0.0", features = ["ws", "http", "tls"]}
log = "0.4"
openbook-v2 = {path = "../../programs/openbook-v2", features = ["client"]}
pyth-sdk-solana = { workspace = true }
pyth-sdk-solana = {workspace = true}
reqwest = "0.11.11"
rust_decimal = "1.26.1"
serde = "1.0.141"
serde_json = "1.0.82"
shellexpand = "2.1.0"
Expand Down
12 changes: 2 additions & 10 deletions lib/client/src/gpa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,7 @@ pub async fn fetch_market_by_index(
) -> anyhow::Result<Vec<(Pubkey, Market)>> {
let config = RpcProgramAccountsConfig {
filters: Some(vec![
RpcFilterType::Memcmp(Memcmp::new_raw_bytes(
0,
Market::discriminator().to_vec(),
)),
RpcFilterType::Memcmp(Memcmp::new_raw_bytes(0, Market::discriminator().to_vec())),
RpcFilterType::Memcmp(Memcmp::new_raw_bytes(4, index.to_le_bytes().to_vec())),
]),
account_config: RpcAccountInfoConfig {
Expand All @@ -97,11 +94,6 @@ pub async fn fetch_market_by_index(
rpc.get_program_accounts_with_config(&program, config)
.await?
.into_iter()
.map(|(key, account)| {
Ok((
key,
Market::try_deserialize(&mut (&account.data as &[u8]))?,
))
})
.map(|(key, account)| Ok((key, Market::try_deserialize(&mut (&account.data as &[u8]))?)))
.collect()
}
79 changes: 55 additions & 24 deletions lib/client/src/jup.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,28 @@
use anchor_lang::AccountDeserialize;
use anchor_lang::__private::bytemuck::Zeroable;
use anyhow::Result;
use openbook_v2::state::{SelfTradeBehavior::DecrementTake, Order, OrderWithAmounts, Orderbook, PlaceOrderType, Side, EventQueue, Market};
use fixed::types::I80F48;
use openbook_v2::state::{BookSide, OrderParams};
use openbook_v2::state::{
EventQueue, Market, Order, OrderWithAmounts, Orderbook, SelfTradeBehavior::DecrementTake, Side,
};

use rust_decimal::Decimal;
/// An abstraction in order to share reserve mints and necessary data
use solana_sdk::{account::Account, instruction::AccountMeta, pubkey::Pubkey};
use solana_sdk::{account::Account, pubkey::Pubkey};
use std::cell::RefCell;
use std::collections::HashMap;
use std::str;

#[derive(Clone)]
pub struct KeyedAccount {
pub key: Pubkey,
pub account: Account,
}

pub struct QuoteParams {
pub max_base_lots: u64,
pub max_quote_lots_including_fees: u64,
pub max_base_lots: i64,
pub max_quote_lots_including_fees: i64,
pub input_mint: Pubkey,
pub output_mint: Pubkey,
}
Expand Down Expand Up @@ -38,11 +52,14 @@ pub trait Amm {
// Picks data necessary to update it's internal state
fn update(&mut self, accounts_map: &HashMap<Pubkey, Vec<u8>>) -> Result<()>;
// Compute the quote from internal state
fn quote(&self, quote_params: &QuoteParams) -> Result<Quote>;
fn quote(&mut self, quote_params: &QuoteParams) -> Result<Quote>;
}

pub struct OpenBookMarket {
market: Market,
event_queue: EventQueue,
bids: BookSide,
asks: BookSide,
key: Pubkey,
label: String,
related_accounts: [Pubkey; 6],
Expand All @@ -52,11 +69,15 @@ pub struct OpenBookMarket {
}

impl OpenBookMarket {
pub fn new_from_market(key: Pubkey, market: Market) -> OpenBookMarket {
OpenBookMarket {
pub fn from_keyed_account(keyed_account: &KeyedAccount) -> Result<Self> {
let market = Market::try_deserialize(&mut (&keyed_account.account.data as &[u8]))?;

Ok(OpenBookMarket {
market,
key,
label: str::from_utf8(&market.name).unwrap_or_else(|d| "").to_string(),
key: keyed_account.key,
label: str::from_utf8(&market.name)
.unwrap_or_else(|d| "")
.to_string(),
related_accounts: [
market.bids,
market.asks,
Expand All @@ -68,7 +89,10 @@ impl OpenBookMarket {
reserve_mints: [market.base_mint, market.quote_mint],
reserves: [0, 0],
program_id: openbook_v2::ID,
}
event_queue: EventQueue::zeroed(),
bids: BookSide::zeroed(),
asks: BookSide::zeroed(),
})
}
}

Expand All @@ -90,14 +114,19 @@ impl Amm for OpenBookMarket {
}

fn update(&mut self, accounts_map: &HashMap<Pubkey, Vec<u8>>) -> Result<()> {
let bids_data: &Vec<u8> = accounts_map.get(&self.market.bids).unwrap();
self.bids = BookSide::try_deserialize(&mut bids_data.as_slice()).unwrap();

let asks_data = accounts_map.get(&self.market.asks).unwrap();
self.asks = BookSide::try_deserialize(&mut asks_data.as_slice()).unwrap();

let event_queue_data = accounts_map.get(&self.market.event_queue).unwrap();
self.event_queue = EventQueue::try_deserialize(&mut event_queue_data.as_slice()).unwrap();

Ok(())
}

fn quote(&self, quote_params: &QuoteParams) -> Result<Quote> {
let mut book = Orderbook {
bids: self.market.bids,
asks: self.market.asks,
};
fn quote(&mut self, quote_params: &QuoteParams) -> Result<Quote> {
let side = if quote_params.input_mint == self.market.quote_mint {
Side::Bid
} else {
Expand All @@ -111,25 +140,27 @@ impl Amm for OpenBookMarket {
client_order_id: 0,
time_in_force: 0,
self_trade_behavior: DecrementTake,
params: match order_type {
PlaceOrderType::Market => OrderParams::Market,
_ => unreachable!(),
},
params: OrderParams::Market,
};
let owner = &Pubkey::default();
let mut event_queue = &EventQueue{header: , nodes: , reserved:};
event_queue.init();

let bids_ref = RefCell::new(self.bids);
let asks_ref = RefCell::new(self.asks);
let mut book = Orderbook {
bids: bids_ref.borrow_mut(),
asks: asks_ref.borrow_mut(),
};
let order_amounts: OrderWithAmounts = book.new_order(
order,
&mut self.market,
event_queue,
0,
&mut self.event_queue,
I80F48::from_num(0),
None,
owner,
0,
8,
None,
[],
&[],
)?;
let out_amount = if side == Side::Bid {
order_amounts.total_base_taken_native
Expand Down

0 comments on commit d6e1958

Please sign in to comment.