Skip to main content

equanetwork_math/
mod.rs

1#![allow(
2    unexpected_cfgs,
3    unused_attributes,
4    clippy::needless_range_loop,
5    // `U128` is `u128` without `wasm`; `.into()` keeps wasm builds working.
6    clippy::useless_conversion
7)]
8#![cfg_attr(test, allow(clippy::too_many_arguments))]
9#![cfg_attr(target_os = "solana", no_std)]
10#![cfg_attr(feature = "wasm", allow(non_snake_case))]
11#![cfg_attr(target_os = "solana", feature(cfg_boolean_literals))]
12
13mod bitmap;
14mod error;
15mod fee;
16mod oracle;
17mod price;
18mod skew;
19mod swap;
20mod token;
21
22pub use bitmap::*;
23pub use error::*;
24pub use fee::*;
25pub use oracle::*;
26pub use price::*;
27pub use skew::*;
28pub use swap::*;
29pub use token::*;
30
31#[cfg(feature = "wasm")]
32use equanetwork_macros::wasm_expose;
33
34#[cfg_attr(feature = "wasm", wasm_expose)]
35pub const BPS_DENOMINATOR: i16 = 10000;
36
37#[cfg_attr(feature = "wasm", wasm_expose)]
38pub const PER_M_DENOMINATOR: i32 = 1_000_000;
39
40#[cfg(feature = "wasm")]
41use serde::Serializer;
42
43#[cfg(feature = "wasm")]
44pub fn u64_serialize<S>(value: &u64, serializer: S) -> Result<S::Ok, S::Error>
45where
46    S: Serializer,
47{
48    serializer.serialize_u128(*value as u128)
49}
50
51#[cfg(not(feature = "wasm"))]
52pub type U128 = u128;
53
54#[cfg(feature = "wasm")]
55use core::fmt::{Debug, Formatter};
56
57#[cfg(feature = "wasm")]
58use ethnum::U256;
59
60#[cfg(feature = "wasm")]
61use wasm_bindgen::prelude::*;
62
63#[cfg(feature = "wasm")]
64#[wasm_bindgen]
65extern "C" {
66    #[wasm_bindgen(typescript_type = "bigint")]
67    #[derive(PartialEq)]
68    pub type U128;
69}
70
71#[cfg(feature = "wasm")]
72impl Debug for U128 {
73    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
74        write!(f, "{:?}", JsValue::from(self))
75    }
76}
77
78#[cfg(feature = "wasm")]
79impl From<U128> for u128 {
80    fn from(value: U128) -> u128 {
81        JsValue::from(value)
82            .try_into()
83            .expect("Number too large to fit in u128")
84    }
85}
86
87#[cfg(feature = "wasm")]
88impl From<U128> for U256 {
89    fn from(value: U128) -> U256 {
90        let u_128: u128 = value.into();
91        <U256>::from(u_128)
92    }
93}
94
95#[cfg(feature = "wasm")]
96impl From<u128> for U128 {
97    fn from(value: u128) -> U128 {
98        JsValue::from(value).unchecked_into()
99    }
100}
101
102#[cfg(feature = "wasm")]
103impl TryFrom<U256> for U128 {
104    type Error = core::num::TryFromIntError;
105
106    fn try_from(value: U256) -> Result<Self, Self::Error> {
107        let u_128: u128 = value.try_into()?;
108        Ok(U128::from(u_128))
109    }
110}