Skip to main content

riptide_amm_math/
mod.rs

1#![allow(unexpected_cfgs, unused_attributes, clippy::needless_range_loop)]
2#![cfg_attr(all(not(feature = "wasm"), not(test)), no_std)]
3#![cfg_attr(feature = "wasm", allow(non_snake_case))]
4#![cfg_attr(target_os = "solana", feature(cfg_boolean_literals))]
5
6mod error;
7mod oracle;
8mod price;
9mod quote;
10mod token;
11mod transfer_fee;
12
13pub use error::*;
14pub use oracle::*;
15pub use price::*;
16pub use quote::*;
17pub use token::*;
18pub use transfer_fee::*;
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    #[derive(PartialEq)]
54    pub type U128;
55}
56
57#[cfg(feature = "wasm")]
58impl Debug for U128 {
59    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
60        write!(f, "{:?}", JsValue::from(self))
61    }
62}
63
64#[cfg(feature = "wasm")]
65impl From<U128> for u128 {
66    fn from(value: U128) -> u128 {
67        JsValue::from(value)
68            .try_into()
69            .expect("Number too large to fit in u128")
70    }
71}
72
73#[cfg(feature = "wasm")]
74impl From<U128> for U256 {
75    fn from(value: U128) -> U256 {
76        let u_128: u128 = value.into();
77        <U256>::from(u_128)
78    }
79}
80
81#[cfg(feature = "wasm")]
82impl From<u128> for U128 {
83    fn from(value: u128) -> U128 {
84        JsValue::from(value).unchecked_into()
85    }
86}
87
88#[cfg(feature = "wasm")]
89impl TryFrom<U256> for U128 {
90    type Error = core::num::TryFromIntError;
91
92    fn try_from(value: U256) -> Result<Self, Self::Error> {
93        let u_128: u128 = value.try_into()?;
94        Ok(U128::from(u_128))
95    }
96}