use std::{fmt, str::FromStr};
use alloy_primitives::{I256, Sign, U256};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use super::VenueId;
const MAX_DIGITS: usize = 78;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Amount(U256);
impl Amount {
pub const ZERO: Self = Self(U256::ZERO);
pub const fn new(units: U256) -> Self {
Self(units)
}
pub const fn get(self) -> U256 {
self.0
}
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)
}
pub fn format_venue(&self, venue: &VenueId) -> Option<String> {
venue.decimals().map(|decimals| self.format_units(decimals))
}
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))
}
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}") }
}
pub fn checked_add(self, other: Self) -> Option<Self> {
self.0.checked_add(other.0).map(Self)
}
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;
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)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct SignedAmount(I256);
impl SignedAmount {
pub const ZERO: Self = Self(I256::ZERO);
pub const fn new(units: I256) -> Self {
Self(units)
}
pub const fn get(self) -> I256 {
self.0
}
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;
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)
}
}
#[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;