From e225f86adb155431117ae4e9ba58dda3f7aea451 Mon Sep 17 00:00:00 2001 From: wiseaidev Date: Thu, 13 Jun 2024 16:21:11 +0300 Subject: [PATCH] feat: add handy utils functions --- programs/openbook-v2/src/state/market.rs | 19 +++++++++++++++++++ .../src/state/orderbook/bookside.rs | 9 +++++++++ 2 files changed, 28 insertions(+) diff --git a/programs/openbook-v2/src/state/market.rs b/programs/openbook-v2/src/state/market.rs index 03b6bc3bf..0ec1e4147 100644 --- a/programs/openbook-v2/src/state/market.rs +++ b/programs/openbook-v2/src/state/market.rs @@ -197,6 +197,7 @@ impl Market { pub fn max_quote_lots(&self) -> i64 { i64::MAX / self.quote_lot_size } +a pub fn max_base_lots_from_lamports(&self, lamports: u64) -> i64 { let base_lots = lamports / self.base_lot_size as u64; @@ -218,6 +219,24 @@ impl Market { / I80F48::from_num(self.base_lot_size) } + /// Convert the quantity from quote lots to native quantity (e.g. 5 SOL, 0.3 USDC, etc) + pub fn quote_lot_to_native_quantity(&self, quote_lots: i64) -> f64 { + let quote_lot_size = self.quote_lot_size as f64; + let quote_decimals = self.quote_decimals as u32; + let quote_units = quote_lots as f64 * quote_lot_size; + let quantity = quote_units / 10_i64.pow(quote_decimals) as f64; + quantity + } + + /// Convert the quantity from base lots to native quantity (e.g. 5 SOL, 0.3 USDC, etc) + pub fn base_lot_to_native_quantity(&self, base_lots: i64) -> f64 { + let base_lot_size = self.base_lot_size as f64; + let base_decimals = self.base_decimals as u32; + let base_units = base_lots as f64 * base_lot_size; + let quantity = base_units / 10_i64.pow(base_decimals) as f64; + quantity + } + pub fn native_price_to_lot(&self, price: I80F48) -> Result { price .checked_mul(I80F48::from_num(self.base_lot_size)) diff --git a/programs/openbook-v2/src/state/orderbook/bookside.rs b/programs/openbook-v2/src/state/orderbook/bookside.rs index 41fca4f01..ccb6de00c 100644 --- a/programs/openbook-v2/src/state/orderbook/bookside.rs +++ b/programs/openbook-v2/src/state/orderbook/bookside.rs @@ -182,6 +182,15 @@ impl BookSide { ) } + /// Return the quantity of the order closest to the spread + pub fn best_quantity(&self, now_ts: u64, oracle_price_lots: Option) -> Option { + Some( + self.iter_valid(now_ts, oracle_price_lots) + .next()? + .quantity, + ) + } + /// Walk up the book `quantity` units and return the price at that level. If `quantity` units /// not on book, return None pub fn impact_price(&self, quantity: i64, now_ts: u64, oracle_price_lots: i64) -> Option {