use std::fmt;
use std::iter::Sum;
use std::num::ParseIntError;
use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use std::str::FromStr;
use ethnum::I256;
use serde::{Deserialize, Serialize};
use crate::error::{Result, WalletError};
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct TokenType(pub String);
impl TokenType {
#[inline]
#[must_use]
pub fn new(s: impl Into<String>) -> Self {
Self(s.into())
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for TokenType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl From<String> for TokenType {
#[inline]
fn from(s: String) -> Self {
Self(s)
}
}
impl From<&str> for TokenType {
#[inline]
fn from(s: &str) -> Self {
Self(s.to_owned())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct Amount(I256);
impl Amount {
pub const ZERO: Self = Self(I256::ZERO);
pub const ONE: Self = Self(I256::ONE);
pub const NEG_ONE: Self = Self(I256::MINUS_ONE);
pub const MAX: Self = Self(I256::MAX);
pub const MIN: Self = Self(I256::MIN);
#[inline]
#[must_use]
pub fn from_u128(value: u128) -> Self {
Self(I256::from(value))
}
#[inline]
#[must_use]
pub fn from_i128(value: i128) -> Self {
Self(I256::from(value))
}
#[inline]
pub fn try_to_u128(self) -> Option<u128> {
if self.0 < I256::ZERO {
return None;
}
let (hi, lo) = self.0.into_words();
if hi != 0 {
return None;
}
Some(u128::from_ne_bytes(lo.to_ne_bytes()))
}
#[inline]
pub fn try_to_i128(self) -> Option<i128> {
let min = I256::from(i128::MIN);
let max = I256::from(i128::MAX);
if self.0 < min || self.0 > max {
return None;
}
let (_hi, lo) = self.0.into_words();
Some(lo)
}
#[inline]
#[must_use]
pub fn is_positive(self) -> bool {
self.0 > I256::ZERO
}
#[inline]
#[must_use]
pub fn is_negative(self) -> bool {
self.0 < I256::ZERO
}
#[inline]
#[must_use]
pub fn is_zero(self) -> bool {
self.0 == I256::ZERO
}
#[inline]
#[must_use]
pub fn abs(self) -> Self {
Self(self.0.checked_abs().unwrap_or(I256::MAX))
}
#[inline]
#[must_use]
pub fn checked_add(self, rhs: Self) -> Option<Self> {
self.0.checked_add(rhs.0).map(Self)
}
#[inline]
#[must_use]
pub fn checked_sub(self, rhs: Self) -> Option<Self> {
self.0.checked_sub(rhs.0).map(Self)
}
#[inline]
#[must_use]
pub fn checked_mul(self, rhs: Self) -> Option<Self> {
self.0.checked_mul(rhs.0).map(Self)
}
#[inline]
#[must_use]
pub fn checked_neg(self) -> Option<Self> {
self.0.checked_neg().map(Self)
}
#[inline]
#[must_use]
pub const fn as_i256(self) -> I256 {
self.0
}
}
impl Add for Amount {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self {
Self(self.0 + rhs.0)
}
}
impl Sub for Amount {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self {
Self(self.0 - rhs.0)
}
}
impl Mul for Amount {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self {
Self(self.0 * rhs.0)
}
}
impl Neg for Amount {
type Output = Self;
#[inline]
fn neg(self) -> Self {
Self(-self.0)
}
}
impl AddAssign for Amount {
#[inline]
fn add_assign(&mut self, rhs: Self) {
self.0 += rhs.0;
}
}
impl SubAssign for Amount {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
self.0 -= rhs.0;
}
}
impl MulAssign for Amount {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
self.0 *= rhs.0;
}
}
impl Sum for Amount {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Self::ZERO, Add::add)
}
}
impl<'a> Sum<&'a Amount> for Amount {
fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
iter.copied().fold(Self::ZERO, Add::add)
}
}
impl From<i128> for Amount {
#[inline]
fn from(v: i128) -> Self {
Self::from_i128(v)
}
}
impl From<u128> for Amount {
#[inline]
fn from(v: u128) -> Self {
Self::from_u128(v)
}
}
impl From<i64> for Amount {
#[inline]
fn from(v: i64) -> Self {
Self(I256::from(v))
}
}
impl From<u64> for Amount {
#[inline]
fn from(v: u64) -> Self {
Self(I256::from(v))
}
}
impl From<i32> for Amount {
#[inline]
fn from(v: i32) -> Self {
Self(I256::from(v))
}
}
impl From<u32> for Amount {
#[inline]
fn from(v: u32) -> Self {
Self(I256::from(v))
}
}
impl From<i16> for Amount {
#[inline]
fn from(v: i16) -> Self {
Self(I256::from(v))
}
}
impl From<u16> for Amount {
#[inline]
fn from(v: u16) -> Self {
Self(I256::from(v))
}
}
impl From<i8> for Amount {
#[inline]
fn from(v: i8) -> Self {
Self(I256::from(v))
}
}
impl From<u8> for Amount {
#[inline]
fn from(v: u8) -> Self {
Self(I256::from(v))
}
}
impl TryFrom<Amount> for u128 {
type Error = WalletError;
fn try_from(value: Amount) -> std::result::Result<Self, Self::Error> {
value
.try_to_u128()
.ok_or_else(|| WalletError::InvalidAmount(format!("{value} does not fit in u128")))
}
}
impl TryFrom<Amount> for i128 {
type Error = WalletError;
fn try_from(value: Amount) -> std::result::Result<Self, Self::Error> {
value
.try_to_i128()
.ok_or_else(|| WalletError::InvalidAmount(format!("{value} does not fit in i128")))
}
}
impl fmt::Display for Amount {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl FromStr for Amount {
type Err = WalletError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
I256::from_str_prefixed(s)
.map(Self)
.map_err(|e| WalletError::InvalidAmount(format!("'{s}': {e}")))
}
}
impl Serialize for Amount {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
serializer.collect_str(&self.0)
}
}
impl<'de> Deserialize<'de> for Amount {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
Self::from_str(&s).map_err(serde::de::Error::custom)
}
}
pub fn parse_amount(s: &str) -> Result<Amount> {
Amount::from_str(s)
}
pub trait CoinRecipe {
fn token_type(&self) -> &TokenType;
fn value(&self) -> Amount;
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SimpleCoin {
pub token_type: TokenType,
pub value: Amount,
}
impl SimpleCoin {
#[inline]
#[must_use]
pub fn new(token_type: impl Into<TokenType>, value: impl Into<Amount>) -> Self {
Self {
token_type: token_type.into(),
value: value.into(),
}
}
}
impl CoinRecipe for SimpleCoin {
#[inline]
fn token_type(&self) -> &TokenType {
&self.token_type
}
#[inline]
fn value(&self) -> Amount {
self.value
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct TransactionCostModel {
pub input_fee_overhead: Amount,
pub output_fee_overhead: Amount,
}
impl TransactionCostModel {
#[inline]
#[must_use]
pub fn new(
input_fee_overhead: impl Into<Amount>,
output_fee_overhead: impl Into<Amount>,
) -> Self {
Self {
input_fee_overhead: input_fee_overhead.into(),
output_fee_overhead: output_fee_overhead.into(),
}
}
pub const ZERO: Self = Self {
input_fee_overhead: Amount::ZERO,
output_fee_overhead: Amount::ZERO,
};
}
impl From<ParseIntError> for WalletError {
fn from(e: ParseIntError) -> Self {
WalletError::InvalidAmount(e.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lifts_full_u128_range_without_overflow() {
let max_u128 = u128::MAX;
let amt = Amount::from_u128(max_u128);
assert!(amt.is_positive());
assert_eq!(amt.try_to_u128(), Some(max_u128));
}
#[test]
fn sum_of_two_max_u128_does_not_overflow() {
let a = Amount::from_u128(u128::MAX);
let b = Amount::from_u128(u128::MAX);
let sum = a + b;
let s = sum.to_string();
let expected: I256 = (I256::ONE << 129u8) - I256::from(2u32);
assert_eq!(sum.as_i256(), expected, "got {s}");
}
#[test]
fn negative_imbalance_round_trips() {
let inputs = Amount::from_u128(100);
let outputs = Amount::from_u128(150);
let imbalance = inputs - outputs;
assert!(imbalance.is_negative());
assert_eq!(imbalance, -Amount::from_u128(50));
}
#[test]
fn checked_add_returns_none_on_overflow() {
assert_eq!(Amount::MAX.checked_add(Amount::ONE), None);
}
#[test]
fn try_to_u128_rejects_negative() {
assert_eq!(Amount::from_i128(-1).try_to_u128(), None);
}
#[test]
fn try_to_u128_rejects_above_u128_max() {
let big = Amount::from_u128(u128::MAX) + Amount::ONE;
assert_eq!(big.try_to_u128(), None);
}
#[test]
fn try_to_i128_rejects_above_i128_max() {
let big = Amount::from_i128(i128::MAX) + Amount::ONE;
assert_eq!(big.try_to_i128(), None);
}
#[test]
fn try_to_i128_allows_full_i128_range() {
assert_eq!(Amount::from_i128(i128::MAX).try_to_i128(), Some(i128::MAX));
assert_eq!(Amount::from_i128(i128::MIN).try_to_i128(), Some(i128::MIN));
}
#[test]
fn display_round_trip() {
let a = Amount::from_u128(123_456_789_012_345_678_901_234_567_890_u128);
let s = a.to_string();
let b: Amount = s.parse().unwrap();
assert_eq!(a, b);
}
#[test]
fn negative_display_round_trip() {
let a = -Amount::from_u128(42);
let s = a.to_string();
assert_eq!(s, "-42");
let b: Amount = s.parse().unwrap();
assert_eq!(a, b);
}
#[test]
fn serde_uses_string_form() {
let a = Amount::from_u128(u128::MAX);
let json = serde_json::to_string(&a).unwrap();
assert!(json.starts_with('"'));
let back: Amount = serde_json::from_str(&json).unwrap();
assert_eq!(a, back);
}
#[test]
fn sum_iterator() {
let coins = [
Amount::from_u128(10),
Amount::from_u128(20),
Amount::from_u128(30),
];
let total: Amount = coins.iter().sum();
assert_eq!(total, Amount::from_u128(60));
}
}