Skip to main content

riptide_amm/math/
quote.rs

1use super::error::{CoreError, INVALID_ORACLE_DATA};
2
3use super::oracle::OracleData;
4
5use borsh::BorshDeserialize;
6
7use riptide_amm_macros::alias;
8#[cfg(feature = "wasm")]
9use riptide_amm_macros::wasm_expose;
10
11#[derive(Debug, Clone, Copy, Eq, PartialEq)]
12#[cfg_attr(feature = "wasm", wasm_expose)]
13pub enum QuoteType {
14    TokenAExactIn,
15    TokenAExactOut,
16    TokenBExactIn,
17    TokenBExactOut,
18}
19
20impl QuoteType {
21    pub(crate) fn new(amount_is_token_a: bool, amount_is_input: bool) -> Self {
22        match (amount_is_token_a, amount_is_input) {
23            (true, true) => QuoteType::TokenAExactIn,
24            (true, false) => QuoteType::TokenAExactOut,
25            (false, true) => QuoteType::TokenBExactIn,
26            (false, false) => QuoteType::TokenBExactOut,
27        }
28    }
29
30    pub fn exact_in(&self) -> bool {
31        matches!(self, QuoteType::TokenAExactIn | QuoteType::TokenBExactIn)
32    }
33
34    pub fn exact_out(&self) -> bool {
35        matches!(self, QuoteType::TokenAExactOut | QuoteType::TokenBExactOut)
36    }
37
38    #[alias(output_is_token_b, a_to_b)]
39    pub fn input_is_token_a(&self) -> bool {
40        matches!(self, QuoteType::TokenAExactIn | QuoteType::TokenBExactOut)
41    }
42
43    #[alias(output_is_token_a, b_to_a)]
44    pub fn input_is_token_b(&self) -> bool {
45        matches!(self, QuoteType::TokenBExactIn | QuoteType::TokenAExactOut)
46    }
47}
48
49#[derive(Debug, Clone, Copy, Eq, PartialEq)]
50#[cfg_attr(feature = "wasm", wasm_expose)]
51pub struct Quote {
52    pub amount_in: u64,
53    pub amount_out: u64,
54    pub quote_type: QuoteType,
55}
56
57#[cfg_attr(feature = "wasm", wasm_expose)]
58pub fn quote_exact_in(
59    amount: u64,
60    amount_is_token_a: bool,
61    oracle_data: &[u8],
62    reserves_a: u64,
63    reserves_b: u64,
64) -> Result<Quote, CoreError> {
65    let mut oracle_data = oracle_data;
66    let oracle_data = OracleData::deserialize(&mut oracle_data).map_err(|_| INVALID_ORACLE_DATA)?;
67    oracle_data.swap(amount, amount_is_token_a, true, reserves_a, reserves_b)
68}
69
70#[cfg_attr(feature = "wasm", wasm_expose)]
71pub fn quote_exact_out(
72    amount: u64,
73    amount_is_token_a: bool,
74    oracle_data: &[u8],
75    reserves_a: u64,
76    reserves_b: u64,
77) -> Result<Quote, CoreError> {
78    let mut oracle_data = oracle_data;
79    let oracle_data = OracleData::deserialize(&mut oracle_data).map_err(|_| INVALID_ORACLE_DATA)?;
80    oracle_data.swap(amount, amount_is_token_a, false, reserves_a, reserves_b)
81}