lamarge 0.6.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! Token amounts in base units.

use std::{fmt, str::FromStr};

use alloy_primitives::{I256, Sign, U256};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};

use super::VenueId;

/// The most digits a wire amount has: `2^256 - 1` has 78.
const MAX_DIGITS: usize = 78;

/// A token amount in base units (`"1000000"` is 1 USDC).
///
/// On the wire it is a decimal string (`^[0-9]{1,78}$`), never hex. Which token's units depends
/// on the venue: see [`Amount::parse_venue`] and [`VenueId::decimals`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Amount(U256);

impl Amount {
    /// Zero.
    pub const ZERO: Self = Self(U256::ZERO);

    /// An amount of `units` base units.
    pub const fn new(units: U256) -> Self {
        Self(units)
    }

    /// The base units.
    pub const fn get(self) -> U256 {
        self.0
    }

    /// Parses a decimal token amount (`"12.5"`) in `venue`'s token decimals.
    ///
    /// Fails for a venue this SDK version does not know, or a text [`Amount::parse_units`]
    /// refuses.
    pub fn parse_venue(venue: &VenueId, decimal: &str) -> Result<Self, ParseAmountError> {
        let decimals = venue.decimals().ok_or(ParseAmountError(ParseAmountKind::UnknownVenue))?;
        Self::parse_units(decimal, decimals)
    }

    /// Formats the amount as a decimal token amount in `venue`'s token decimals; `None` for a
    /// venue this SDK version does not know.
    pub fn format_venue(&self, venue: &VenueId) -> Option<String> {
        venue.decimals().map(|decimals| self.format_units(decimals))
    }

    /// Parses a decimal token amount (`"12.5"`) with `decimals` decimals, exactly.
    ///
    /// Accepts `digits` or `digits.digits`; refuses more fractional digits than `decimals` and
    /// values of `2^256` base units or more.
    pub fn parse_units(decimal: &str, decimals: u8) -> Result<Self, ParseAmountError> {
        let (whole, fraction) = match decimal.split_once('.') {
            Some((whole, fraction)) => (whole, fraction),
            None => (decimal, ""),
        };
        let digits = |text: &str| !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit());
        if !digits(whole) || (decimal.contains('.') && !digits(fraction)) {
            return Err(ParseAmountError(ParseAmountKind::Invalid));
        }
        let padding = usize::from(decimals)
            .checked_sub(fraction.len())
            .ok_or(ParseAmountError(ParseAmountKind::TooManyDecimals))?;
        let units = whole
            .bytes()
            .chain(fraction.bytes())
            .chain(std::iter::repeat_n(b'0', padding))
            .try_fold(U256::ZERO, |units, digit| {
                units.checked_mul(U256::from(10u8))?.checked_add(U256::from(digit - b'0'))
            })
            .ok_or(ParseAmountError(ParseAmountKind::Overflow))?;
        Ok(Self(units))
    }

    /// Formats the amount as a decimal token amount with `decimals` decimals, without trailing
    /// fractional zeros (`1500000` with 6 decimals is `"1.5"`).
    pub fn format_units(&self, decimals: u8) -> String {
        let digits = self.0.to_string();
        let decimals = usize::from(decimals);
        if decimals == 0 {
            return digits;
        }
        let padded = format!("{digits:0>width$}", width = decimals + 1);
        let (whole, fraction) = padded.split_at(padded.len() - decimals);
        let fraction = fraction.trim_end_matches('0');
        if fraction.is_empty() { whole.to_owned() } else { format!("{whole}.{fraction}") }
    }

    /// `self + other`, or `None` on overflow.
    pub fn checked_add(self, other: Self) -> Option<Self> {
        self.0.checked_add(other.0).map(Self)
    }

    /// `self - other`, or `None` below zero.
    pub fn checked_sub(self, other: Self) -> Option<Self> {
        self.0.checked_sub(other.0).map(Self)
    }
}

impl From<u64> for Amount {
    fn from(units: u64) -> Self {
        Self(U256::from(units))
    }
}

impl From<u128> for Amount {
    fn from(units: u128) -> Self {
        Self(U256::from(units))
    }
}

impl FromStr for Amount {
    type Err = ParseAmountError;

    /// Parses base units as the wire writes them: 1 to 78 decimal digits.
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        if text.is_empty() || text.len() > MAX_DIGITS || !text.bytes().all(|b| b.is_ascii_digit()) {
            return Err(ParseAmountError(ParseAmountKind::Invalid));
        }
        Self::parse_units(text, 0)
    }
}

impl fmt::Display for Amount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl Serialize for Amount {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for Amount {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer)?.parse().map_err(de::Error::custom)
    }
}

/// A signed token amount in base units (`"-20000"`), for balances that can be negative.
///
/// On the wire it is a decimal string (`^-?[0-9]{1,78}$`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct SignedAmount(I256);

impl SignedAmount {
    /// Zero.
    pub const ZERO: Self = Self(I256::ZERO);

    /// An amount of `units` base units.
    pub const fn new(units: I256) -> Self {
        Self(units)
    }

    /// The base units.
    pub const fn get(self) -> I256 {
        self.0
    }

    /// Formats the amount as a signed decimal token amount with `decimals` decimals, without
    /// trailing fractional zeros (`-1500000` with 6 decimals is `"-1.5"`).
    pub fn format_units(&self, decimals: u8) -> String {
        let magnitude = Amount(self.0.unsigned_abs()).format_units(decimals);
        if self.0.is_negative() { format!("-{magnitude}") } else { magnitude }
    }
}

impl FromStr for SignedAmount {
    type Err = ParseAmountError;

    /// Parses base units as the wire writes them: an optional `-`, then 1 to 78 decimal digits.
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let (sign, digits) = match text.strip_prefix('-') {
            Some(digits) => (Sign::Negative, digits),
            None => (Sign::Positive, text),
        };
        let magnitude: Amount = digits.parse()?;
        I256::checked_from_sign_and_abs(sign, magnitude.0)
            .map(Self)
            .ok_or(ParseAmountError(ParseAmountKind::Overflow))
    }
}

impl fmt::Display for SignedAmount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl Serialize for SignedAmount {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for SignedAmount {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer)?.parse().map_err(de::Error::custom)
    }
}

/// Why a text is not an amount.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseAmountError(ParseAmountKind);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParseAmountKind {
    Invalid,
    TooManyDecimals,
    Overflow,
    UnknownVenue,
}

impl fmt::Display for ParseAmountError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self.0 {
            ParseAmountKind::Invalid => "not a decimal number",
            ParseAmountKind::TooManyDecimals => "more decimals than the token has",
            ParseAmountKind::Overflow => "2^256 base units or more",
            ParseAmountKind::UnknownVenue => "a venue this SDK version does not know",
        })
    }
}

impl std::error::Error for ParseAmountError {}

#[cfg(test)]
mod tests;