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