1use std::fmt;
44use std::iter::Sum;
45use std::num::ParseIntError;
46use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
47use std::str::FromStr;
48
49use ethnum::I256;
50use serde::{Deserialize, Serialize};
51
52use crate::error::{Result, WalletError};
53
54#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
58#[serde(transparent)]
59pub struct TokenType(pub String);
60
61impl TokenType {
62 #[inline]
63 #[must_use]
64 pub fn new(s: impl Into<String>) -> Self {
65 Self(s.into())
66 }
67
68 #[inline]
69 #[must_use]
70 pub fn as_str(&self) -> &str {
71 &self.0
72 }
73}
74
75impl fmt::Display for TokenType {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 f.write_str(&self.0)
78 }
79}
80
81impl From<String> for TokenType {
82 #[inline]
83 fn from(s: String) -> Self {
84 Self(s)
85 }
86}
87
88impl From<&str> for TokenType {
89 #[inline]
90 fn from(s: &str) -> Self {
91 Self(s.to_owned())
92 }
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
111pub struct Amount(I256);
112
113impl Amount {
114 pub const ZERO: Self = Self(I256::ZERO);
116 pub const ONE: Self = Self(I256::ONE);
118 pub const NEG_ONE: Self = Self(I256::MINUS_ONE);
120 pub const MAX: Self = Self(I256::MAX);
122 pub const MIN: Self = Self(I256::MIN);
124
125 #[inline]
129 #[must_use]
130 pub fn from_u128(value: u128) -> Self {
131 Self(I256::from(value))
132 }
133
134 #[inline]
137 #[must_use]
138 pub fn from_i128(value: i128) -> Self {
139 Self(I256::from(value))
140 }
141
142 #[inline]
145 pub fn try_to_u128(self) -> Option<u128> {
146 if self.0 < I256::ZERO {
147 return None;
148 }
149 let (hi, lo) = self.0.into_words();
150 if hi != 0 {
151 return None;
152 }
153 Some(u128::from_ne_bytes(lo.to_ne_bytes()))
157 }
158
159 #[inline]
162 pub fn try_to_i128(self) -> Option<i128> {
163 let min = I256::from(i128::MIN);
164 let max = I256::from(i128::MAX);
165 if self.0 < min || self.0 > max {
166 return None;
167 }
168 let (_hi, lo) = self.0.into_words();
169 Some(lo)
170 }
171
172 #[inline]
175 #[must_use]
176 pub fn is_positive(self) -> bool {
177 self.0 > I256::ZERO
178 }
179
180 #[inline]
182 #[must_use]
183 pub fn is_negative(self) -> bool {
184 self.0 < I256::ZERO
185 }
186
187 #[inline]
189 #[must_use]
190 pub fn is_zero(self) -> bool {
191 self.0 == I256::ZERO
192 }
193
194 #[inline]
197 #[must_use]
198 pub fn abs(self) -> Self {
199 Self(self.0.checked_abs().unwrap_or(I256::MAX))
200 }
201
202 #[inline]
204 #[must_use]
205 pub fn checked_add(self, rhs: Self) -> Option<Self> {
206 self.0.checked_add(rhs.0).map(Self)
207 }
208
209 #[inline]
211 #[must_use]
212 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
213 self.0.checked_sub(rhs.0).map(Self)
214 }
215
216 #[inline]
218 #[must_use]
219 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
220 self.0.checked_mul(rhs.0).map(Self)
221 }
222
223 #[inline]
226 #[must_use]
227 pub fn checked_neg(self) -> Option<Self> {
228 self.0.checked_neg().map(Self)
229 }
230
231 #[inline]
234 #[must_use]
235 pub const fn as_i256(self) -> I256 {
236 self.0
237 }
238}
239
240impl Add for Amount {
243 type Output = Self;
244 #[inline]
245 fn add(self, rhs: Self) -> Self {
246 Self(self.0 + rhs.0)
247 }
248}
249
250impl Sub for Amount {
251 type Output = Self;
252 #[inline]
253 fn sub(self, rhs: Self) -> Self {
254 Self(self.0 - rhs.0)
255 }
256}
257
258impl Mul for Amount {
259 type Output = Self;
260 #[inline]
261 fn mul(self, rhs: Self) -> Self {
262 Self(self.0 * rhs.0)
263 }
264}
265
266impl Neg for Amount {
267 type Output = Self;
268 #[inline]
269 fn neg(self) -> Self {
270 Self(-self.0)
271 }
272}
273
274impl AddAssign for Amount {
275 #[inline]
276 fn add_assign(&mut self, rhs: Self) {
277 self.0 += rhs.0;
278 }
279}
280
281impl SubAssign for Amount {
282 #[inline]
283 fn sub_assign(&mut self, rhs: Self) {
284 self.0 -= rhs.0;
285 }
286}
287
288impl MulAssign for Amount {
289 #[inline]
290 fn mul_assign(&mut self, rhs: Self) {
291 self.0 *= rhs.0;
292 }
293}
294
295impl Sum for Amount {
296 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
297 iter.fold(Self::ZERO, Add::add)
298 }
299}
300
301impl<'a> Sum<&'a Amount> for Amount {
302 fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
303 iter.copied().fold(Self::ZERO, Add::add)
304 }
305}
306
307impl From<i128> for Amount {
310 #[inline]
311 fn from(v: i128) -> Self {
312 Self::from_i128(v)
313 }
314}
315
316impl From<u128> for Amount {
317 #[inline]
318 fn from(v: u128) -> Self {
319 Self::from_u128(v)
320 }
321}
322
323impl From<i64> for Amount {
324 #[inline]
325 fn from(v: i64) -> Self {
326 Self(I256::from(v))
327 }
328}
329
330impl From<u64> for Amount {
331 #[inline]
332 fn from(v: u64) -> Self {
333 Self(I256::from(v))
334 }
335}
336
337impl From<i32> for Amount {
338 #[inline]
339 fn from(v: i32) -> Self {
340 Self(I256::from(v))
341 }
342}
343
344impl From<u32> for Amount {
345 #[inline]
346 fn from(v: u32) -> Self {
347 Self(I256::from(v))
348 }
349}
350
351impl From<i16> for Amount {
352 #[inline]
353 fn from(v: i16) -> Self {
354 Self(I256::from(v))
355 }
356}
357
358impl From<u16> for Amount {
359 #[inline]
360 fn from(v: u16) -> Self {
361 Self(I256::from(v))
362 }
363}
364
365impl From<i8> for Amount {
366 #[inline]
367 fn from(v: i8) -> Self {
368 Self(I256::from(v))
369 }
370}
371
372impl From<u8> for Amount {
373 #[inline]
374 fn from(v: u8) -> Self {
375 Self(I256::from(v))
376 }
377}
378
379impl TryFrom<Amount> for u128 {
382 type Error = WalletError;
383
384 fn try_from(value: Amount) -> std::result::Result<Self, Self::Error> {
385 value
386 .try_to_u128()
387 .ok_or_else(|| WalletError::InvalidAmount(format!("{value} does not fit in u128")))
388 }
389}
390
391impl TryFrom<Amount> for i128 {
392 type Error = WalletError;
393
394 fn try_from(value: Amount) -> std::result::Result<Self, Self::Error> {
395 value
396 .try_to_i128()
397 .ok_or_else(|| WalletError::InvalidAmount(format!("{value} does not fit in i128")))
398 }
399}
400
401impl fmt::Display for Amount {
404 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405 fmt::Display::fmt(&self.0, f)
406 }
407}
408
409impl FromStr for Amount {
410 type Err = WalletError;
411
412 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
413 I256::from_str_prefixed(s)
414 .map(Self)
415 .map_err(|e| WalletError::InvalidAmount(format!("'{s}': {e}")))
416 }
417}
418
419impl Serialize for Amount {
426 fn serialize<S: serde::Serializer>(
427 &self,
428 serializer: S,
429 ) -> std::result::Result<S::Ok, S::Error> {
430 serializer.collect_str(&self.0)
431 }
432}
433
434impl<'de> Deserialize<'de> for Amount {
435 fn deserialize<D: serde::Deserializer<'de>>(
436 deserializer: D,
437 ) -> std::result::Result<Self, D::Error> {
438 let s = String::deserialize(deserializer)?;
439 Self::from_str(&s).map_err(serde::de::Error::custom)
440 }
441}
442
443pub fn parse_amount(s: &str) -> Result<Amount> {
449 Amount::from_str(s)
450}
451
452pub trait CoinRecipe {
458 fn token_type(&self) -> &TokenType;
459 fn value(&self) -> Amount;
460}
461
462#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
465pub struct SimpleCoin {
466 pub token_type: TokenType,
467 pub value: Amount,
468}
469
470impl SimpleCoin {
471 #[inline]
475 #[must_use]
476 pub fn new(token_type: impl Into<TokenType>, value: impl Into<Amount>) -> Self {
477 Self {
478 token_type: token_type.into(),
479 value: value.into(),
480 }
481 }
482}
483
484impl CoinRecipe for SimpleCoin {
485 #[inline]
486 fn token_type(&self) -> &TokenType {
487 &self.token_type
488 }
489
490 #[inline]
491 fn value(&self) -> Amount {
492 self.value
493 }
494}
495
496#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
505pub struct TransactionCostModel {
506 pub input_fee_overhead: Amount,
507 pub output_fee_overhead: Amount,
508}
509
510impl TransactionCostModel {
511 #[inline]
515 #[must_use]
516 pub fn new(
517 input_fee_overhead: impl Into<Amount>,
518 output_fee_overhead: impl Into<Amount>,
519 ) -> Self {
520 Self {
521 input_fee_overhead: input_fee_overhead.into(),
522 output_fee_overhead: output_fee_overhead.into(),
523 }
524 }
525
526 pub const ZERO: Self = Self {
528 input_fee_overhead: Amount::ZERO,
529 output_fee_overhead: Amount::ZERO,
530 };
531}
532
533impl From<ParseIntError> for WalletError {
538 fn from(e: ParseIntError) -> Self {
539 WalletError::InvalidAmount(e.to_string())
540 }
541}
542
543#[cfg(test)]
544mod tests {
545 use super::*;
546
547 #[test]
548 fn lifts_full_u128_range_without_overflow() {
549 let max_u128 = u128::MAX;
550 let amt = Amount::from_u128(max_u128);
551 assert!(amt.is_positive());
552 assert_eq!(amt.try_to_u128(), Some(max_u128));
553 }
554
555 #[test]
556 fn sum_of_two_max_u128_does_not_overflow() {
557 let a = Amount::from_u128(u128::MAX);
559 let b = Amount::from_u128(u128::MAX);
560 let sum = a + b;
561 let s = sum.to_string();
563 let expected: I256 = (I256::ONE << 129u8) - I256::from(2u32);
565 assert_eq!(sum.as_i256(), expected, "got {s}");
566 }
567
568 #[test]
569 fn negative_imbalance_round_trips() {
570 let inputs = Amount::from_u128(100);
571 let outputs = Amount::from_u128(150);
572 let imbalance = inputs - outputs;
573 assert!(imbalance.is_negative());
574 assert_eq!(imbalance, -Amount::from_u128(50));
575 }
576
577 #[test]
578 fn checked_add_returns_none_on_overflow() {
579 assert_eq!(Amount::MAX.checked_add(Amount::ONE), None);
581 }
582
583 #[test]
584 fn try_to_u128_rejects_negative() {
585 assert_eq!(Amount::from_i128(-1).try_to_u128(), None);
586 }
587
588 #[test]
589 fn try_to_u128_rejects_above_u128_max() {
590 let big = Amount::from_u128(u128::MAX) + Amount::ONE;
591 assert_eq!(big.try_to_u128(), None);
592 }
593
594 #[test]
595 fn try_to_i128_rejects_above_i128_max() {
596 let big = Amount::from_i128(i128::MAX) + Amount::ONE;
597 assert_eq!(big.try_to_i128(), None);
598 }
599
600 #[test]
601 fn try_to_i128_allows_full_i128_range() {
602 assert_eq!(Amount::from_i128(i128::MAX).try_to_i128(), Some(i128::MAX));
603 assert_eq!(Amount::from_i128(i128::MIN).try_to_i128(), Some(i128::MIN));
604 }
605
606 #[test]
607 fn display_round_trip() {
608 let a = Amount::from_u128(123_456_789_012_345_678_901_234_567_890_u128);
609 let s = a.to_string();
610 let b: Amount = s.parse().unwrap();
611 assert_eq!(a, b);
612 }
613
614 #[test]
615 fn negative_display_round_trip() {
616 let a = -Amount::from_u128(42);
617 let s = a.to_string();
618 assert_eq!(s, "-42");
619 let b: Amount = s.parse().unwrap();
620 assert_eq!(a, b);
621 }
622
623 #[test]
624 fn serde_uses_string_form() {
625 let a = Amount::from_u128(u128::MAX);
626 let json = serde_json::to_string(&a).unwrap();
627 assert!(json.starts_with('"'));
629 let back: Amount = serde_json::from_str(&json).unwrap();
630 assert_eq!(a, back);
631 }
632
633 #[test]
634 fn sum_iterator() {
635 let coins = [
636 Amount::from_u128(10),
637 Amount::from_u128(20),
638 Amount::from_u128(30),
639 ];
640 let total: Amount = coins.iter().sum();
641 assert_eq!(total, Amount::from_u128(60));
642 }
643}