equanetwork-math 0.1.0

The Equa Network program math library
Documentation
#![allow(
    unexpected_cfgs,
    unused_attributes,
    clippy::needless_range_loop,
    // `U128` is `u128` without `wasm`; `.into()` keeps wasm builds working.
    clippy::useless_conversion
)]
#![cfg_attr(test, allow(clippy::too_many_arguments))]
#![cfg_attr(target_os = "solana", no_std)]
#![cfg_attr(feature = "wasm", allow(non_snake_case))]
#![cfg_attr(target_os = "solana", feature(cfg_boolean_literals))]

mod bitmap;
mod error;
mod fee;
mod oracle;
mod price;
mod skew;
mod swap;
mod token;

pub use bitmap::*;
pub use error::*;
pub use fee::*;
pub use oracle::*;
pub use price::*;
pub use skew::*;
pub use swap::*;
pub use token::*;

#[cfg(feature = "wasm")]
use equanetwork_macros::wasm_expose;

#[cfg_attr(feature = "wasm", wasm_expose)]
pub const BPS_DENOMINATOR: i16 = 10000;

#[cfg_attr(feature = "wasm", wasm_expose)]
pub const PER_M_DENOMINATOR: i32 = 1_000_000;

#[cfg(feature = "wasm")]
use serde::Serializer;

#[cfg(feature = "wasm")]
pub fn u64_serialize<S>(value: &u64, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_u128(*value as u128)
}

#[cfg(not(feature = "wasm"))]
pub type U128 = u128;

#[cfg(feature = "wasm")]
use core::fmt::{Debug, Formatter};

#[cfg(feature = "wasm")]
use ethnum::U256;

#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;

#[cfg(feature = "wasm")]
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(typescript_type = "bigint")]
    #[derive(PartialEq)]
    pub type U128;
}

#[cfg(feature = "wasm")]
impl Debug for U128 {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:?}", JsValue::from(self))
    }
}

#[cfg(feature = "wasm")]
impl From<U128> for u128 {
    fn from(value: U128) -> u128 {
        JsValue::from(value)
            .try_into()
            .expect("Number too large to fit in u128")
    }
}

#[cfg(feature = "wasm")]
impl From<U128> for U256 {
    fn from(value: U128) -> U256 {
        let u_128: u128 = value.into();
        <U256>::from(u_128)
    }
}

#[cfg(feature = "wasm")]
impl From<u128> for U128 {
    fn from(value: u128) -> U128 {
        JsValue::from(value).unchecked_into()
    }
}

#[cfg(feature = "wasm")]
impl TryFrom<U256> for U128 {
    type Error = core::num::TryFromIntError;

    fn try_from(value: U256) -> Result<Self, Self::Error> {
        let u_128: u128 = value.try_into()?;
        Ok(U128::from(u_128))
    }
}