Skip to main content

riptide_amm_math/
mod.rs

1#![allow(
2    unexpected_cfgs,
3    unused_attributes,
4    clippy::needless_range_loop,
5    clippy::too_many_arguments
6)]
7#![cfg_attr(all(not(feature = "wasm"), not(test)), no_std)]
8#![cfg_attr(feature = "wasm", allow(non_snake_case))]
9#![cfg_attr(target_os = "solana", feature(cfg_boolean_literals))]
10
11mod error;
12mod guards;
13mod oracle;
14mod price;
15mod quote;
16mod token;
17mod transfer_fee;
18
19pub use error::*;
20pub use guards::*;
21pub use oracle::*;
22pub use price::*;
23pub use quote::*;
24pub use token::*;
25pub use transfer_fee::*;
26
27#[cfg(feature = "wasm")]
28use serde::Serializer;
29
30// Serialize a u64 as a u128. This is so that we can use u64 value in rust
31// but serialize as a bigint in wasm.
32#[cfg(feature = "wasm")]
33pub fn u64_serialize<S>(value: &u64, serializer: S) -> Result<S::Ok, S::Error>
34where
35    S: Serializer,
36{
37    serializer.serialize_u128(*value as u128)
38}
39
40// While `wasm_expose` doesn't automatically convert rust `u128` to js `bigint`, we have
41// to proxy it through an opaque type that we define here. This is a workaround until
42// `wasm_bindgen` supports `u128` abi conversion natively.
43
44#[cfg(not(feature = "wasm"))]
45pub type U128 = u128;
46
47#[cfg(feature = "wasm")]
48use core::fmt::{Debug, Formatter};
49
50#[cfg(feature = "wasm")]
51use ethnum::U256;
52
53#[cfg(feature = "wasm")]
54use wasm_bindgen::prelude::*;
55
56#[cfg(feature = "wasm")]
57#[wasm_bindgen]
58extern "C" {
59    #[wasm_bindgen(typescript_type = "bigint")]
60    #[derive(PartialEq)]
61    pub type U128;
62}
63
64#[cfg(feature = "wasm")]
65impl Debug for U128 {
66    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
67        write!(f, "{:?}", JsValue::from(self))
68    }
69}
70
71#[cfg(feature = "wasm")]
72impl From<U128> for u128 {
73    fn from(value: U128) -> u128 {
74        JsValue::from(value)
75            .try_into()
76            .expect("Number too large to fit in u128")
77    }
78}
79
80#[cfg(feature = "wasm")]
81impl From<U128> for U256 {
82    fn from(value: U128) -> U256 {
83        let u_128: u128 = value.into();
84        <U256>::from(u_128)
85    }
86}
87
88#[cfg(feature = "wasm")]
89impl From<u128> for U128 {
90    fn from(value: u128) -> U128 {
91        JsValue::from(value).unchecked_into()
92    }
93}
94
95#[cfg(feature = "wasm")]
96impl TryFrom<U256> for U128 {
97    type Error = core::num::TryFromIntError;
98
99    fn try_from(value: U256) -> Result<Self, Self::Error> {
100        let u_128: u128 = value.try_into()?;
101        Ok(U128::from(u_128))
102    }
103}