Skip to main content

riptide_amm_math/
mod.rs

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